
    Ng                    J   U d Z 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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mZmZmZmZmZ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(m)Z)m*Z*m+Z+m,Z, ddl-m.Z/ ddl-m0Z0m1Z1m2Z2 dd	l3m4Z5 dd
l6m7Z7 erddl8m9Z9 ddl:m;Z;  e	j<        e=          Z> ej?        ee0j@                          dd          ZA ej?        eeB                  dd          ZC ej?        eeeB                           dd          ZD ej?        eeeBef                           dd          ZE ej?        ee#eFed         f                           dd          ZG ej?        ee/jH                          dd          ZIeAeCeDeEeGeIdZJdeKd<   ddZL	 dddZMejN        ddddddddd/            ZOeLZPdd2ZQddddddddd3dd>ZRddAZS G dB dCe!dDE          ZT e"dFdGH          ZU e)dI          ZVe& G dJ dKeeeVeUf                               ZWe%ddL            ZXe%	 dddddddddddN	ddS            ZXddVZX G dW dX          ZYddYZZdd\Z[h d]Z\ G d^ d_e!dDE          Z] G d` dae!dDE          Z^	 	 dddhZ_ddlZ`	 dddoZa	 	 	 dddrZb	 	 	 dddtZcdduZdddxZeddyZf ejg        dz{          dd}            ZhddZiddZjddZkddZl e"d          Zm G d deem                   Zn G d deneem                   Zo G d deneem                   ZpddZqdS )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]c                 4    t                                           S )zGet the current run tree.)r,   get     Q/var/www/html/ai-engine/env/lib/python3.11/site-packages/langsmith/run_helpers.pyget_current_run_treerC   N   s    !!!rA   contextOptional[contextvars.Context]Dict[str, Any]c                x     t                                           t                                          t                                          t                                          t
                                          t                                          dS  fdt                                          D             S )z Get the current tracing context.Nr5   c                B    i | ]\  }}|                     |          S r@   r?   ).0kvrD   s      rB   
<dictcomp>z'get_tracing_context.<locals>.<dictcomp>`   s)    @@@$!QAw{{1~~@@@rA   )	r,   r?   r/   r0   r1   r3   r4   r;   itemsrD   s   `rB   get_tracing_contextrP   S   s     &**,,)--//IIKK!'++--kkmm
 
 	
 A@@@-*=*=*?*?@@@@rA   )r7   r8   r9   r6   r:   r$   r7   Optional[str]r8   Optional[List[str]]r9   Optional[Dict[str, Any]]r6   0Optional[Union[run_trees.RunTree, Mapping, str]]r:   'Optional[Union[bool, Literal['local']]]r$   Optional[ls_client.Client]kwargsr   Generator[None, None, None]c           	   +    K   |rt          j        d| dt                     t                      }t	          d|p|                    d          i          }|Bt          t          |pg           t          |j        pg           z            }i |j	        |pi }||n|                    d          }t          || ||||d           	 dV  t          |           dS # t          |           w xY 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: .r6   
parent_runNr:   r5   )warningswarnDeprecationWarningrP   _get_parent_runr?   sortedsetr8   r9   _set_tracing_context)	r7   r8   r9   r6   r:   r$   rW   current_contextr[   s	            rB   tracing_contextrd   c   s-     4  
8v888	
 	
 	
 *++O (F,Nfjj6N6N!OPPJc$*"ooJO,Ar(B(BBCC>j)>hn"> ,gg/2E2Ei2P2PG ( 	
 	
	 	 	._-----_----s   C   C1func'TypeGuard[SupportsLangsmithExtra[P, R]]c                    t          |           pQt          | t          j                  ot          | j                  p#t          | d          ot          | j                  S )z,Check if a function is @traceable decorated.__call__)_is_traceable_function
isinstance	functoolspartialre   hasattrrh   re   s    rB   is_traceable_functionro      s]     	t$$ 	QtY.//U4J494U4U	QD*%%O*@*O*OrA   namer9   r8   r$   	reduce_fnr7   process_inputsprocess_outputsCallable[P, R]rq   Optional[Mapping[str, Any]]rr   $Optional[Callable[[Sequence], dict]]rs    Optional[Callable[[dict], dict]]rt   Optional[Callable[..., dict]]SupportsLangsmithExtra[P, R]c               d    t          |           r| S  t          ||||||||          |           S )z$Ensure that a function is traceable.rp   )ro   	traceable)	re   rq   r9   r8   r$   rr   r7   rs   rt   s	            rB   ensure_traceabler}      s[     T"" 	9!%'	 	 	 	 	 	rA   r
   boolc                |    t          j        |           p(t          | d          ot          j        | j                  S )z;Inspect function or wrapped function to see if it is async.__wrapped__)inspectiscoroutinefunctionrm   r   rn   s    rB   is_asyncr      s:    &t,, m$$V)DTEU)V)VrA   c                      e Zd ZU dZ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ed<   	 ded<   dS )LangSmithExtraz<Any additional info to be injected into the run dynamically.rQ   rq   Optional[ls_client.ID_TYPE]reference_example_idOptional[Dict]	run_extra0Optional[Union[run_trees.RunTree, str, Mapping]]r6   r=   run_treer7   rS   r9   rR   r8   run_idrV   r$   ,Optional[Callable[[run_trees.RunTree], Any]]on_endN__name__
