
    f                       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" ddl#m$Z$m%Z% ddl&m'Z( ddl&m)Z)m*Z* dd	l+m,Z- dd
l.m/Z/ erddl0m1Z1 ddl2m3Z3  e	jh                  e5      Z6 ejn                  ee)jp                        dd      Z9 ejn                  ee:      dd      Z; ejn                  eee:         dd      Z< ejn                  eee:ef         dd      Z= ejn                  ee>      dd      Z?e9e;e<e=e?dZ@deAd<   d<dZB	 d=	 	 	 d>dZCd?dZDej                  dddddd	 	 	 	 	 	 	 	 	 	 	 	 	 d@d       ZFeBZG	 	 	 	 dAdZHdBdZIdCdZJ G d ded !      ZK ed"d#$      ZL e$d%      ZMe" G d& d'eeeMeLf                ZNe!	 	 	 	 dBd(       ZOe!	 dDdddddddddd)		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dEd*       ZO	 	 	 	 	 	 dFd+ZO G d, d-      ZPdGd.ZQdHd/ZRh d0ZS G d1 d2ed !      ZT G d3 d4ed !      ZU	 	 dI	 	 	 	 	 	 	 dJd5ZVdKd6ZW	 d=	 	 	 	 	 dLd7ZX	 	 	 dM	 	 	 	 	 	 	 	 	 	 	 dNd8ZYdCd9ZZ	 	 	 	 	 	 	 	 dOd:Z[	 	 	 	 	 	 	 	 dOd;Z\y)Pz1Decorator for creating a run tree from functions.    )annotationsN)copy_context)TYPE_CHECKINGAnyAsyncGenerator	AwaitableCallableDict	GeneratorGenericListMappingOptionalProtocolSequenceTupleType	TypedDictTypeVarUnioncastoverloadruntime_checkable)	ParamSpec	TypeGuardclient)	run_treesutils)_aiter)_runtime_env)TracebackType)Runnable_PARENT_RUN_TREEdefault_PROJECT_NAME_TAGS	_METADATA_TRACING_ENABLEDparentproject_nametagsmetadataenabledz!Dict[str, contextvars.ContextVar]_CONTEXT_KEYSc                 *    t         j                         S )zGet the current run tree.)r$   get     T/opt/lhia/ganansol/python/venv/lib/python3.12/site-packages/langsmith/run_helpers.pyget_current_run_treer7   F   s    !!r5   c                D   | bt         j                         t        j                         t        j                         t        j                         t
        j                         dS t        j                         D ci c]  \  }}|| j                  |       c}}S c c}}w )z Get the current tracing context.r+   )r$   r3   r'   r(   r)   r*   r1   items)contextkvs      r6   get_tracing_contextr=   K   sy     &**,)--/IIK!'++-
 	
 +8*=*=*?@$!QAw{{1~@@@s   <Bc                h    | j                         D ]  \  }}t        |   }|j                  |       ! y)zSet the tracing context.N)r9   r1   set)r:   r;   r<   vars       r6   _set_tracing_contextrA   Z   s0     1A
r5   )r-   r.   r/   r,   r0   c              +    K   |rt        j                  d| dt               t               }t	        d|xs |j                  d      i      }|Ft        t        |xs g       t        |j                  xs g       z        }i |j                  |xs i }||n|j                  d      }t        || |||d       	 d t        |       y# t        |       w xY ww)ah  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.
        enabled: Whether tracing is enabled. Defaults to None, meaning it will use the
            current context value or environment variables.

    z Unrecognized keyword arguments: .r,   
parent_runNr0   r+   )warningswarnDeprecationWarningr=   _get_parent_runr3   sortedr?   r.   r/   rA   )r-   r.   r/   r,   r0   kwargscurrent_contextrD   s           r6   tracing_contextrL   a   s     . .vha8	
 *+O (F,Nfjj6N!OPJc$*"oJOO,Ar(BBC>j))>hn"> ,g/2E2Ei2PG ( 	
._-_-s   B9C<C  CCCc                    t        |       xsV t        | t        j                        xr t        | j                        xs# t        | d      xr t        | j                        S )z,Check if a function is @traceable decorated.__call__)_is_traceable_function
isinstance	functoolspartialfunchasattrrN   rS   s    r6   is_traceable_functionrV      sU    
 	t$ 	QtY../U4J4994U	QD*%O*@*Or5   c                <    t        |       r| S  t               |       S )z$Ensure that a function is traceable.)rV   	traceablerU   s    r6   ensure_traceablerY      s    T"9;tr5   c                    t        j                  |       xs- t        | d      xr t        j                  | j                        S )z;Inspect function or wrapped function to see if it is async.__wrapped__)inspectiscoroutinefunctionrT   r[   rU   s    r6   is_asyncr^      s:    &&t, m$V)D)DTEUEU)Vr5   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<   y)LangSmithExtraz<Any additional info to be injected into the run dynamically.Optional[str]nameOptional[ls_client.ID_TYPE]reference_example_idOptional[Dict]	run_extra0Optional[Union[run_trees.RunTree, str, Mapping]]r,   Optional[run_trees.RunTree]run_treer-   Optional[Dict[str, Any]]r/   Optional[List[str]]r.   run_idOptional[ls_client.Client]r   ,Optional[Callable[[run_trees.RunTree], Any]]on_endN__name__