__module____qualname____doc____annotations__r@   rA   rB   r   r      s         FF$5555-.<<<<D)))))'&&&&(,''''"&&&&$8888DDrA   r   F)totalRT)	covariantPc                       e Zd ZdZddddZdS )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]rW   P.kwargsr<   r   c                   dS )aj  Call 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   rW   s       rB   rh   zSupportsLangsmithExtra.__call__   s	    $ 	rA   )r   r   r   r   rW   r   r<   r   )r   r   r   r   rh   r@   rA   rB   r   r      sA        
 
 59       rA   r   c                    d S Nr@   rn   s    rB   r|   r|   
  s	     $'3rA   chain)	rq   r9   r8   r$   rr   r7   rs   rt   _invocation_params_fnrun_typels_client.RUN_TYPE_Tr   8Callable[[Callable[P, R]], SupportsLangsmithExtra[P, R]]c       	            d S r   r@   )
r   rq   r9   r8   r$   rr   r7   rs   rt   r   s
             rB   r|   r|     s     @CsrA   r   /Union[Callable, Callable[[Callable], Callable]]c                    t          t          j        | r#t          | d         t                    r| d         n|                    dd          pd          t          vr#t          j        d dt           d d           t          |           d	k    rt          j        d
           d|v rt          j        dt                     |                    dd          t          |                    dd          |                    dd          |                    dd          |                    dd          |                    dd          |                    dd          |                    dd          |                    dd          	  	        |                    dd          }t          j        t          |          |r=t          j        dt          |                                           dt                     dfd}t          |           d	k    r(t#          | d                   r|s || d                   S |S )a  Trace 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.

    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"}})
    r   r   Nr   zUnrecognized run_type: z. Must be one of: z . Did you mean @traceable(name='z')?   zThe `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.rr   rq   r9   r8   r$   r7   rs   r   )	extra_outerrq   r9   r8   r$   r7   r   rs   invocation_params_fnrt   )outputs_processorzHThe following keyword arguments are not recognized and will be ignored: rZ   re   r
   c           	        
 t          j                   }|j                            dd           d u|j                            dd           d u
t	          j                   d dd 
fd
            }t	          j                   d dd 
fd            }t	          j                   d dd 
fd            }t	          j                   d dd 
fd            }t	          j                   d dd 
fd            }t	          j                   d dd 
fd            }t          j                   r|}n5t          j                   r|}nt                     rr|}n
|}nr|}n|}t          |dd           t          j        |          }	|	j                            d          s|	
                    g d |	j                                        D             t          j        dt           j        j        d           d |	j                                        D                       }	|	|_        |S )Nr   configr   r   r   r   r   rW   r<   c                b  K   t          j        t          
	| ||           d{V }	 t          j                    }r|d         |d<   s|                    dd            
|i |}|r#t          j        ||d                    d{V }n?t          d
i t          |d                   5  | d{V }ddd           n# 1 swxY w Y   nC# t          $ r6}t          j
        t          j        ||                     d{V  |d}~ww xY wt          j        ||	           d{V  |S )z"Async version of wrapper function.container_inputr   r   rW   Nnew_runr   r   rD   rO   erroroutputsr@   )
aitertoolsaio_to_thread
_setup_runasyncio_accepts_contextpopasynciocreate_taskrd   rP   BaseExceptionshield)r   r   rW   run_containeraccepts_contextfr_corofunction_resulte_on_run_endr   re   func_accepts_configfunc_accepts_parent_runs           rB   async_wrapperz3traceable.<locals>.decorator.<locals>.async_wrapper  sA      #-": / /# # #      M","D"F"F* B)6y)AF:&* /JJx...$///" 	8,3,?y)A- - - ' ' ' ' ' 'OO
 )  -mI.FGG  8 8 18------8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 !   n,[-qQQQ          *]O          #"s<   BC .	C7C CC 
CC 
D1D

Dr   c               >  K   t          j        t          
| ||           d {V }g }	 r|d         |d<   s|                    dd             |i |}t          j                    }t          j        |          rd|r#t          j        ||d                    d {V }n?t          di t          |d                   5  | d {V }d d d            n# 1 swxY w Y   t          |||d         r|d         j        dk    nd||	          2 3 d {V }|W V  6 nR# t          $ rE}t          j        t          j        	||t          |          
                     d {V  |d }~ww xY wt          j        	|t          |                     d {V  d S )Nr   r   r   r   rD   rO   llmF	generatorr   
is_llm_runr   resultsr   r   r   r@   )r   r   r   r   r   r   iscoroutiner   r   rd   rP   _process_async_iteratorr   r   r   _get_function_result)r   r   rW   r   r   async_gen_resultr   itemr   r   r   re   r   r   rr   s            rB   async_generator_wrapperz=traceable.<locals>.decorator.<locals>.async_generator_wrapper  s!      #-": / /# # #      M "$G,* B)6y)AF:& + /JJx...#'4#8#8#8 ","D"F"F&'788 
F& 	F181D,mI6N2 2 2 , , , , , ,((
 -  1-	2JKK  F F 6F/E/E/E/E/E/E,F F F F F F F F F F F F F F F
 #:."/ )3#i09UBB"$3#
# 
# 
#       $ JJJJJ
# 
# ! 	 	 	n,#% 4Wi H H	           	 *,Wi@@           sI   BD  	CD  CD   C!0D  DD   
E/*A E**E/c                f   t          	| ||          }t          j        	          j                            dd          du}	 |r|d         |d<   
s|                    dd            |d         j        	g|R i |}n!# t          $ r} ||           |d}~ww xY w ||           |S )	>Create a new run or create_child() if run is passed in kwargs.r   r   Nr   r   rD   r   r   )r   r   	signature
parametersr?   r   runr   )r   r   rW   r   r   r   r   r   r   re   r   s          rB   wrapperz-traceable.<locals>.decorator.<locals>.wrapperP  s    ' / /  M !$''266z4HHPTT $* B)6y)AF:&* /JJx...">-	":">t"Ud"U"U"Uf"U"U    M3333 K????""s   <B 
B!BB!c           	   ?    K   t          
| ||          }t          j                  j                            dd           d u}g }d }	 |r|d         |d<   s|                    dd             |d         j        g|R i |}t          ||dk    |          E d {V }||                    |           n0# t          $ r#} 	||t          |                     |d }~ww xY w 	|t          |          	           |S )
Nr   r   r   r   rD   r   r   r   r   r   )r   r   r   r   r?   r   r   _process_iteratorappendr   r   )r   r   rW   r   r   r   function_returngenerator_resultr   r   r   re   r   rr   r   s            rB   generator_wrapperz7traceable.<locals>.decorator.<locals>.generator_wrapperm  s      ' / /  M !$''266z4HHPTT $ "$G#'O* B)6y)AF:&* /JJx...#?=#;#?#Vt#V#V#Vv#V#V ->$!'50#	. . . # # # # # # #.NN?333    !0)DD   
  K/CGY/W/WXXXX""s   A0B= =
C*C%%C*c                   t          | ||          }	 
r|d         |d<   	s|                    dd             |d         j        g|R i |}n # t          $ r} ||            d }~ww xY wt	          |d          rt          ||          S t	          |d          rt          ||          S  ||	           |S )
Nr   r   r   r   rD   r   __iter__	__aiter__r   )r   r   r   	Exceptionrm   _TracedStream_TracedAsyncStreamr   r   rW   trace_containerstreamr   r   r   re   r   r   rr   s         rB   stream_wrapperz4traceable.<locals>.decorator.<locals>.stream_wrapper  s)    ) / /  O* D)8)CF:&* /JJx...737NtNNNvNN   O15555 vz** N$V_iHHH-- N)&/9MMM K8888Ms   <A 
A1A,,A1c                  K   t          j        t          | ||           d {V }	 
r|d         |d<   	s|                    dd             |i | d {V }n0# t          $ r#}t          j        ||           d {V   d }~ww xY wt          |d          rt          ||          S t          |d          rt          ||          S t          j        ||           d {V  |S )	Nr   r   r   r   r   r   r   r   )r   r   r   r   r   rm   r   r   r   s         rB   async_stream_wrapperz:traceable.<locals>.decorator.<locals>.async_stream_wrapper  s|      %/$< / /% % %      O* D)8)CF:&* /JJx...#tT4V44444444    .{OSTUUUUUUUUUU v{++ I)&/9MMM,, I$V_iHHH *;QWXXXXXXXXXXMs   3A 
B(BB__langsmith_traceable__Tc              3  N   K   | ] }|j         t          j        j        k    |V  !d S r   kindr   	ParameterVAR_KEYWORDrJ   params     rB   	<genexpr>z/traceable.<locals>.decorator.<locals>.<genexpr>  A        ! :):)FFF FFFF rA   r-   c              3  N   K   | ] }|j         t          j        j        k    |V  !d S r   r   r   s     rB   r   z/traceable.<locals>.decorator.<locals>.<genexpr>  r   rA   )r   )r   r   r   r   rW   r   r<   r   )r   r   r   r   rW   r   r<   r   )r   r   r   r?   rk   wrapsisasyncgenfunctionisgeneratorfunctionr   setattrreplacevaluesr   KEYWORD_ONLY__signature__)re   func_sigr   r   r   r   r   r   selected_wrappersigr   r   r   r   rr   r   s   `         @@rB   	decoratorztraceable.<locals>.decorator  s   $T**"*"5"9"9*d"K"KSW"W&155hEETQ			 9=)	# )	# )	# )	# )	# )	# )	# )	# )	# )	# )	# 
	)	#V 
		DH=	 =	 =	 =	 =	 =	 =	 =	 =	 =	 =	 =	 
	=	~ 
		 9=	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 
		#8 
		DH)	# )	# )	# )	# )	# )	# )	# )	# )	# )	# )	# )	# 
	)	#\ 
		DH	 	 	 	 	 	 	 	 	 	 	 	 
		> 
		DH	 	 	 	 	 	 	 	 	 	 	 	 
		@ %d++ 	+)@(.. 	+0d^^ 		+ 1#7  #0   +#1  #*  ";TBBB 011~!!(++ 	1++ %(^%:%:%<%<   % '"3"@$   %(^%:%:%<%<     C" .1*rA   )re   r
   )r   	ls_client
RUN_TYPE_Trj   strr   _VALID_RUN_TYPESr\   r]   lenr^   _ContainerInputrk   rl   _handle_container_endr`   keyscallable)r   rW   r   r
  r   r   rr   r   s       @@@@rB   r|   r|      s   Z  ;"47C00;DGG**Z..9' H '''<h < <BR < <.6< < <	
 	
 	
 4yy1}}$	
 	
 	

 &	
 	
 	

 