__module____qualname____doc____annotations__r4   r5   r6   r`   r`      sG    F
55<<))&&
''&&88r5   r`   F)totalRT)	covariantPc                  ,    e Zd ZdZdd	 	 	 	 	 	 	 ddZy)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_extrac                    y)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.

        Nr4   )selfr}   argsrJ   s       r6   rN   zSupportsLangsmithExtra.__call__   s    $ 	r5   )r   zP.argsr}   Optional[LangSmithExtra]rJ   zP.kwargsreturnrw   )rq   rr   rs   rt   rN   r4   r5   r6   r{   r{      s7    
 59 2 	
 
r5   r{   c                     y Nr4   rU   s    r6   rX   rX      s     $'r5   )	rb   r/   r.   r   	reduce_fnr-   process_inputsprocess_outputs_invocation_params_fnc       	             y r   r4   )
run_typerb   r/   r.   r   r   r-   r   r   r   s
             r6   rX   rX      s	     @Cr5   c                    | rt        | d   t              r| d   n|j                  dd      xs dt        vr#t	        j
                  d dt         d d       t        |       d	kD  rt	        j
                  d
       d|v rt	        j
                  dt               |j                  dd      t        |j                  dd      |j                  dd      |j                  dd      |j                  dd      |j                  dd      |j                  dd      |j                  dd      |j                  dd      	      |j                  dd      	 	 d	 	 	 	 	 	 	 dfd|r5t	        j
                  dt        |j                                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:
        .. code-block:: python
            import httpx
            import asyncio

            from typing import Iterable
            from langsmith import traceable, Client


            # Basic usage:
            @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:
            @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
            @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:
            @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:
            @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:
            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:
            @traceable
            def manual_extra_function(x):
                return x**2


            manual_extra_function(5, langsmith_extra={"metadata": {"version": "1.0"}})
    r   r   Nchainz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.r   rb   r/   r.   r   r-   r   r   )	extra_outerrb   r/   r.   r   r-   r   r   invocation_params_fnr   c                :    |r
 |      }t        | ||       y)zHandle the end of run.Noutputserror)_container_end)	containerr   r   outputs_processors      r6   _on_run_endztraceable.<locals>._on_run_end  s$     (4'0Gy'?r5   zHThe following keyword arguments are not recognized and will be ignored: rC   c           
     2   	 t        j                         }|j                  j                  dd       d u	|j                  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                         r|}n/t               rr|}n|}nst        j                         r|}n|}t        |dd	       t        j                  |      }|j                  j                  d      s|j                  g d
 |j                  j                         D        t        j                  dt         j                  j                  d       d |j                  j                         D              }||_        |S )Nri   configr|   c                h  K   t        j                  t        
	| ||       d{   }	 t        j                         }r|d   |d<   s|j	                  dd        
|i |}|r#t        j                  ||d          d{   }n*t        d
i t        |d         5  | d{   }ddd       t        j                  |	       d{    |S 7 7 S7 2# 1 sw Y   1xY w# t        $ r;}t        j                  t        j                  ||             d{  7   |d}~ww xY w7 _w)z"Async version of wrapper function.container_inputr}   r   rJ   Nnew_runri   r   r:   r:   r   r   r4   )
aitertoolsaio_to_thread
_setup_runasyncio_accepts_contextpopasynciocreate_taskrL   r=   BaseExceptionshield)r}   r   rJ   run_containeraccepts_contextfr_corofunction_resulter   r   rS   func_accepts_configfunc_accepts_parent_runs           r6   async_wrapperz3traceable.<locals>.decorator.<locals>.async_wrapper  sR     #-":": / /# M","D"D"F*)6y)AF:&*JJx.//",3,?,?y)A- 'O
 ) -mI.FG 8 18-8 **]O   #"G"' +88 8 ! nn,,[-qQ   s   #D2CD2AC) CC) "C(C)C-C) 5D2D0D2C) CC&"C) )	D-2.D( D#!D((D--D2c               D  K   t        j                  t        | ||       d {   }g }	 r|d   |d<   s|j                  dd         |i |}t        j                         }t        j                  |      rO|r#t        j                  ||d          d {   }n*t        di t        |d         5  | d {   }d d d        	 	 |r6t        j                  t        j                  |      |d          d {   }n=t        di t        |d         5  t        j                  |       d {   }d d d        dk(  rb|d   r]|d   j                  dt        j                  j                  t        j                  j                         j#                         d	id
       |j%                         | 7 7 (7 # 1 sw Y   xY w7 7 # 1 sw Y   xY w# t&        $ r Y nw xY wnG# t(        $ r;}t        j*                  t        j                  
||             d {  7   |d }~ww xY w|r<r7	  |      }	n2# t(        $ r!}t,        j/                  |       |}	Y d }~nd }~ww xY w|}	nd }	t        j                  
||	       d {  7   y w)Nr   r   ri   r   r:   r   llm	new_tokentokenrb   timerJ   r   r   r4   )r   r   r   r   r   r\   iscoroutiner   r   rL   r=   py_anext	add_eventdatetimenowtimezoneutc	isoformatappendStopAsyncIterationr   r   LOGGERr   )r}   r   rJ   r   resultsasync_gen_resultr   itemr   r   r   r   rS   r   r   r   r   s             r6   async_generator_wrapperz=traceable.<locals>.decorator.<locals>.async_generator_wrapper  s     #-":": / /# M "$G6*)6y)AF:& +JJx.#'#8#8 ","D"D"F&&'78&181D1D,mI6N2 ,(
 - 1-	2JK F 6F/E,F*)0)<)< * 3 34D E(5i(@* $D "1 ""5mI6N"O" S .8-@-@AQ-R'RS $u,,Y7 -i 8 B B0;080A0A0E0E,4,=,=,A,A1**3)+3:D/%&!"  t,"
1 A,, 0FF F$ (SS S" *   nn,,[-qQ   	
 2*3G*<( 2Q*12 '.O"&**]O  s  #J GJ A.G7 GG7 9G
?G G
G7 3G'  GG' G6G7G;BG' J G7 G

GG7 G' GG$ G' '	G30G7 2G33G7 6J 7	H; .H6.H1/H66H;;J I J 	I6I1,J 1I66#J JJ c                H   t        	| ||      }t        j                  	      j                  j	                  dd      du}	 |r|d   |d<   
s|j                  dd        |d   j                  	g|i |} ||       |S # t        $ r} ||       |d}~ww xY w)	>Create a new run or create_child() if run is passed in kwargs.r   ri   Nr   r   r:   r   r   )r   r\   	signature
parametersr3   r   runr   )r}   r   rJ   r   r   r   r   r   r   rS   r   s          r6   wrapperz-traceable.<locals>.decorator.<locals>.wrapper?  s     ' / /M !!$'2266z4HPTT $*)6y)AF:&*JJx.">-	":">">t"Ud"Uf"U ?""	 ! M3s   7B 	B!BB!c              ?  D  K   t        | ||      }t        j                        j                  j	                  dd       d u}g }	 |r|d   |d<   s|j                  dd         |d   j                  g|i |}	 	 |d   j                  t        |      }dk(  rb|d   r]|d   j                  dt        j                  j                  t        j                  j                        j                         d|id	       |j                  |       	 | # t        $ r Y nw xY wn# t         $ r Y nw xY wn# t"        $ r} 
||
       |d }~ww xY w|r<r7	  |      }	n2# t"        $ r!}t$        j'                  |       |}	Y d }~nd }~ww xY w|}	nd }	 
||	       y w)Nr   ri   r   r   r:   r   r   r   r   r   r   )r   r\   r   r   r3   r   r   nextr   r   r   r   r   r   r   GeneratorExitStopIterationr   r   r   )r}   r   rJ   r   r   r   generator_resultr   r   r   r   r   rS   r   r   r   s             r6   generator_wrapperz7traceable.<locals>.decorator.<locals>.generator_wrapper\  s     ' / /M !!$'2266z4HPTT $ "$G!*)6y)AF:& +JJx.#?=#;#?#?#Vt#Vv#V ,Y7;;DBRS#u,,Y7 -i 8 B B0;080A0A0E0E,4,=,=,A,A1**3)+3:D/%&!"  t,""&J    - "!"!$  ! M3 2*3G*<( 2Q*12 '.O"&?s   AF 7D8  BD( D D( 	D$!D( #D$$D( 'D8 (	D41D8 3D44D8 7F 8	EEEF E# "F #	F,FF FF __langsmith_traceable__Tc              3  n   K   | ]-  }|j                   t        j                  j                  k7  r| / y wr   kindr\   	ParameterVAR_KEYWORD.0params     r6   	<genexpr>z/traceable.<locals>.decorator.<locals>.<genexpr>  0      ! ::):):)F)FF    35r%   c              3  n   K   | ]-  }|j                   t        j                  j                  k(  r| / y wr   r   r   s     r6   r   z/traceable.<locals>.decorator.<locals>.<genexpr>  r   r   )r   )r   r   r}   r   rJ   r   r   r   )r   r   r}   r   rJ   r   r   r   )r\   r   r   r3   rQ   wrapsisasyncgenfunctionr^   isgeneratorfunctionsetattrreplacevaluesr   KEYWORD_ONLY__signature__)rS   func_sigr   r   r   r   selected_wrappersigr   r   r   r   r   r   s   `       @@r6   	decoratorztraceable.<locals>.decorator  s   $$T*"*"5"5"9"9*d"KSW"W&1155hETQ		 9=)	#)	#5)	# )	# 	)	# )	# 
)	#V 
	DHP	P	)AP	TWP	P	 P	 