;--I%JJw--ZZ%%J--ZZ%%zz(D))ZZ55zz"2D99#ZZ(?FF  O 

#4d;;#1B  K  
(fkkmm$$( ( (	
 	
 	
a  a  a  a  a  a  a  a  a J	 4yyA~~(47++~F~ya!!!rA   c                  x    e Zd ZdZ	 d/ddddddddddddd0dZd1d"Zd2d*Zd1d+Z	 	 	 d3d2d,Zd1d-Z		 	 	 d3d2d.Z
dS )4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   r7   r6   r8   r9   r$   r   r   exceptions_to_handleattachmentsrq   r  r   r   r  r   r   r7   rQ   r6   r   r8   rR   r9   rv   r$   rV   r   r   r   r  )Optional[Tuple[Type[BaseException], ...]]r  Optional[schemas.Attachments]rW   r   c                  |r=t          j        dt          |                                           dt                     || _        || _        || _        || _        || _	        || _
        || _        |                    d          | _        || _        || _        |	| _        |
| _        || _        || _        d| _        d| _        dS )z_Initialize the trace context manager.

        Warns if unsupported kwargs are passed.
        zEThe `trace` context manager no longer supports the following kwargs: rZ   r   N)r\   r]   r`   r  r^   rq   r   r  r  r   r7   r6   r?   r   r8   r9   r$   r   r   r  r   old_ctx)r   rq   r   r  r   r7   r6   r8   r9   r$   r   r   r  r  rW   s                  rB   __init__ztrace.__init__@  s    ,  	M,&++--((, , ,"  
 	 &
( 

:..	 $8!$8!48'+rA   r<   run_trees.RunTreec                   t                      | _        t          j        | j                  }t                                          }t                                          }| j        p| j                            d          }t          | j	        | j
        |d          }t          t          | j        pg |pg z                       }i | j        pi |pi ddi}| j        pi }||d<   t!          | j                  }	|=|r;|                    | j        | j        | j        || j        || j                  | _        nmt3          j        | j        t7          j        | j                  t7          j        | j        d	          | j        ||	pd
| j        pi ||| j        pi 
  
        | _        |du r| j                                         |rt                              |           t                              |           t>                              | j                   t@                              |	           tB                              |           | j        S )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$   )r6   r   r$   	ls_methodr  r9   N)rq   r   r   r   r  r8   r  Taccept_nullr.   )
rq   idr   r   r   r7   r  r8   r$   r  )"rP   r  r'   tracing_is_enabledr0   r?   r1   r$   r_   r6   r   r`   ra   r8   r9   r   _get_project_namer7   create_childrq   r   r   r  r  r   r%   RunTreer  _ensure_uuidr   postr,   r/   r4   )
r   r:   
outer_tagsouter_metadataclient_parent_run_tags_r9   r   project_name_s
             rB   _setupztrace._setupo  sT    +,,*4<88YY[[
"+;!1!1(!;!;%+ M! 
 
 sDIO
0@bABBCC
}"
#
 
 
 j&B"*J)$*;<<"w"&33Y{!{ , 4  DLL %,Y)$+66%.%;-4& & & !*7i{(b ,2  DL d??L 	!IIeMM(###  ...m,,,KK   |rA   exc_typeOptional[Type[BaseException]]	exc_valueOptional[BaseException]	tracebackOptional[TracebackType]Nonec                   | j         dS |\| j        rt          || j                  rd}n"t          j                    }|j         d| d| }| j                             |           | j        Lt          j        | j                  }|du r| j         	                                 t          | j                   dS t          j        dt                     dS )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  r$  patchrb   r\   r]   RuntimeWarning)r   r1  r3  r5  tbr:   s         rB   	_teardownztrace._teardown  s      <F( AZ$3. . A &(( )@@Y@@B@@L2&&&<#.t|<<G$""$$$ .....MDnUUUUUrA   c                *    |                                  S )zyEnter the context manager synchronously.

        Returns:
            run_trees.RunTree: The newly created run.
        )r0  r   s    rB   	__enter__ztrace.__enter__  s     {{}}rA   c                4    |                      |||           dS )a  Exit 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)rA  )r   r1  r3  r5  s       rB   __exit__ztrace.__exit__  s      	xI66666rA   c                   K   t                      }t          j        | j        |           d{V }t	          t          |                     |S )zzEnter the context manager asynchronously.

        Returns:
            run_trees.RunTree: The newly created run.
        __ctxN)r   r   r   r0  rb   rP   )r   ctxresults      rB   