P	d 
	 9=	#	#5	# 	# 		# 
	#8 
	DH;	@;	@)A;	@TW;	@;	@ ;	@ 
;	@z %%d+)@d^#: #0 '55d;0& ";TB 01~~!!(+++%(^^%:%:%< %% '"3"3"@"@$%(^^%:%:%<  C" .1*r5   NNr   _TraceableContainerr   zOptional[Any]r   Optional[BaseException]r   None)rS   r	   )rP   strr   _VALID_RUN_TYPESrE   rF   lenrG   _ContainerInputrI   keyscallable)r   rJ   r   r   r   r   r   r   s      @@@@@r6   rX   rX      s   R JtAw, 	QjjT*5g 
 ''%hZ/ABRAS T..6Zs<	
 4y1}$	

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

 

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

#4d; "&)-@&@@ '@ 
	@ Vfkkm$%Q(	
   F 4yA~(47+Fa!!r5   c                      e Zd ZdZ	 dddddddddddd
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZ	 	 	 	 	 	 	 	 ddZddZ	 	 	 d	 	 	 	 	 	 	 ddZdd	Z		 	 	 d	 	 	 	 	 	 	 dd
Z
y)tracea
  Manage a langsmith run in context.

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

    Parameters:
    -----------
    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
    project_name : Optional[str], optional
        Associates the run with a specific project, overriding defaults
    parent : Optional[Union[run_trees.RunTree, str, Mapping]], optional
        Parent run, accepts RunTree, dotted order string, or tracing headers
    tags : Optional[List[str]], optional
        Categorization labels for the run
    metadata : Optional[Mapping[str, Any]], optional
        Arbitrary key-value pairs for run annotation
    client : Optional[ls_client.Client], optional
        LangSmith client for specifying a different tenant,
        setting custom headers, or modifying API endpoint
    run_id : Optional[ls_client.ID_TYPE], optional
        Preset identifier for the run
    reference_example_id : Optional[ls_client.ID_TYPE], optional
        You typically won't set this. It associates this run with a dataset example.
        This is only valid for root runs (not children) in an evaluation context.
    exceptions_to_handle : Optional[Tuple[Type[BaseException], ...]], optional
        Typically not set. Exception types to ignore in what is sent up to LangSmith
    extra : Optional[Dict], optional
        Typically not set. Use 'metadata' instead. Extra data to be sent to LangSmith.

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

    Asynchronous usage:
    >>> async def main():
    ...     async with trace("Async Operation", run_type="tool", tags=["async"]) as run:
    ...         result = "foo"  # Can await some_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())

    Allowing pytest.skip in a test:
    >>> import sys
    >>> import pytest
    >>> with trace("OS-Specific Test", exceptions_to_handle=(pytest.skip.Exception,)):
    ...     if sys.platform == "win32":
    ...         pytest.skip("Not supported on Windows")
    ...     result = "foo"  # e.g., do some unix_specific_operation()
    N)