__aenter__ztrace.__aenter__  sV       nn!/3GGGGGGGGG055666rA   c           	       K   t                      }|7t          j        t          j        | j        ||||                     d{V  n$t          j        | j        ||||           d{V  t          t          |                     dS )a  Exit 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.
        NrH  )r   r   r   r   r   rA  rb   rP   )r   r1  r3  r5  rJ  s        rB   	__aexit__ztrace.__aexit__  s       nn.(NHi#            *)Yc          	05566666rA   r   )rq   r  r   r   r  r   r   r   r7   rQ   r6   r   r8   rR   r9   rv   r$   rV   r   r   r   r   r  r  r  r  rW   r   )r<   r  )r1  r2  r3  r4  r5  r6  r<   r7  NNN)r   r   r   r   r  r0  rA  rD  rF  rL  rN  r@   rA   rB   r  r  
  s       3 3p *1-,
 "& $&*CG$(04-1.2<@JN59-, -, -, -, -, -,^G G G GR"V "V "V "VH    37-1-1	7 7 7 7 7
 
 
 
 37-1-1	7 7 7 7 7 7 7rA   r  c                    t                                           }t                                          p|r|j        nd p| pt	          j                    S r   )r,   r?   r/   session_namer'   get_tracer_project)r7   prts     rB   r%  r%    s[    



 
 C 	 	& #-C	& 	&
 #%%rA   traceable_fnr+   c                B   	 ddl mm} ddlmm n"# t          $ r}t          d          |d}~ww xY wt          |           s=	 t          j	        |           }n# t          $ r d}Y nw xY wt          d|  d|            G f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:
c                  n     e Zd ZdZ	 dd fd	Zedfd            Zedfd            Z xZS )&as_runnable.<locals>.RunnableTraceablezConverts a @traceable decorated function to a Runnable.

        This helps maintain a consistent LangSmith tracing context.
        Nre   r
   afunc*Optional[Callable[..., Awaitable[Output]]]r<   r7  c           
     B   d }|                      |          }t          |          rC|t          d          t          t          gf         |                      |                    }n@t          |          r1t          t          gf         |                     |                    }|t          | j        j	         d|           t                                          |t          t          t          gt                   f                  |                     d S )NzFunc 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   	TypeErrorr   r
   ro   