inputsr   r-   r,   r.   r/   r   rl   rd   exceptions_to_handlec       
        b   |r5t        j                  dt        |j                                dt               || _        || _        || _        || _        || _	        || _
        |j                  d      | _        || _        || _        |	| _        |
| _        || _        || _        d| _        d| _        y)z_Initialize the trace context manager.

        Warns if unsupported kwargs are passed.
        zEThe `trace` context manager no longer supports the following kwargs: rC   ri   N)rE   rF   rI   r   rG   rb   r   r   r   r-   r,   r3   ri   r.   r/   r   rl   rd   r   r   old_ctx)r   rb   r   r   r   r-   r,   r.   r/   r   rl   rd   r   rJ   s                 r6   __init__ztrace.__init__  s    * MMW&++-(),"
 	 
( 

:.	 $8!$8!48'+r5   c                   t               | _        t        j                  | j                        }t        j                         }t        j                         }t        | j                  | j                  | j                  d      }t        t        | j                  xs g |xs g z               }i | j                  xs i |xs i ddi}| j                  xs i }||d<   t!        | j"                        }|G|rE|j%                  | j&                  | j(                  | j*                  || j,                  |      | _        nt1        j2                  | j&                  t5        j6                  | j(                        t5        j6                  | j8                  d      | j*                  ||xs d| j,                  xs i || j                  		      | _        |rx| j.                  j;                          t        j                  |       t        j                  |       t<        j                  | j.                         t>        j                  |       | 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,   ri   r   	ls_methodr   r/   )rb   rl   r   r   r   r.   Taccept_nullr&   )	rb   idrd   r   r   r-   r   r.   r   ) r=   r   r   tracing_is_enabledr(   r3   r)   rH   r,   ri   r   rI   r?   r.   r/   r   _get_project_namer-   create_childrb   rl   r   r   r   r   RunTree	ls_client_ensure_uuidrd   postr$   r'   )	r   r0   
outer_tagsouter_metadataparent_run_tags_r/   r   project_name_s	            r6   _setupztrace._setup.  s    +,**4<<8YY[
"%++ MM++
 sDIIO
0@bABC
}}"
#
 
 jj&B"*J)$*;*;<"w&33YY{{!{{ 4 DL %,,YY))$++6%.%;%;--4& !*7i{{(b{{DL LLIIeMM(#  .m,||r5   c                   | j                   y|i| j                  rt        || j                        rd}n(t        j                         }|j
                   d| d| }| j                   j                  |       | j                  Qt        j                  | j                        }|r| j                   j                          t        | j                         yt        j                  dt               y)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   z(Tracing context was not set up properly.)r   r   
issubclassr   _format_excrq   endr   r  patchrA   rE   rF   RuntimeWarning)r   exc_type	exc_value	tracebacktbr0   s         r6   	_teardownztrace._teardownr  s      <<((Z$33. &&( ))*"YKtB4@LL2&<<#..t||<G""$ .MMDnUr5   c                "    | j                         S )zyEnter the context manager synchronously.

        Returns:
            run_trees.RunTree: The newly created run.
        )r  )r   s    r6   	__enter__ztrace.__enter__  s     {{}r5   c                *    | j                  |||       y)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)r  )r   r  r  r  s       r6   __exit__ztrace.__exit__  s     	xI6r5   c                   K   t               }t        j                  | j                  |       d{   }t	        t        |             |S 7 w)zzEnter the context manager asynchronously.

        Returns:
            run_trees.RunTree: The newly created run.
        __ctxN)r   r   r   r  rA   r=   )r   ctxresults      r6   
__aenter__ztrace.__aenter__  sA      n!//3GG056 Hs   /AAAc           	     ,  K   t               }|@t        j                  t        j                  | j
                  ||||             d{    n,t        j                  | j
                  ||||       d{    t        t        |             y7 F7 w)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.
        Nr#  )r   r   r   r   r   r  rA   r=   )r   r  r  r  r%  s        r6   	__aexit__ztrace.__aexit__  s      n..((NNHi#   **)Yc   	056s$   AB	B
,B6B7BBr   )rb   r   r   ls_client.RUN_TYPE_Tr   re   r   re   r-   ra   r,   rg   r.   rk   r/   Optional[Mapping[str, Any]]r   rm   rl   rc   rd   rc   r   z)Optional[Tuple[Type[BaseException], ...]]rJ   r   )r   zrun_trees.RunTree)r  zOptional[Type[BaseException]]r  r   r  zOptional[TracebackType]r   r   NNN)rq   rr   rs   rt   r   r  r  r  r!  r'  r)  r4   r5   r6   r   r     sh   :~ *1+,
 "& $&*CG$(04-1.2<@JN+,+, '+,
 +, +, $+, A+, "+, .+, ++, ,+, :+, H+, +,ZBH"V/"V +"V +	"V
 
"VH 37-1-1	7/7 +7 +	7
 