_wrap_sync
ValueError	__class__r   superr  r   r	   )r   re   r]  wrappedawrappedrY  rZ  rd  s        rB   r  z/as_runnable.<locals>.RunnableTraceable.__init__T  s7   
 <@G''..H~~ 	Q'#7  
 x8$:J:J4:P:PQQ&t,, Qx8$//$:O:OPP ~. 9 9269 9   GGXugy/@&@AB     rA   Callable[..., Output])Callable[[Input, RunnableConfig], Output]c                P     d fd}t          t          gf         |          S )	z4Wrap a synchronous function to make it asynchronous.r  dictr   rW  r<   r   c                    t           j                            t          t          |                    } di | dd|iiS Nr   r   r@   r%   r'  from_runnable_configr   rk  )r  r   r   re   s      rB   wrap_traceablezIas_runnable.<locals>.RunnableTraceable._wrap_sync.<locals>.wrap_traceablez  sI    $,AA$tVBTBTUUtMMfMMz86LMMMMrA   r  rk  r   rW  r<   r   )r   r
   )re   rp  rY  rZ  rW  s   ` rB   rb  z1as_runnable.<locals>.RunnableTraceable._wrap_synct  sI    N N N N N N %!8&!@A>RRRrA   >Optional[Callable[[Input, RunnableConfig], Awaitable[Output]]]c                    | dS t          |           st          d|            t          t          dt                   f         |           dfd
}t          t          gt                   f         |          S )z.Wrap an async function to make it synchronous.NzXRunnableTraceable expects a function wrapped by the LangSmith @traceable decorator. Got .r  rk  r   rW  r<   r   c                   K   t           j                            t          t          |                    } di | dd|ii d {V S rm  rn  )r  r   r   afunc_s      rB   awrap_traceablezKas_runnable.<locals>.RunnableTraceable._wrap_async.<locals>.awrap_traceable  s_      $,AA$tVBTBTUU#VUUfUUz8>TUUUUUUUUUUrA   rq  )ro   rc  r   r
   r	   )r]  rv  ru  rY  rZ  rW  s     @rB   r`  z2as_runnable.<locals>.RunnableTraceable._wrap_async  s    
 }t(//  :27: :   (3	&(9#9:EBBFV V V V V V %0)F2CCDo  rA   r   )re   r
   r]  r^  r<   r7  )re   rh  r<   ri  )r]  r^  r<   rr  )	r   r   r   r   r  staticmethodrb  r`  __classcell__)rd  rY  rZ  rW  s   @rB   RunnableTraceabler\  N  s        	 	 AE	 	 	 	 	 	 	 	 	@ 
		S 		S 		S 		S 		S 		S 		S 
		S 
	 	 	 	 	 	 	 
	 	 	 	 	rA   ry  )langchain_core.runnablesrW  rX  langchain_core.runnables.utilsrY  rZ  ImportErrorro   r   	getsourcer   rc  )rU  rX  r   fn_srcry  rY  rZ  rW  s        @@@rB   as_runnabler  '  sZ   *KKKKKKKK@@@@@@@@@   D
 
 	
 !.. 
	,&|44FF 	, 	, 	,+FFF	,O*6O OFLO O
 
 	

G G G G G G G G GN G G GR \***s"    
505A A,+A,>   r   toolr   parserprompt	embedding	retrieverc                  Z    e Zd ZU dZded<   ded<   ded<   ded<   d	ed
<   ded<   ded<   dS )_TraceableContainer3Typed response when initializing a run a traceable.r=   r   rQ   r7   outer_projectrS   r+  rR   r*  r   r   zcontextvars.ContextrD   Nr   r@   rA   rB   r  r    sl         ==((((    ,,,,####8888      rA   r  c                  x    e Zd ZU dZ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ed<   dS )r  r  r   r   rQ   rq   rS   r9   rR   r8   rV   r$   Optional[Callable]rr   r7   r   r   rx   rs   r   Nr   r@   rA   rB   r  r    s         ==&&&&&&&&!!!!""""4444::::::rA   r  	containerr   Optional[Any]r   r4  r7  c                   |                      d          }|dS t          |t                    r|nd|i}d}|r't          j                    }t          |           d| }|                    ||           t          j                    du r|                                 |                      d          }|Rt          |          rE	  ||           dS # t          $ r(}t                              d|            Y d}~dS d}~ww xY wdS dS )	zEnd the run.r   Noutputr:  r   r   Tr   zFailed to run on_end function: )r?   rj   rk  r'   r<  reprr=  r$  r>  r  r   LOGGERwarning)	r  r   r   r   outputs_error_
stacktracer   r   s	            rB   _container_endr    sI    }}Y''H$Wd33Lww(G9LHF 2&((
KK11Z11LLL000!!T))]]8$$Fhv..	BF8 	B 	B 	BNN@Q@@AAAAAAAAA	B s   C 
DDDr   rk  r   c                H    |                     dd           }|ri | |}n| }|S )Nr   rI   )r   r   r   extra_inners       rB   _collect_extrar    s;    ##K66I "22	2!rA   r   Optional[dict]c           	     J   |                      d          }t          |t          j                  r|S t          |t                    rUt          j                            ||                      d          t          |                      d                              S t          |t                    rWt          j                            ||                      d          t          |                      d                              }|S |                      d          }|r|S t                      }t          j                    at          j                            ||                      d                    x}r+|r'||                     d          s|j        |j        k    r|S |S )Nr6   r$   r7   )r$   r7   r   r#   	callbacks)r?   rj   r%   r'  rk  from_headersr%  r  from_dotted_orderrC   r)   get_langchain_core_versionro  dotted_order)r   r   r6   dortr   crtrts          rB   r_   r_     s      **F&)+,, &$ 
 --"&&x00*?+>+>~+N+NOO	 . 
 
 	
 &#  22"&&x00*?+>+>~+N+NOO	 3 
 
 "":..H 

 
 C.00<"77?..x88 8 
 
 
2 	  &6::k+B+B& ?S%555	JrA   r   r   c                x   |                     d          pi }|                     d          }|                     d          }|                     d          }|                     d          pd}	t                                           }
|pt                      }|                     d          p|                     d          }|                     d|          pt                                           }t	          i |d|i|                     d                    }t                                           }|p:|r|j        nd	p/|                     d
          p|d
         pt          j                    }|                     d          }|                     d          }|sgt          j                    sTt          j	        t          j        d           t          d	||
d	d	|                     d          t                                S |pt          t          j                              }t#          j        |           }|pt          j        |           }| j        }t+          ||          }t,                                           }t.                                           }t                      }i |                     d          pi |pi }|                    t,          j        |           |                    |pi            d|d<   ||d<   t7          |g|R i |\  }}|                     d          }|r	 d  ||                                          D             }|r*t;          |t<                    r|                    |           n7# t>          $ r*}t@          !                    d| d|            Y d	}~nd	}~ww xY w|                     d          }|rD	  ||          }n7# t>          $ r*}t@          !                    d| d|            Y d	}~nd	}~ww xY w|                     d          pg |pg z   } |                    t.          j        |            | |pg z  } |/|"                    ||	|t          |          |d|| |||          }!nVtG          j$        tK          j&        |          ||t          |          |d||	tK          j&        |d          ||| ||          }!t          j                    du rR	 |!'                                 n<# t>          $ r/}t@          !                    d|!j(         d|            Y d	}~nd	}~ww xY wt          |!||
|||                     d          |          }"|                    t          j        |"d
                    |                    tR          j        |"d                    |"S )r   r   r9   r8   r$   r   r   rq   r   Nr7   r   r   z>LangSmith tracing is not enabled, returning original function.r   )r   r7   r  r+  r*  r   rD   r|   r   r   c                    i | ]
\  }}|||S r   r@   )rJ   rK   rL   s      rB   rM   z_setup_run.<locals>.<dictcomp>X  s&     ! ! !A1rA   z&Failed to infer invocation params for r9  rs   zFailed to filter inputs for )rq   r   doc)rq   r   
serializedr  r8   r   r   r  Tr!  )r#  rq   r  r  r   r   r7   r   r8   r$   r  zFailed to post run r   )*r?   r/   r   r4   r_   rR  r'   rS  r$  log_onceloggingDEBUGr  r   r  uuiduuid4r   r   _get_function_namer   r  r1   r0   r   ra   update _get_inputs_and_attachments_saferN   rj   rk  r   r  r   r&  r%   r'  r  r(  r)  r#  r,   )#re   r   r   r   rW   r   r9   r8   r$   r   r  rq   r,  r-  
project_cvselected_projectr   id_r   name_	docstringr  r+  r*  rD   	metadata_r  r  r   invocation_paramsr   rs   r.  r   response_containers#                                      rB   r   r     s    "%%m44:K"":..Hv&&D  **F"":..9'H!%%''M%9)9)9Ov&&E/*=*=f*E*ED!!(F33Dw{{}}G!.?.Hg..

80D0D K ""$$J 	&(3=K$$	& ~..		&
 >*	& #%%  +../EFF


h
'
'C 
u799 
ML	
 	
 	
 #)'"&&x00 NN
 
 
 	
 
"TZ\\""C!$''I2E,T22EI o>>K]]__NJnnGz**0bRI KK	y)))X^$$$(Ik'K
:9VtVVVvVVFK*../EFF P	P! !!5!5f!=!=!C!C!E!E! ! ! ! 4Z0A4%H%H 4  !2333 	P 	P 	PLLN%NN1NNOOOOOOOO	P$(()9::N F	F#^F++FF 	F 	F 	FLLDDDDDEEEEEEEE	F  ((.B:3CDEKK	5!!!	TZRE** ^^  
 # + 
 
 #%c** ^^  
 !*!7$$" " " *##
 
 
& !!T))	BLLNNNN 	B 	B 	BLL@wz@@Q@@AAAAAAAA	B,%#%""8,,   KK!#5n#EFFFKK $&8&CDDDsI   .AN 
N6 N11N6O 
P' PP4T	 	
U%T==Ur   c                    	 | ||          }t          | ||           dS # t          $ r5}t                              dt	          |                      Y d}~dS d}~ww xY w)zHandle the end of run.Nr  z!Unable to process trace outputs: )r  r   r  r  r  )r  r   r   r   r   s        rB   r  r    s    F(''00Gy'?????? F F FD477DDEEEEEEEEEFs   # 
A"*AA"c                $    t          | dd          S )Nr   F)getattrrn   s    rB   ri   ri     s    42E:::rA   r   inspect.Signaturec                    | j         |i |}|                                 t          |j                  }|                    dd           |                    dd           | j                                        D ]S\  }}|j        t          j	        j
        k    r4||v r0|                    ||                    |                    |           T|S )z:Return a dictionary of inputs from the function signature.r   Ncls)bind_partialapply_defaultsrk  	argumentsr   r   rN   r   r   r   r   r  )r   r   rW   boundr  
param_namer   s          rB   _get_inputsr    s     #I"D3F33E	U_%%IMM&$MM%&17799 * *
E:*666 Y&&  :!6777j)))rA   c                    	 t          | g|R i |S # t          $ r/}t                              d|  d|            ||dcY d }~S d }~ww xY wNzFailed to get inputs for r9  )r   rW   )r  r   r  debug)r   r   rW   r   s       rB   _get_inputs_safer    s    096t666v666 0 0 0AAAaAABBB////////0s    
A$A AAi  )maxsizeSet[str]c                V    ddfd| j                                         D             S )Nr   inspect.Parameterr<   r~   c                    | j         t          j        k    sHt          | j                   t          k    r-t          d t          | j                   D                       rdS dS )Nc              3  6   K   | ]}|t           j        k    V  d S r   )r&   
Attachment)rJ   args     rB   r   z;_attachment_args.<locals>._is_attachment.<locals>.<genexpr>  s*      TT#C7--TTTTTTrA   TF)
annotationr&   r  r"   r   anyr!   )r   s    rB   _is_attachmentz(_attachment_args.<locals>._is_attachment  s_    w111u'((I55TT%BR9S9STTTTT 6 4urA   c                0    h | ]\  }} |          |S r@   r@   )rJ   rq   r   r  s      rB   	<setcomp>z#_attachment_args.<locals>.<setcomp>  s<       uu@U@U  rA   )r   r  r<   r~   )r   rN   )r   r  s    @rB   _attachment_argsr    sQ           ) 4 : : < <   rA    Tuple[dict, schemas.Attachments]c                ,   	 t          | g|R i |}t          |           }|r1i i }}|                                D ]\  }}||v r|||<   |||<   ||fS |i fS # t          $ r1}	t                              d|  d|	            ||di fcY d }	~	S d }	~	ww xY wr  )r  r  rN   r   r  r  )
r   r   rW   inferredattachment_argsr  r  rK   rL   r   s
             rB   r  r    s    4y:4:::6::*955 	'"$bKF (( " "1''%&KNN !F1II;&&| 4 4 4AAAaAABBB//33333334s$   AA A 
B"&BBBc                ~    |                                  D ]'\  }}t          |         }|                    |           (dS )zSet the tracing context.N)rN   r;   ra   )rD   rK   rL   vars       rB   rb   rb     sB      1A



 rA   r   Iterator[T]r   r   r   	List[Any]Generator[T, None, Any]c              #    K   	 	 |d                              t          |           }|rg|d         r_|d                             dt          j                            t          j        j                                                  d|id           |                    |           |V  # t          $ r}|j
        cY d }~S d }~ww xY w)NTrD   r   	new_tokentokenrq   timerW   )r   next	add_eventdatetimenowtimezoneutc	isoformatr   StopIterationvalue)r   r   r   r   r   r   s         rB   r   r     s      	#I.224CCD 	mI6 	i(22 + ( 1 5 5$-1! !#)++#*D/    NN4   JJJ	    ws   B%B) )
C3B?9C?CAsyncIterator[T]r   AsyncGenerator[T, None]c              F  K   	 	 |r5t          j        t          j        |           |d                    d {V }nQt	          di t          |d                   5  t          j        |            d {V }d d d            n# 1 swxY w Y   |rg|d         r_|d                             dt          j                            t          j	        j
                                                  d|id           |                    |           |W V  # t          $ r Y d S w xY w)	NTrD   rO   r   r  r  r  r@   )r   r   r   py_anextrd   rP   r  r  r  r  r  r  r   StopAsyncIteration)r   r   r   r   r   r   s         rB   r   r     s     	 @$0'	22))4         %UU':=;S'T'TUU @ @!+!4Y!?!???????D@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ 	mI6 	i(22 + ( 1 5 5$-1! !#)++#*D/    NN4   JJJJ+	,    s7   AD B6D BD 	B
BD 
D D Tc                  H    e Zd ZdZ	 ddd	ZddZd Zd Zd Zd Z	dddZ
dS )_TracedStreamBasez%Base class for traced stream objects.Nr   $Union[Iterator[T], AsyncIterator[T]]r   r  rr   r  c                    || _         || _        d| _        || _        g | _        |d         r|d         j        dk    nd| _        d S )NFr   r   )__ls_stream____ls_trace_container____ls_completed____ls_reduce_fn____ls_accumulated_output__r   __is_llm_run__)r   r   r   rr   s       rB   r  z_TracedStreamBase.__init__<  s^     $&5# % )24& y)OI&/588 	rA   rq   r  c                ,    t          | j        |          S r   )r  r  )r   rq   s     rB   __getattr__z_TracedStreamBase.__getattr__M  s    t)4000rA   c                    t          t          t          | j                  t          | j                  z                       S r   )listra   dirrd  r  rC  s    rB   __dir__z_TracedStreamBase.__dir__P  s2    CDN++c$2D.E.EEFFGGGrA   c                    d| j         dS )Nz
Traceable())r  rC  s    rB   __repr__z_TracedStreamBase.__repr__S  s    3D.3333rA   c                *    t          | j                  S r   )r  r  rC  s    rB   __str__z_TracedStreamBase.__str__V  s    4%&&&rA   c                    	 | j         s|                                  n# t          $ r Y nw xY w	 | j                                         d S # t          $ r Y d S w xY wr   )r  
_end_tracer   r  __del__rC  s    rB   r
  z_TracedStreamBase.__del__Y  s    	( "!!! 	 	 	D		&&((((( 	 	 	DD	s    
++A
 

AAr   r4  c                    | j         rd S 	 | j        r|                     | j                  }n| j        }t          | j        ||           d| _         d S # d| _         w xY w)Nr  T)r  r  r  r  r  )r   r   reduced_outputs      rB   r	  z_TracedStreamBase._end_traced  s      	F		)$ @!%!6!6t7U!V!V!%!?+^5    %)D!!!DD!((((s   A A 	Ar   )r   r  r   r  rr   r  )rq   r  r   r4  )r   r   r   r   r  r  r  r  r  r
  r	  r@   rA   rB   r  r  9  s        // )-	
 
 
 
 
"1 1 1 1H H H4 4 4' ' '	 	 	) ) ) ) ) ) )rA   r  c                  D     e Zd ZdZ	 dd fd	ZddZddZd Zd Z xZ	S )r   z>A wrapper for synchronous stream objects that handles tracing.Nr   r  r   r  rr   r  c                    t                                          |||           || _        t          | j        | j        | j        | j                  | _        d S )Nr   r   rr   r   )re  r  r  r   r  r  r  __ls__gen__r   r   r   rr   rd  s       rB   r  z_TracedStream.__init__v  sl     	?i 	 	
 	
 	
 $,'*2	
 
 
rA   r<   r  c                r    	 t          | j                  S # t          $ r |                                   w xY wr   )r  r  r  r	  rC  s    rB   __next__z_TracedStream.__next__  sF    	())) 	 	 	OO	s     6c              #     K   	 | j         E d {V  |                                  d S # t          $ r}|                     |            d }~ww xY wNr   )r  r	  r   )r   r   s     rB   r   z_TracedStream.__iter__  sv      	''''''''
 OO	  	 	 	OO!O$$$	s   ' 
AAAc                4    | j                                         S r   )r  rD  rC  s    rB   rD  z_TracedStream.__enter__  s    !++---rA   c                    	 | j                             |||          |                     |r|nd            S # |                     |r|nd            w xY wr  )r  rF  r	  r   r1  exc_valexc_tbs       rB   rF  z_TracedStream.__exit__  sc    	A%..x&IIOOX"?''4O@@@@DOOX"?''4O@@@@s	   8 Ar   )r   r  r   r  rr   r  r<   r  )r<   r  )
r   r   r   r   r  r  r   rD  rF  rx  rd  s   @rB   r   r   s  s        HH )-	
 
 
 
 
 
 
"      . . .A A A A A A ArA   r   c                  N     e Zd ZdZ	 dd fd	ZdddZddZddZd Zd Z	 xZ
S )r   z?A wrapper for asynchronous stream objects that handles tracing.Nr   r  r   r  rr   r  c                    t                                          |||           || _        t          | j        | j        | j        t          j                    | j                  | _	        d S )Nr  r   )
re  r  r  r   r  r  r   r   r  _TracedAsyncStream__ls_genr  s       rB   r  z_TracedAsyncStream.__init__  su     	?i 	 	
 	
 	
 $/(5*&>@@2
 
 
rA   r   r4  c                   K   t                      }t          j        t          j        | j        ||                     d {V  t          t          |                     d S )NrH  )r   r   r   r   r   r	  rb   rP   )r   r   rJ  s      rB   _aend_tracez_TracedAsyncStream._aend_trace  sw      nnn$T_e3GGG
 
 	
 	
 	
 	
 	
 	
 	
 	05566666rA   r<   r  c                   K   	 t          t          t          j        | j                   d {V           S # t
          $ r |                                  d {V   w xY wr   )r   r  r   r  r   r  r"  rC  s    rB   	__anext__z_TracedAsyncStream.__anext__  s|      	!4T]!C!CCCCCCCDDD! 	 	 	""$$$$$$$$$	s	   16 &Ac                  K   	 | j         2 3 d {V }|W V  6 	 |                                  d {V  d S # t          $ r |                                  d {V   w xY wr   )r   r"  r   )r   r   s     rB   r   z_TracedAsyncStream.__aiter__  s      	%"m       d




 ,m ""$$$$$$$$$$$	  	 	 	""$$$$$$$$$	s   6 6 &Ac                D   K   | j                                          d {V S r   )r  rL  rC  s    rB   rL  z_TracedAsyncStream.__aenter__  s-      '22444444444rA   c                   K   	 | j                             |||           d {V 	 |                                  d {V  S # |                                  d {V  w xY wr   )r  rN  r"  r  s       rB   rN  z_TracedAsyncStream.__aexit__  s      	%+55hPPPPPPPPP""$$$$$$$$$$$""$$$$$$$$$$s   !A Ar   )r   r  r   r  rr   r  r  r  )r<   r  )r   r   r   r   r  r"  r$  r   rL  rN  rx  r  s   @rB   r   r     s        II )-	
 
 
 
 
 
 
$7 7 7 7 7   % % % %5 5 5% % % % % % %rA   r   r   c                    | rC|?	  ||           S # t           $ r&}t                              |           | cY d }~S d }~ww xY w| S d S r   )r   r  r   )r   rr   r   s      rB   r   r     ss       y)))    Q N s   
 
A<AA)r<   r=   r   )rD   rE   r<   rF   )r7   rQ   r8   rR   r9   rS   r6   rT   r:   rU   r$   rV   rW   r   r<   rX   )re   r   r<   rf   )re   ru   rq   rQ   r9   rv   r8   rR   r$   rV   rr   rw   r7   rQ   rs   rx   rt   ry   r<   rz   )re   r
   r<   r~   )re   ru   r<   rz   rO  )r   r   rq   rQ   r9   rv   r8   rR   r$   rV   rr   rw   r7   rQ   rs   rx   rt   ry   r   rx   r<   r   )r   r   rW   r   r<   r   )r7   rQ   r<   rQ   )rU  r
   r<   r+   )NN)r  r  r   r  r   r4  r<   r7  )r   rk  r   r   r<   rk  )r   r   r   r  r<   r=   rP  )re   r
   r   r  r   r   r   r   rW   r   r<   r  )
r  r  r   r  r   r4  r   ry   r<   r7  )re   r   r<   r~   )r   r  r   r   rW   r   r<   rF   )r   r  r<   r  )r   r  r   r   rW   r   r<   r  )rD   rF   )
r   r  r   r  r   r~   r   r  r<   r  )r   r  r   r  r   r~   r   r~   r   r  r<   r  )r   r   rr   r
   r<   r   )rr   
__future__r   r   
contextlibcontextvarsr  rk   r   r  r  r\   r   typingr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typing_extensionsr   r   r    r!   r"   	langsmithr$   r  r%   r&   r'   langsmith._internalr(   r   langsmith.envr)   typesr*   rz  r+   	getLoggerr   r  
ContextVarr'  r,   r  r/   r0   r1   r~   r3   Clientr4   r;   r   rC   rP   contextmanagerrd   get_run_tree_contextro   r}   r   r   r   r   r   r|   r  r%  r  r  r  r  r  r  r_   r   r  ri   r  r  	lru_cacher  r  rb   r   r   r  r  r   r   r   r@   rA   rB   <module>r8     s   7 7 7 " " " " " "                   $ $ $ $ $ $                                                     8 T S S S S S S S S S S S S S ) ) ) ) ) ) / / / / / / / / / / 4 4 4 4 4 4 & & & & & & 2######111111		8	$	$F;)(93D*EF    6&x}5otTTT3xS	23GTJJJ<K"8DcN#;<[RVWWW	 S;)(5ww?O9O3P*QR    =+
 )*:!;
<YPT
U
U
U!4 4    " " " " .2A A A A A   #' $)-?C7;)-2. 2. 2. 2. 2. 2.l ,     ,0 $)-6:"&7;59     6   E E E E EYe E E E E6 GC4   IcNN     Xwq!t}   D 
' ' ' 
'
 
%,C ,0 $)-6:"&7;59>BC C C C C 
Cg g g gTM7 M7 M7 M7 M7 M7 M7 M7`
 
 
 
p+ p+ p+ p+h   	! 	! 	! 	! 	!)5 	! 	! 	! 	!; ; ; ; ;iu ; ; ; ;" "%)B B B B B4    "/ / / / /j 15E E E E ET "%)7;	F F F F F; ; ; ;   (0 0 0 0 T"""   #"4 4 4 4(      4       F GCLL7) 7) 7) 7) 7)
 7) 7) 7)t+A +A +A +A +A%wqz +A +A +A\4% 4% 4% 4% 4%*GAJ 4% 4% 4%n	 	 	 	 	 	rA   