7
 37-1-1	7/7 +7 +	7
 
7r5   r   c                    t         j                         }t        j                         xs* |r|j                  nd xs | xs t	        j
                         S r   )r$   r3   r'   session_namer   get_tracer_project)r-   prts     r6   r  r    sR    



 C 	 	& #C	& 	&
 ##%r5   c                   	 ddl mm} ddlmm t        |       s'	 t        j                  |       }t        d|  d|        G fd	d
|      } ||       S # t        $ r}t        d      |d}~ww xY w# t        $ r d}Y Rw xY w)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                  |     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.
        c           
        d }| j                  |      }t        |      r3|t        d      t        t        gf   | j                  |            }n0t        |      r%t        t        gf   | j                  |            }|$t        | j                  j                   d|       t        | -  |t        t        t        gt           f      |             y )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	   rV   
_wrap_sync
ValueError	__class__rq   superr   r   r   )r   rS   afuncwrappedawrappedr5  r6  r>  s        r6   r   z/as_runnable.<locals>.RunnableTraceable.__init__  s    
 <@G''.H~'#7 
 x8$:J:J4:PQ&t,x8$//$:OP ~~../ 02269  GXugy/@&@ABr5   c                @     d fd}t        t        gf   |      S )z4Wrap a synchronous function to make it asynchronous.c                z    t         j                  j                  t        t        |            } di | dd|iiS Nr}   ri   r4   r   r  from_runnable_configr   dict)r   r   ri   rS   s      r6   wrap_traceablezIas_runnable.<locals>.RunnableTraceable._wrap_sync.<locals>.wrap_traceable4  s8    $,,AA$tVBTUMfMz86LMMr5   r   rH  r   r3  r   r   )r   r	   )rS   rI  r5  r6  r3  s   ` r6   r<  z1as_runnable.<locals>.RunnableTraceable._wrap_sync.  s'    N %!8&!@A>RRr5   c                    | y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 .c                   K   t         j                  j                  t        t        |            } di | dd|ii d {   S 7 wrE  rF  )r   r   ri   afunc_s      r6   awrap_traceablezKas_runnable.<locals>.RunnableTraceable._wrap_async.<locals>.awrap_traceableI  sB     $,,AA$tVBTU#UfUz8>TUUUUs   ?A	AA	rJ  )rV   r=  r   r	   r   )r@  rN  rM  r5  r6  r3  s     @r6   r:  z2as_runnable.<locals>.RunnableTraceable._wrap_async:  s|    
 }(/ 227:  (3	&(9#9:EBFV %0)F2CCDo r5   r   )rS   r	   r@  *Optional[Callable[..., Awaitable[Output]]]r   r   )rS   zCallable[..., Output]r   z)Callable[[Input, RunnableConfig], Output])r@  rO  r   z>Optional[Callable[[Input, RunnableConfig], Awaitable[Output]]])	rq   rr   rs   rt   r   staticmethodr<  r:  __classcell__)r>  r5  r6  r3  s   @r6   RunnableTraceabler8    s}    	 AE		 >	 		@ 
		S'		S6		S 
		S 
	=	K	 
	r5   rR  )langchain_core.runnablesr3  r4  langchain_core.runnables.utilsr5  r6  ImportErrorrV   r\   	getsource	Exceptionr=  )traceable_fnr4  r   fn_srcrR  r5  r6  r3  s        @@@r6   as_runnablerZ    s    *K@ !.	,&&|4F **6~fXO
 	

G GN GR \**q  D
 	  	,+F	,s(   A A; 	A8'A33A8;B	B	>   r   toolr   parserprompt	embedding	retrieverc                  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<   y)r   3Typed response when initializing a run a traceable.rh   r   ra   r-   outer_projectrj   r  rk   r  rn   ro   zcontextvars.Contextr:   Nrp   r4   r5   r6   r   r   a  s/    =((  ,,##88  r5   r   c                  v    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<   y)r   ra  re   r   ra   rb   rj   r/   rk   r.   rm   r   zOptional[Callable]r   r-   r+  r    Optional[Callable[[dict], dict]]r   r   Nrp   r4   r5   r6   r   r   m  sA    =
&&
&&!!""44::r5   r   c                   | j                  d      }|yt        |t              r|nd|i}d}|r$t        j                         }t        |       d| }|j                  ||       |j                          | j                  d      }|t        |      r
	  ||       yyy# t        $ r"}t        j                  d|        Y d}~yd}~ww xY w)zEnd the run.r   Noutputr  r   ro   zFailed to run on_end function: )r3   rP   rH  r   r  reprr  r  r   r   r   warning)	r   r   r   ri   outputs_error_
stacktracero   r   s	            r6   r   r   |  s     }}Y'H$Wd3w(G9LHF&&(
K=ZL1LLL0NN]]8$Fhv.	B8 /  	BNN<QC@AA	Bs   B   	C)CCc                B    |j                  dd       }|ri | |}|S | }|S )Nrf   )r3   )r   r}   rf   extra_inners       r6   _collect_extrarn    s;    ##K6I22	2  "r5   c           	        | j                  d      }t        |t        j                        r|S t        |t              rIt        j                  j                  || j                  d      t        | j                  d                  S t        |t              rKt        j                  j                  || j                  d      t        | j                  d                  }|S | j                  d      }|r|S t               }t        j                         bt        j                  j                  || j                  d            x}r0|r,||j                  d      s|j                  |j                  kD  r|S |S )Nr,   r   r-   )r   r-   ri   r   	callbacks)r3   rP   r   r  rH  from_headersr  r   from_dotted_orderr7   r!   get_langchain_core_versionrG  dotted_order)r}   r   r,   dortri   crtrts          r6   rH   rH     sa      *F&)++,&$  --"&&x0*?+>+>~+NO	 . 
 	
 &#  22"&&x0*?+>+>~+NO	 3 
 "":.H

 C..0<""77?..x8 8 
 
2 
  &6::k+B ??S%5%55	Jr5   c                
   |j                  d      xs i }|j                  d      }|j                  d      }|j                  d      }|j                  d      xs d}	t        j                         }
|xs
 t               }|j                  d      xs |j                  d      }|j                  d|      }t        i |d|i|j                  d            }t        j                         }|xs@ |r|j                  nd	xs. |j                  d
      xs |d
   xs t        j                         }|j                  d      }|j                  d      }|sat        j                         sMt        j                  t        j                  d       t        d	||
d	d	|j                  d      t                     S |xs t        t        j                               }t!        j"                  |       }|xs | j$                  }| j&                  }t)        ||      }t*        j                         }t,        j                         }t               }i |j                  d      xs i |xs i }|j/                  t*        j0                  |       |j3                  |xs i        d|d<   ||d<   t5        |g|i |}|j                  d      }|rP	  ||      j7                         D ci c]  \  }}|	|| }}}|r!t9        |t:              r|j3                  |       |j                  d      } | r		  | |      }|j                  d      xs g |xs g z   }!|j/                  t,        j0                  |!       |!|xs g z  }!|&|jC                  ||	|t        |      |d||!||      }"nTtE        jF                  tI        jJ                  |      ||t        |      |d||	tI        jJ                  |d      |||!|
      }"	 |"jM                          t        |"||
|||j                  d      |      }#|j/                  t        j0                  |#d
          |j/                  tP        j0                  |#d          |#S c c}}w # t<        $ r&}t>        jA                  d| d|        Y d	}~d	}~ww xY w# t<        $ r&}t>        jA                  d| d|        Y d	}~d	}~ww xY w# t<        $ r0}t>        jA                  d|"jN                   d|        Y d	}~d	}~ww xY w)r   r   r/   r.   r   r   r   rb   r   Nr-   rd   rl   z:LangSmith tracing is enabled, returning original function.ro   )r   r-   rb  r  r  ro   r:   rX   r   r   z&Failed to infer invocation params for r  r   zFailed to filter inputs for )rb   r   doc)rb   r   
serializedr   r.   r   rl   Tr  )
r  rb   rz  r   r   rd   r-   r   r.   r   zFailed to post run r   ))r3   r'   r`   rH   r/  r   r0  r  log_onceloggingDEBUGr   r   r   uuiduuid4r\   r   rq   rt   rn  r)   r(   r   r?   update_get_inputs_safer9   rP   rH  r   r   r   r  r   r  r  r	  r
  r  r$   )$rS   r   r}   r   rJ   r   r/   r.   r   r   rb  rb   client_r  
project_cvselected_projectrd   id_r   name_	docstringrm  r  r  r:   	metadata_r   r   r;   r<   invocation_paramsr   r   r  r   response_containers$                                       r6   r   r     s    "%%m4:K"":.Hv&D  *F"":.9'H!%%'M%9)9Ov&E/*=*=f*ED!!(F3G!.?.Hg.

80DK ""$J 	&(3K$$	& ~.		&
 >*	& ##%  +../EF


h
'Cu779MMW	
 #)'"&&x0 N
 	
 
"TZZ\"C!!$'I!DMMEI o>K]]_NJnGz*0bRI KK	y)X^$(Ik'K
i9$9&9F*../EF	P!5f!=!C!C!E!A1! ! !Z0A4%H  !23 %(()9:N	F#F+F   (.B:3CDEKK		5!	TZRE** ^ 
  + 
 ##%%c* ^ 
 !*!7!7$$" *!
$> -%#%""8, KK!!#5n#EFKK $$&8&CDA!
  	PLLA%1#NOO	P  	FLL7wbDEE	FP  >*7::,b<==>s`   Q/ 
Q)'Q),&Q/ &R! 0S )Q/ /	R8RR!	S*SS	T%TTc                    t        | dd      S )Nr   F)getattrrU   s    r6   rO   rO   T  s    42E::r5   c                    | j                   |i |}|j                          t        |j                        }|j	                  dd       |j	                  dd       | j
                  j                         D ]W  \  }}|j                  t        j                  j                  k(  s.||v s3|j                  ||          |j	                  |       Y |S )z:Return a dictionary of inputs from the function signature.r   Ncls)bind_partialapply_defaultsrH  	argumentsr   r   r9   r   r\   r   r   r  )r   r   rJ   boundr  
param_namer   s          r6   _get_inputsr  X  s     #I""D3F3E	U__%IMM&$MM%&11779 *
E::**666 Y&  :!67j)* r5   c                    	 t        | g|i |S # t        $ r*}t        j                  d|  d|        ||dcY d }~S d }~ww xY w)NzFailed to get inputs for r  )r   rJ   )r  r   r   debug)r   r   rJ   r   s       r6   r  r  l  sQ    096t6v66 002aSAB//0s    	A?AA)r   rh   r   )r:   zOptional[contextvars.Context]r   Dict[str, Any])r:   r  )r-   ra   r.   rk   r/   rj   r,   z0Optional[Union[run_trees.RunTree, Mapping, str]]r0   zOptional[bool]rJ   r   r   zGenerator[None, None, None])rS   Callable[P, R]r   z'TypeGuard[SupportsLangsmithExtra[P, R]])rS   r  r   zSupportsLangsmithExtra[P, R])rS   r	   r   boolr*  )r   r+  rb   ra   r/   r,  r.   rk   r   rm   r   z$Optional[Callable[[Sequence], dict]]r-   ra   r   rd  r   zOptional[Callable[..., dict]]r   rd  r   z8Callable[[Callable[P, R]], SupportsLangsmithExtra[P, R]])r   r   rJ   r   r   z/Union[Callable, Callable[[Callable], Callable]])r-   ra   r   ra   )rX  r	   r   r#   r   r   )r   rH  r}   r`   r   rH  )r}   r`   r   zOptional[dict]r   rh   r-  )rS   r	   r   r   r}   r   r   r   rJ   r   r   r   )r   zinspect.Signaturer   r   rJ   r   r   r  )]rt   
__future__r   r   
contextlibcontextvarsr   rQ   r\   r|  r~  rE   r   typingr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typing_extensionsr   r   	langsmithr   r  r   r   langsmith._internalr    r   langsmith.envr!   typesr"   rS  r#   	getLoggerrq   r   
ContextVarr  r$   r   r'   r(   r)   r  r*   r1   ru   r7   r=   rA   contextmanagerrL   get_run_tree_contextrV   rY   r^   r`   rw   ry   r{   rX   r   r  rZ  r   r   r   r   rn  rH   r   rO   r  r  r4   r5   r6   <module>r     s   7 "          $     0 3 ) & 4 &#1			8	$F;))(93D3D*EF  6&&x}5otT3xS	23GTJ<K""8DcN#;<[RVW	9;))(4.9  !40 " .2A*AA  #' $)-?C"/./. /. '	/.
 =/. /. /. !/. /.f , 
,9Ye 9  C4 cN Xwq!t}  D 
'
'!' 
'
 
%,C ,0 $)-6:"&7;59>BC"C C *	C
 C 'C 4C  C 5C 3C <C >C 
CCCC 5CLM7 M7`
p+j 	!)5 	!;iu ;" "%)B"BB #B 
	B2 "/#// !/j 15A
A$A .A 	A
 A AH; ),8;(0 0),08;00r5   