
    =Ki2                      % S r SSKJr  SSKrSSKrSSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKJrJrJrJrJrJrJr  SSKJr  SSKJrJrJrJrJrJrJrJrJrJrJrJ r J!r!J"r"J#r#  SSK$J%r%J&r&J'r'J(r(  SSK)J*s  J+r+  SSK,J-r.  SS	K,J/r/J0r0J1r1  SS
K2J3r4  SSK5J6r6  SSK7J8r8  \(       a  SSK9J:r:  SSK;J<r<  \	Rz                  " \>5      r?\+R                  \+R                  \+R                  \+R                  \+R                  \+R                  \/R                  \/R                  S.rHS\IS'   SrJSqKS\IS'   SXS jrL\R                      SYS j5       rNSZS jrO S[   S\S jjrP\R                  SSSSSSSSS.                   S]S jj5       rQ\LrRS^S jrSSSSSSSSSSS.	                     S_S jjrTS`S jrU " S S \S!S"9rV\" S#S$S%9rW\%" S&5      rX\# " S' S(\\\X\W4   5      5       rYSS).       SaS* jjrZ\"    SbS+ j5       r[\" ScSSSSSSSSSSS!SSS,.                             SdS- jjj5       r[      SeS. jr[ " S/ S05      r\SfS1 jr]SgS2 jr^1 S3kr_ " S4 S5\S!S"9r` " S6 S7\S!S"9ra      ShS8 jrb  Si       SjS9 jjrcSkS: jrd S[     SlS; jjre   Sm           SnS< jjrf   Sm         SoS= jjrgSpS> jrh        SqS? jri        SqS@ jrjS[SrSA jjrk S[     SsSB jjrl\R                  " SCSD9 S[     SsSE jj5       rn S[     SsSF jjroSSG.         StSH jjrpS[SuSI jjrq S[             SvSJ jjrrSSK.               SwSL jjrs\" SM5      rt " SN SO\\t   5      ru " SP SQ\u\\t   5      rv " SR SS\u\\t   5      rwSxST jrxSySU jrySzSV jrzS{SW jr{\+R                  rA\+R                  rB\+R                  rC\+R                  rD\+R                  rE\+R                  r@g)|z1Decorator for creating a run tree from functions.    )annotationsN)AsyncGeneratorAsyncIterator	Awaitable	GeneratorIteratorMappingSequence)copy_context)TYPE_CHECKING	AnnotatedAnyCallableGenericLiteralOptionalProtocol	TypedDictTypeVarUnioncastget_type_hintsoverloadruntime_checkable)	ParamSpec	TypeGuardget_args
get_originclient)	run_treesschemasutils)_aiter)_runtime_env)WriteReplica)TracebackType)Runnableparentproject_nametagsmetadataenabledr    replicasdistributed_parent_idz!dict[str, contextvars.ContextVar]_CONTEXT_KEYSzlangsmith/run_helpers.pyOptional[bool]_OTEL_AVAILABLEc                 >    [         R                  R                  5       $ )zGet the current run tree.)_context_PARENT_RUN_TREEget     W/var/www/html/dynamic-report/venv/lib/python3.13/site-packages/langsmith/run_helpers.pyget_current_run_treer;   H   s    $$((**r9   c              #     #    [         R                  R                  U 5      n Sv   [         R                  R                  U5        g! [         R                  R                  U5        f = f7f)aq  Set a RunTree as the active tracing parent within this block.

Unlike `tracing_context`, this only sets `_PARENT_RUN_TREE` and nothing
else, making it safe to use in isolated threads where you want precise
control over which run acts as the parent without inheriting or overwriting
other context variables.

Args:
    run_tree: The RunTree to use as the active parent.
N)r5   r6   setreset)run_treetokens     r:   set_tracing_parentrA   M   sM      %%))(3E/!!''.!!''.s    A+A  A+!A((A+c                     [        5       nUc  [        R                  S5        gUR                  R	                  U 5        g)z(Update metadata on the current run tree.NzFNo active run tree found. Call `set_run_metadata` inside a traced run.)r;   LOGGERwarningr-   update)r-   r?   s     r:   set_run_metadatarF   b   s=    #%HT	

  	  *
r9   c           	     Z   U c  [         R                  R                  5       [         R                  R                  5       [         R                  R                  5       [         R
                  R                  5       [         R                  R                  5       [         R                  R                  5       [        R                  R                  5       [        R                  R                  5       S.$ [        R                  5        VVs0 s H  u  pXR                  U5      _M     snn$ s  snnf )z Get the current tracing context.r)   )r5   r6   r7   _PROJECT_NAME_TAGS	_METADATA_TRACING_ENABLED_CLIENTr!   	_REPLICAS_DISTRIBUTED_PARENT_IDr1   items)contextkvs      r:   get_tracing_contextrS   n   s     //335$22668NN&&( **..000446&&**,!++//1%.%E%E%I%I%K	
 		
 +8*=*=*?@*?$!A{{1~*?@@@s   D')r+   r,   r-   r*   r.   r    r/   r0   c              +  *  #    U(       a  [         R                  " SU S3[        5        [        5       n	USLa%  [	        SU=(       d    UR                  S5      05      OSn
UnUcd  U
ba  [        [        U=(       d    / 5      [        U
R                  =(       d    / 5      -  5      n0 U
R                  EU=(       d    0 EnU
R                  nUb  UOU	R                  S5      n[        U
U UUUUUUS.5         Sv   [        U	5        g! [        U	5        f = f7f)	a  Set the tracing context for a block of code.

Args:
    project_name: The name of the project to log the run to.
    tags: The tags to add to the run.
    metadata: The metadata to add to the run.
    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.
    client: The client to use for logging the run to LangSmith.
    enabled: Whether tracing is enabled.

        Defaults to `None`, meaning it will use the current context value or environment variables.
    replicas: A sequence of `WriteReplica` dictionaries to send runs to.

        Example: `[{"api_url": "https://api.example.com", "auth": {"api_key": "key"}, "project_name": "proj"}]`
        or `[{"project_name": "my_experiment", "updates": {"reference_example_id": None}}]`
    distributed_parent_id: The distributed parent ID for distributed tracing. Defaults to None.
z Unrecognized keyword arguments: .Fr*   
parent_runNr.   r)   )warningswarnDeprecationWarningrS   _get_parent_runr7   sortedr=   r,   r-   id_set_tracing_context)r+   r,   r-   r*   r.   r    r/   r0   kwargscurrent_contextrV   distributed_parent_id_to_uses               r:   tracing_contextra      s    B .vha8	
 *+O  	6#EVZZ-EFG 
 $9 #+
0Fc$*"oJOO,Ar(BBC>j))>hn">'1}}$ ,g/2E2Ei2PG (  %A		
._-_-s   C0D3D 7DDDc                    [        U 5      =(       de    [        U [        R                  5      =(       a    [        U R                  5      =(       d(    [        U S5      =(       a    [        U R                  5      $ )z.Check if a function is `@traceable` decorated.__call__)_is_traceable_function
isinstance	functoolspartialfunchasattrrc   rh   s    r:   is_traceable_functionrk      sU     	t$ 	QtY../U4J4994U	QD*%O*@*Or9   	namer-   r,   r    	reduce_fnr+   process_inputsprocess_outputsprocess_chunkc       	        T    [        U 5      (       a  U $ [        UUUUUUUUU	S9	" U 5      $ )z$Ensure that a function is traceable.rl   )rk   	traceable)
rh   rm   r-   r,   r    rn   r+   ro   rp   rq   s
             r:   ensure_traceablert      sF     T""!%'#
 
 
r9   c                    [         R                  " U 5      =(       d3    [        U S5      =(       a     [         R                  " U R                  5      $ )z;Inspect function or wrapped function to see if it is async.__wrapped__)inspectiscoroutinefunctionri   rv   rj   s    r:   is_asyncry      s:    &&t, m$V)D)DTEUEU)Vr9   c                      \ rS rSr% SrS\S'    S\S'    S\S'    S	\S
'    S\S'    S\S'    S\S'    S\S'    S\S'    S\S'    S\S'   S\S'   Srg)LangSmithExtra   z<Any additional info to be injected into the run dynamically.Optional[str]rm   Optional[ls_client.ID_TYPE]reference_example_idOptional[dict]	run_extraz0Optional[Union[run_trees.RunTree, str, Mapping]]r*   Optional[run_trees.RunTree]r?   r+   Optional[dict[str, Any]]r-   Optional[list[str]]r,   run_idOptional[ls_client.Client]r    z-Optional[Callable[[run_trees.RunTree], None]]_on_success,Optional[Callable[[run_trees.RunTree], Any]]on_endr8   N__name__
__module____qualname____firstlineno____doc____annotations____static_attributes__r8   r9   r:   r{   r{      sn    F
$55-.<<D)))'&&(
,''"&&$>>88Qr9   r{   F)totalRT)	covariantPc                  8    \ rS rSrSrSS.       SS jjrSrg)SupportsLangsmithExtrai  zNImplementations of this Protocol accept an optional langsmith_extra parameter.Nlangsmith_extrac                   g)a*  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.

Nr8   )selfr   argsr^   s       r:   rc   SupportsLangsmithExtra.__call__  s    $ 	r9   r8   )r   zP.argsr   Optional[LangSmithExtra]r^   zP.kwargsreturnr   )r   r   r   r   r   rc   r   r8   r9   r:   r   r     s:    X
 59 2 	
 
 r9   r   outputsc                    U R                   =(       d    0 R                  S5      nU=(       d    0 R                  S5      =(       d    U$ )Nusage_metadata)r-   r7   )r?   r   r^   from_metadatas       r:   _extract_usager   1  s;     &&,"112BCMMr/0AMAr9   c                    g Nr8   rj   s    r:   rs   rs   ;  s     $'r9   )rm   r-   r,   r    rn   r+   ro   rp   rq   _invocation_params_fndangerously_allow_filesystemr.   exceptions_to_handlec                   g r   r8   )run_typerm   r-   r,   r    rn   r+   ro   rp   rq   r   r   r.   r   s                 r:   rs   rs   A  s	    " @Cr9   c                   ^^^^^^ [        [        R                  U (       a  [        U S   [        5      (       a  U S   OUR                  SS5      =(       d    S5      mT[        ;  a$  [        R                  " ST S[         ST S35        [        U 5      S	:  a  [        R                  " S
5        SU;   a  [        R                  " S[        5        UR                  SS5      mUR                  SS5      m[        UR                  SS5      UR                  SS5      UR                  SS5      UR                  SS5      UR                  SS5      UR                  SS5      TUR                  SS5      UR                  SS5      UR                  SS5      UR                  SS5      TUR                  SS5      S9mUR                  SS5      m[        R                  " [        TS9mU(       a6  [        R                  " S[        UR!                  5       5       S3[        5        S UUUUUU4S jjn[        U 5      S	:X  a%  [#        U S   5      (       a  U(       d  U" U S   5      $ U$ )!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`.
    dangerously_allow_filesystem: Whether to allow filesystem access for attachments.

        Defaults to `False`.

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

        Defaults to `None`, which will use the default value from the current context.
    exceptions_to_handle: Exception types to ignore when logging errors.

        If an exception of one of these types is raised, the run will still be recorded
        but the error field will be `None` instead of containing the full traceback.

        Defaults to `None`.

Returns:
    The decorated function.

!!! note

    Requires that `LANGSMITH_TRACING_V2` be set to 'true' in the environment.

Examples:
    !!! example "Basic usage"

        ```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"}))
        ```

    !!! example "Streaming data with a generator"

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


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

    !!! example "Async streaming data"

        ```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())
        ```

    !!! example "Specifying a run type and name"

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


        another_function(5, 6)
        ```

    !!! example "Logging with custom metadata and tags"

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


        tagged_function(5)
        ```

    !!! example "Specifying a custom client and project name"

        ```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"})
        ```

    !!! example "Manually passing `langsmith_extra`"

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


        manual_extra_function(5, langsmith_extra={"metadata": {"version": "1.0"}})
        ```

    !!! example "Handling specific exceptions"

        ```python
        @traceable(exceptions_to_handle=(ValueError, TypeError))
        def function_with_handled_exceptions(x):
            if x < 0:
                raise ValueError("Negative value")  # Won't send error in the trace
            return x**2


        function_with_handled_exceptions(-5)
        ```
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.rn   r.   rm   r-   r,   r    r+   ro   rq   r   r   Fr   )extra_outerrm   r-   r,   r    r+   r   ro   rq   invocation_params_fnr   r.   r   rp   )outputs_processorzHThe following keyword arguments are not recognized and will be ignored: rU   c                  >^ ^
^ [         R                  " T 5      nUR                  R                  SS 5      S LmUR                  R                  SS 5      S Lm
[        R
                  " T 5      S S.       SUUU U
U4S jjj5       n[        R
                  " T 5      S S.       SUUU U
UU4S jjj5       n[        R
                  " T 5      S S.       SUUU U
4S jjj5       n[        R
                  " T 5      S S.       SUUU U
UU4S jjj5       n[        R
                  " T 5      S S.       SUUU U
UU4S jjj5       n[        R
                  " T 5      S S.       SUUU U
UU4S	 jjj5       n[         R                  " T 5      (       a  UnOG[         R                  " T 5      (       a  UnO)[        T 5      (       a  T(       a  UnOUnOT(       a  UnOUn[        US
S5        [        USTR                  S5      TTTR                  S5      TR                  S5      T S.5        [         R                  " U5      n	U	R                  R                  S5      (       d  U	R                  / S U	R                  R                  5        5       Q[         R                  " S[         R                  R                  S S9PS U	R                  R                  5        5       QS9n	Xl        U$ )Nr?   configr   c           	       >^^^	#    T(       d  TR                  SS5        [        R                  " [        TTU TTS9I Sh  vN n [        R                  " 5       nT(       a  US   TS'   [        US   5      m	T	(       af  UUUU	4S jnU(       a&  [        R                  " U" 5       US   S9I Sh  vN nO[        S0 [        US   5      D6   U" 5       I Sh  vN nSSS5        OYT" T0 TD6nU(       a   [        R                  " XsS   S9I Sh  vN nO*[        S0 [        US   5      D6   UI Sh  vN nSSS5        [        R                  " T
UWS
9I Sh  vN   U$  GN N N! , (       d  f       N5= f Ng NF! , (       d  f       NJ= f! [         aC  n[        U5        [        R                  " [        R                  " T
X8S	95      I Sh  vN    e SnAff = f N7f)z"Async version of wrapper function.r   Ncontainer_inputr   r   r^   new_runr?   c                 j   >#    T   T" T 0 TD6I S h  vN sS S S 5        $  N! , (       d  f       g = f7fr   r8   r   rh   r^   otel_context_managers   r:   run_with_otel_contextRtraceable.<locals>.decorator.<locals>.async_wrapper.<locals>.run_with_otel_contextd  s,     1)-t)>v)>#> 21#> 21s    3" "
3"
03rP   rP   errorr   r8   )pop
aitertoolsaio_to_thread
_setup_runasyncio_accepts_context_maybe_create_otel_contextasynciocreate_taskra   rS   BaseException_cleanup_tracebackshield)r   r   r^   run_containeraccepts_contextr   function_resultfr_coroer   _on_run_endr   rh   func_accepts_configfunc_accepts_parent_runs    ``      @r:   async_wrapper3traceable.<locals>.decorator.<locals>.async_wrapperH  s     '

8T*",":": / /# M*","D"D"F*)6y)AF:&'A!),($ (? ? '070C0C13]9=U1 +
 - 1-	2JK 5J4K.KO 
 #D3F3G&070C0C#9-E1 +
 - 1-	2JK 5<mO **]O   #"o0+ /L + /<  ! "1%nn,,[-Q   s   :G EGA)F /E!0F 4G5F E%E#E%F $G%)F E6F GF +E:1E82E:6F >GGG!F #E%%
E3/F 2G3F 8E::
FF GF 
G7GGGGGc                 >#    T(       d  UR                  SS 5        [        R                  " [        TTU UUS9I S h  vN n/ n T(       a  US   US'   [	        US   5      nT" U0 UD6n[        R
                  " 5       n[        R                  " U5      (       aQ  U(       a   [        R                  " XcS   S9I S h  vN nO*[        S0 [        US   5      D6   UI S h  vN nS S S 5        [        UUUS   (       a  US   R                  S:H  OSUUTR                  S	5      US
9  S h  vN nU7v   M   N N{ NZ! , (       d  f       N^= f N"
 O\! [         aO  n	[!        U	5        [        R"                  " [        R                  " T
UU	[%        UT5      S95      I S h  vN    e S n	A	ff = f[        R                  " T
U[%        UT5      S9I S h  vN    g 7f)Nr   r   r   r?   rP   r   llmFrq   )	generatorr   
is_llm_runr   resultsrq   r   r   r   r   r8   )r   r   r   r   r   r   rw   iscoroutiner   r   ra   rS   _process_async_iteratorr   r7   r   r   r   _get_function_result)r   r   r^   r   r   r   async_gen_resultr   itemr   r   r   rh   r   r   rn   s             r:   async_generator_wrapper=traceable.<locals>.decorator.<locals>.async_generator_wrapper  s     '

8T*",":": / /# M "$G2*)6y)AF:&
 (B!),($ $(#8#8 ","D"D"F&&'788&181D1D,I6N2 ,(
 - 1-	2JK 6F/E,
 #:."/ )3 &i099UB"$3#"1"5"5o"F)=# $ Ja2, 0F 
 # ! 
"1%nn,,#% 4Wi H	   
 **,Wi@  s   :GD5GA6E ;D7<E D;D9D;#AE %E)E*E-E 5G7E 9D;;
E	E EE G
F)AF$F F$$F))&GGGc                  >^^^ T(       d  TR                  SS5        [        TT
U TTS9n[        R                  " T5      R                  R                  SS5      SLn U(       a  US   TS'   [        US   5      mT(       a  UUUU4S jnUS   R                  U5      nOUS   R                  " T/TQ70 TD6n T	" X6S	9  U$ ! [         a  n[        U5        T	" X7S9  e SnAff = f)
>Create a new run or create_child() if run is passed in kwargs.r   Nr   r?   r   c                 N   > T   T" T 0 TD6sS S S 5        $ ! , (       d  f       g = fr   r8   r   s   r:   r   Ltraceable.<locals>.decorator.<locals>.wrapper.<locals>.run_with_otel_context  s    1#'#8#8 211s   
$rP   r   r   )
r   r   rw   	signature
parametersr7   r   runr   r   )r   r   r^   r   r   r   r   r   r   r   r   rh   r   s    ``     @r:   wrapper-traceable.<locals>.decorator.<locals>.wrapper  s    '

8T*& / /M !!$'2266z4HPTT $*)6y)AF:&'A!),($ (9 9 '4I&>&B&B-'O '4I&>&B&B'#''-'O ?"" ! "1%M3s   AC  C 
C#CC#c           	   ?  4  >#    T(       d  UR                  SS 5        [        TTU UUS9n[        R                  " T5      R                  R                  SS 5      S Ln/ nS n U(       a  US   US'   US   R                  " T/UQ70 UD6n[        US   5      n[        UUTS:H  UTR                  S5      US9 S h  vN nUb  UR                  U5        T
" U[        UT5      S
9  U$  N+! [         a#  n	[        U	5        T
" UU	[        UT5      S	9  e S n	A	ff = f7f)Nr   r   r?   r   rP   r   rq   )r   r   rq   r   r   r   )r   r   rw   r   r   r7   r   r   _process_iteratorappendr   r   r   )r   r   r^   r   r   r   function_returngenerator_resultr   r   r   r   rh   r   rn   r   s             r:   generator_wrapper7traceable.<locals>.decorator.<locals>.generator_wrapper   sR     '

8T*& / /M !!$'2266z4HPTT $ "$G#'O*)6y)AF:&#0#;#?#?#Vt#Vv#V 'A!),($ .?$!'50#"1"5"5o"F)=. # #.NN?3 /CGY/WX""-# ! "1%!0)D
 s=   AD!AC( :C&;C( D&C( (
D2DDDc                n  > T	(       d  UR                  SS 5        [        TTU UUS9n T
(       a  US   US'   US   R                  " T/UQ70 UD6n[        US5      (       a  [        XCT5      $ [        US5      (       a  [        XCT5      $ T" X4S	9  U$ ! [         a  n[	        U5        T" X5S9  e S nAff = f)
Nr   r   r   r?   rP   r   __iter__	__aiter__r   )r   r   r   	Exceptionr   ri   _TracedStream_TracedAsyncStreamr   r   r^   trace_containerstreamr   r   r   rh   r   r   rn   s         r:   stream_wrapper4traceable.<locals>.decorator.<locals>.stream_wrapper8  s     '

8T*( / /O*)8)CF:&(377NtNvN vz**$ViHH--)&9MM 8M  "1%O5s   (B 
B4B//B4c           	       >#    T	(       d  UR                  SS 5        [        R                  " [        TTU UUS9I S h  vN n T
(       a  US   US'   T" U0 UD6I S h  vN n[        US5      (       a  [        XCT5      $ [        US5      (       a  [        XCT5      $ [        R                  " TX4S9I S h  vN   U$  N} N_! [         a$  n[        R                  " TX5S9I S h  vN    e S nAff = f N;7f)	Nr   r   r   r?   r   r   r   r   )r   r   r   r   r   ri   r   r   r   s         r:   async_stream_wrapper:traceable.<locals>.decorator.<locals>.async_stream_wrapperY  s      '

8T*$.$<$< / /% O*)8)CF:&#T4V44
 v{++)&9MM,,$ViHH **;XXXM3 5  ..{OUUU Ys^   :C2B;C2B? B=B? "AC24C05C2=B? ?
C-	C(!C$"C((C--C2__langsmith_traceable__T__traceable_config__ro   r,   r-   )ro   rp   r.   r,   r-   wrappedc              3  z   #    U  H1  nUR                   [        R                  R                  :w  d  M-  Uv   M3     g 7fr   kindrw   	ParameterVAR_KEYWORD.0params     r:   	<genexpr>/traceable.<locals>.decorator.<locals>.<genexpr>  1      %<E ::):):)F)FF %<   ,;	;)defaultc              3  z   #    U  H1  nUR                   [        R                  R                  :X  d  M-  Uv   M3     g 7fr   r  r
  s     r:   r  r    r  r  )r   )r   r   r   r   r^   r   r   r   )r   r   r   r   r^   r   r   r   )rw   r   r   r7   rf   wrapsisasyncgenfunctionisgeneratorfunctionry   setattrreplacevaluesr  KEYWORD_ONLY__signature__)rh   func_sigr   r   r   r   r   r   selected_wrappersigr   r   r   r   r.   r   rn   r   s   `         @@r:   	decoratortraceable.<locals>.decoratorC  se   $$T*"*"5"5"9"9*d"KSW"W&1155hETQ		 9=?	#?	#5?	# ?	# 	?	# ?	# 
?	#B 
	DHE	E	)AE	TWE	E	 E	 
E	N 
	 9=+	#+	#5+	# +	# 	+	# +	# 
+	#Z 
	DH2	#2	#)A2	#TW2	#2	# 2	# 
2	#n 
	DH		)A	TW		 	 
	@ 
	DH		)A	TW		 	 
	@ %%d++)@((..0d^^#7 #0 #1 #*  ";TB""1"5"56F"G#4"'++F3+//
;	
  01~~!!(++++%(^^%:%:%< %% '"3"3"@"@$%(^^%:%:%<  C" .1*r9   )rh   r   )r   	ls_client
RUN_TYPE_Tre   strr   _VALID_RUN_TYPESrW   rX   lenrY   _ContainerInputrf   rg   _handle_container_endr[   keyscallable)	r   r^   r  r   r   r.   r   rn   r   s	      @@@@@@r:   rs   rs   U  s(   l  
47C00 G**Z.9'H ''%hZ/ABRAS T..6Zs<	
 4y1}$	

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

 

;-IjjD)G%JJw-ZZ%J-ZZ%zz(D)ZZ5zz"2D9jj$7#ZZ(?F%+ZZ0NPU%V#ZZ(>EO  

#4d;##+K
 Vfkkm$%Q(	
f  f T 4yA~(47++Fa!!r9   c                      \ rS rSrSr SSSSSSSSSSSSS.                           SS jjjrSS jr        SS jrSS jr   S       SS	 jjr	SS
 jr
   S       SS jjrSrg)tracei  a^  Manage a LangSmith run in context.

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

Args:
    name: Name of the run.
    run_type: Type of run (e.g., `'chain'`, `'llm'`, `'tool'`).
    inputs: Initial input data for the run.
    project_name: Project name to associate the run with.
    parent: Parent run.

        Can be a `RunTree`, dotted order string, or tracing headers.
    tags: List of tags for the run.
    metadata: Additional metadata for the run.
    client: LangSmith client for custom settings.
    run_id: Preset identifier for the run.
    reference_example_id: Associates run with a dataset example.

        Only for root runs in evaluation.
    exceptions_to_handle: Exception types to ignore.
    extra: Extra data to send to LangSmith.

        Use 'metadata' instead.

Examples:
    Synchronous usage:

    ```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:

    ```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:

    ```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
    ```
N)inputsr   r+   r*   r,   r-   r    r   r   r   attachmentsc                  UR                  SS5      U l        U(       a6  [        R                  " S[	        UR                  5       5       S3[        5        Xl        X l        X0l	        Xl
        X@l        XPl        X`l        UR                  S5      U l        Xpl        Xl        Xl        Xl        Xl        Xl        SU l        SU l        g)zOInitialize the trace context manager.

Warns if unsupported kwargs are passed.
_end_on_exitTzEThe `trace` context manager no longer supports the following kwargs: rU   r?   N)r   r.  rW   rX   r[   r'  rY   rm   r   r+  r,  r   r+   r*   r7   r?   r,   r-   r    r   r   r   r   old_ctx)r   rm   r   r+  r   r+   r*   r,   r-   r    r   r   r   r,  r^   s                  r:   __init__trace.__init__  s    0 #JJ~t<MMW&++-(),"
 	 &
( 

:.	 $8!$8!48'+r9   c                   [        5       U l        [        R                  " U R                  5      n[        R
                  R                  5       =(       d    [        R                  n[        R                  R                  5       =(       d    [        R                  nU R                  =(       d    U R                  R                  S5      n[        U R                  U R                  UU R                  S.5      n[        [!        U R"                  =(       d    / U=(       d    / -   5      5      n0 U R$                  =(       d    0 EU=(       d    0 ESS0EnU R&                  =(       d    0 nXxS'   [)        U R                  5      n	UbT  U(       aM  UR+                  U R,                  U R.                  U R0                  UU R2                  UU R4                  S9U l        O[8        R:                  " U R,                  [<        R>                  " U R.                  5      [<        R>                  " U R@                  SS9U R0                  UU	=(       d    S	[8        RB                  R                  5       U R2                  =(       d    0 UUU R4                  =(       d    0 S
9U l        USL a  U R6                  RE                  5         U(       a  [        R
                  R!                  U5        [        R                  R!                  U5        [        RF                  R!                  U R6                  5        [        RH                  R!                  U	5        [        RJ                  R!                  U5        U R6                  $ )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    )r*   r?   r    r+   	ls_methodr*  r-   )rm   r   r   r   r+  r,   r,  Taccept_nullr  )rm   r\   r   r   r   r+   r/   r+  r,   r    r,  )&rS   r/  r#   tracing_is_enabledr5   rI   r7   _GLOBAL_TAGSrJ   _GLOBAL_METADATAr    rZ   r*   r?   r+   r[   r=   r,   r-   r   _get_project_namecreate_childrm   r   r   r+  r,  r   r!   RunTreer   _ensure_uuidr   rM   postr6   rH   rL   )
r   r.   
outer_tagsouter_metadataclient_parent_run_tags_r-   r   project_name_s
             r:   _setuptrace._setup$  s    +,**4<<8^^'')BX-B-B
!++//1NX5N5N++;!1!1(!;%++ MM! $ 1 1	
 sDIIO
0@bABC
}}"
#
 
 jj&B"*J)$*;*;<"w&33YY{{!{{ ,, 4 DL %,,YY))$++6%.%;%;--4& !*7i",,002{{(b ,,2DL  d?LLNNu%""8,%%))$,,7""&&}5  )||r9   c                   U R                   c  gUb.  [        X R                  5      nU R                   R                  US9  U R                  bf  [
        R                  " U R                  5      nUSL a+  U R                  (       a  U R                   R                  5         [        U R                  5        g[        R                  " S[        5        g)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.
Nr   Tz(Tracing context was not set up properly.)r   '_format_error_with_exceptions_to_handler   endr/  r#   r6  r.  patchr]   rW   rX   RuntimeWarning)r   exc_type	exc_value	tracebacktbr.   s         r:   	_teardowntrace._teardowno  s      <<844B LL2&<<#..t||<G$4#4#4""$ .MMDnUr9   c                "    U R                  5       $ )zaEnter the context manager synchronously.

Returns:
    run_trees.RunTree: The newly created run.
)rD  r   s    r:   	__enter__trace.__enter__  s     {{}r9   c                (    U R                  XU5        g)zExit 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)rO  )r   rK  rL  rM  s       r:   __exit__trace.__exit__  s     	xI6r9   c                   #    [        5       n[        R                  " U R                  US9I Sh  vN n[	        [        U5      5        U$  N7f)zbEnter the context manager asynchronously.

Returns:
    run_trees.RunTree: The newly created run.
__ctxN)r   r   r   rD  r]   rS   )r   ctxresults      r:   
__aenter__trace.__aenter__  s@      n!//3GG056 Hs   -AA
Ac           
        #    [        5       nUb=  [        R                  " [        R                  " U R
                  XX4S95      I Sh  vN   O([        R                  " U R
                  XX4S9I Sh  vN   [        [        U5      5        g NB N7f)zExit 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.
NrY  )r   r   r   r   r   rO  r]   rS   )r   rK  rL  rM  r[  s        r:   	__aexit__trace.__aexit__  s      n..((NNH   **Y   	056s$   ABB
(B0B1BB)r.  r,  r    r   r   r+  r-   rm   r   r/  r*   r+   r   r   r?   r   r,   r   )rm   r"  r   ls_client.RUN_TYPE_Tr+  r   r   r   r+   r}   r*   zCOptional[Union[run_trees.RunTree, str, Mapping, Literal['ignore']]]r,   r   r-   Optional[Mapping[str, Any]]r    r   r   r~   r   r~   r   )Optional[tuple[type[BaseException], ...]]r,  zOptional[schemas.Attachments]r^   r   )r   run_trees.RunTree)rK  zOptional[type[BaseException]]rL  Optional[BaseException]rM  zOptional[TracebackType]r   NoneNNN)r   r   r   r   r   r0  rD  rO  rS  rV  r]  r`  r   r8   r9   r:   r*  r*    s{   <B *10,
 "& $&* $(04-1.2<@JN59#0,0, '0,
 0, 0, $0,
0, "0, .0, +0, ,0, :0,  H!0," 3#0,$ %0,dIVV/V +V +	V
 
V@ 37-1-1	7/7 +7 +	7
 
7
 37-1-1	7/7 +7 +	7
 
7 7r9   r*  c                   U (       a  U $ [         R                  5       n[        R                  R                  5       =(       dH    U(       a  UR                  OS =(       d,    [        R
                  =(       d    [        R                  " 5       $ r   )r6   r7   r5   rH   session_name_GLOBAL_PROJECT_NAMEr#   get_tracer_project)r+   prts     r:   r9  r9    sg    



 C 	""$ 	& #C	& ((	&
 ##%r9   c                *  ^^^  SSK JmJn  SSKJmJm  [        U 5      (       d(   [        R                  " U 5      n[        SU  SU 35      e " UUU4S	 jS
U5      nU" U 5      $ ! [         a  n[        S5      UeSnAff = f! [         a    Sn NUf = f)aJ  Convert a function wrapped by the LangSmith `@traceable` decorator to a `Runnable`.

Args:
    traceable_fn: 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                     >^  \ rS rSrSr S     SUUU 4S jjjr\    S	UUU4S jj5       r\    S
UUU4S jj5       rSr	U =r
$ )&as_runnable.<locals>.RunnableTraceablei  zyConverts a `@traceable` decorated function to a `Runnable`.

This helps maintain a consistent LangSmith tracing context.
c           
       > S nU R                  U5      n[        U5      (       a4  Ub  [        S5      e[        [        T/T4   U R                  U5      5      nO5[        U5      (       a%  [        [        T/T4   U R                  U5      5      nUc$  [        U R                  R                   SU 35      e[        TU ]-  U[        [        [        T/[        T   4      U5      5        g )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_asyncry   	TypeErrorr   r   rk   
_wrap_sync
ValueError	__class__r   superr0  r   r   )r   rh   afuncr  awrappedrr  rs  r{  s        r:   r0  /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r9   c                D   >^  SU 4S jjn[        [        TT/T4   U5      $ )z4Wrap a synchronous function to make it asynchronous.c                z   > [         R                  R                  [        [        U5      5      nT" S0 U DSSU00D6$ Nr   r?   r8   r!   r;  from_runnable_configr   dict)r+  r   r?   rh   s      r:   wrap_traceableIas_runnable.<locals>.RunnableTraceable._wrap_sync.<locals>.wrap_traceable/  s8    $,,AA$tVBTUMfMz86LMMr9   r+  r  r   rp  r   r   )r   r   )rh   r  rr  rs  rp  s   ` r:   ry  1as_runnable.<locals>.RunnableTraceable._wrap_sync)  s'    N %!8&!@A>RRr9   c                   >^ U c  g[        U 5      (       d  [        SU  35      e[        [        S[        T   4   U 5      mSU4S jjn[        [        TT/[        T   4   U5      $ )z.Wrap an async function to make it synchronous.NzXRunnableTraceable expects a function wrapped by the LangSmith @traceable decorator. Got .c                   >#    [         R                  R                  [        [        U5      5      nT" S0 U DSSU00D6I S h  vN $  N7fr  r  )r+  r   r?   afunc_s      r:   awrap_traceableKas_runnable.<locals>.RunnableTraceable._wrap_async.<locals>.awrap_traceableD  sA     $,,AA$tVBTU#UfUz8>TUUUUs   ?A	AA	r  )rk   rz  r   r   r   )r}  r  r  rr  rs  rp  s     @r:   rw  2as_runnable.<locals>.RunnableTraceable._wrap_async5  s    
 }(// 227:  (3	&(9#9:EBFV %0)F2CCDo r9   r8   r   )rh   r   r}  *Optional[Callable[..., Awaitable[Output]]]r   rh  )rh   zCallable[..., Output]r   z)Callable[[Input, RunnableConfig], Output])r}  r  r   z>Optional[Callable[[Input, RunnableConfig], Awaitable[Output]]])r   r   r   r   r   r0  staticmethodry  rw  r   __classcell__)r{  rr  rs  rp  s   @r:   RunnableTraceableru    s    	 AE		 >	 		 	@ 
		S'		S6		S 		S 
		S 
	=	K	 	 
	r9   r  )langchain_core.runnablesrp  rq  langchain_core.runnables.utilsrr  rs  ImportErrorrk   rw   	getsourcer   rz  )traceable_fnrq  r   fn_srcr  rr  rs  rp  s        @@@r:   as_runnabler    s    *K@ !..	,&&|4F **6~fXO
 	

G GN GR \**q  D
 	  	,+F	,s(   A% B %
B /A;;B BB>   r   toolr   parserprompt	embedding	retrieverc                      \ rS rSr% SrS\S'   S\S'   S\S'   S\S	'   S
\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   Srg)_TraceableContaineri[  3Typed response when initializing a run a traceable.r   r   r}   r+   outer_projectr   r?  r   r>  r   r   r   zcontextvars.ContextrP   r2   _token_event_loggedr.   re  r   r8   Nr   r8   r9   r:   r  r  [  sG    =((  ,,##==88  ''CCr9   r  c                      \ rS rSr% SrS\S'   S\S'   S\S'   S	\S
'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   Srg)r%  ik  r  r   r   r}   rm   r   r-   r   r,   r   r    Optional[Callable]rn   r+   rc  r    Optional[Callable[[dict], dict]]ro   rq   r   r2   r   r.   re  r   r8   Nr   r8   r9   r:   r%  r%  k  sY    =
&&
&&!!""44%%::"00CCr9   r%  c                |    U(       a  [        X5      (       a  g[        R                  " 5       n[        U 5       SU 3$ )zGFormat error for logging, suppressing traceback for handled exceptions.Nz

)re   r#   _format_excrepr)r   r   
stacktraces      r:   rG  rG  ~  s7    
 
5 G G""$J5k]$zl++r9   c                .   U R                  S5      nUc  g[        U[        5      (       a  UnOYUbR  [        US5      (       aA  [	        UR
                  5      (       a'  [        U[        5      (       d   UR                  SSS9nOS	U0n[        X4S
9=nb  XcR                  S'   U(       a  [        X R                  S5      5      nO3SnU R                  S5      =n(       a  [	        U5      (       a	   U" U5        UR!                  XGS9  U R                  S5      n	U	SL d  ["        R$                  " 5       SL a  UR'                  5         U R                  S5      =n
(       a  [	        U
5      (       a
   U
" U5        ggg! [         a3  n[        R                  S[        U5       SU 35        S	U0n SnAGN(SnAff = f! [         a#  n[        R                  " SU 35         SnANSnAff = f! [         a#  n[        R                  " SU 35         SnAgSnAff = f)zEnd the run.r   N
model_dumpTjson)exclude_nonemodez&Failed to use model_dump to serialize z
 to JSON: output)r?   r   r   r   r   z$Failed to run _on_success function: r   r   r.   r   zFailed to run on_end function: )r7   re   r  ri   r(  r  typer   rC   debugr   r-   rG  r   rW   rX   rH  r#   r6  rI  )	containerr   r   r?   dict_outputsr   usage
error_reprr   r.   r   s              r:   _container_endr    s    }}Y'H'4  G\**W''((7D))	/"--4f-ML !'*HHU.3*+<==!78

 
$==77K7Xk=R=RJH% LLL8mmI&G$%224<--)))x/?/?	A8 0@)5  	/LL8gzRSQTU %g.L		/$ ! J DQCHIIJ  	AMM;A3?@@	AsH   2E7 .F7 ,G' 7
F4(F//F47
G$GG$'
H1HHc                L    UR                  SS 5      nU(       a  0 U EUEnU$ U nU$ )Nr   )r7   )r   r   r   extra_inners       r:   _collect_extrar    s;    ##K6I22	2  "r9   c           	     :   U R                  S5      nUS:X  a  g [        U[        R                  5      (       a  U$ [        U[        5      (       aF  [        R                  R                  UU R                  S5      [        U R                  S5      5      S9$ [        U[        5      (       aH  [        R                  R                  UU R                  S5      [        U R                  S5      5      S9nU$ U R                  S5      nU(       a  U$ [        5       n[        R                  " 5       bo  [        R                  R                  XR                  S5      S9=n(       a<  U(       a3  Ub  UR                  S5      (       d  UR                  UR                  :  a  U$ U$ )	Nr*   ignorer    r+   )r    r+   r?   r   	callbacks)r7   re   r!   r;  r	   from_headersr9  r"  from_dotted_orderr;   r%   get_langchain_core_versionr  dotted_order)r   r   r*   dortr?   crtrts          r:   rZ   rZ     sv      *F&)++,,&'""  --"&&x0*?+>+>~+NO	 . 
 	
 &#  22"&&x0*?+>+>~+NO	 3 
 "":.H

 C..0<""77..x8 8 
 
2 
  &6::k+B+B ??S%5%55	Jr9   c                v   UR                  S5      =(       d    0 nUR                  S5      nUR                  S5      nUR                  S5      nUR                  S5      =(       d    Sn	UR                  SS5      n
[        R                  R                  5       nU=(       d
    [        5       nUR                  S	5      =(       d    UR                  S	5      nUR                  SU5      =(       d    [        R                  R                  5       n[        0 UESU0EUR                  S
5      5      n[        R                  R                  5       nU=(       dl    U(       a  UR                  OS=(       dP    UR                  S5      =(       d8    US   =(       d,    [        R                  =(       d    [        R                  " 5       nUR                  S5      nUR                  S5      nUR                  S5      nUSL d&  USLa  U(       d  [        R                  " 5       (       dl  [        R                  " [        R                  S5        [        SUUSSUR                  S5      UR                  S5      [        5       SUR                  S5      S9
$ [         R"                  " U 5      nU=(       d    [        R$                  " U 5      n['        XR5      n[        R(                  R                  5       =(       d    [        R*                  n[        R,                  R                  5       =(       d    [        R.                  n[        5       n0 UR                  S5      =(       d    0 EU=(       d    0 EnUR1                  [        R(                  R2                  U5        UR5                  U=(       d    0 5        SUS'   UUS'   [7        U/UQ7SU 0UD6u  nnUR                  S5      nU(       a_   U" U5      R9                  5        VVs0 s H  u  nnUc  M  UU_M     n nnU (       a&  [;        U [<        5      (       a  UR5                  U 5        UR                  S5      n"U"(       a	   U"" U5      nUR                  S5      =(       d    / U=(       d    / -   n#UR1                  [        R,                  R2                  U#5        U#U=(       d    / -  n#Ub  URE                  UU	UU#UUUS9n$O}UUU	[F        RH                  " USS9U[J        RL                  R                  5       UU#UUU
S .n%Ub  [F        RH                  " U5      U%S!'   [J        RN                  " S%0 [Q        [R        U%5      D6n$USL d  [        R                  " 5       SL a   U$RU                  5         [        U$UUUUUR                  S5      UR                  S5      USUUR                  S5      S#9n&UR1                  [        R                  R2                  U&S   5        UR1                  [X        R2                  U&S$   5        U&$ s  snnf ! [>         a&  n![@        RC                  SU SU! 35         Sn!A!GNSn!A!ff = f! [>         a&  n![@        RC                  SU SU! 35         Sn!A!GNSn!A!ff = f! [>         a0  n![@        RC                  S"U$RV                   SU! 35         Sn!A!GN3Sn!A!ff = f)&r   r   r-   r,   r    r   r   r   Frm   r   Nr+   r   r   r.   Tz>LangSmith tracing is not enabled, returning original function.r   r   r   )
r   r+   r  r?  r>  r   r   rP   r  r   rs   r3  rh   r   z&Failed to infer invocation params for : ro   zFailed to filter inputs for )rm   r   r+  r,   r   r   r,  r4  )rm   r+  r   r   r+   r/   r   r,   r    r,  r   r\   zFailed to post run )r   r+   r  r?  r>  r   r   rP   r  r.   r   r   r8   )-r7   r5   rH   r{   rL   rZ   rk  rl  r#   rm  r6  log_onceloggingDEBUGr  r   rw   r   _get_function_namer  rJ   r8  rI   r7  r   r=   rE    _get_inputs_and_attachments_saferO   re   r  r   rC   r   r:  r   r<  r!   rM   r;  r   r   r=  r\   r6   )'rh   r   r   r   r^   r   r-   r,   r    r   r   r  rm   r@  rA  
project_cvselected_projectr   id_r.   r   name_r  r?  r>  rP   	metadata_r+  r,  r   rQ   rR   invocation_paramsr   ro   rB  r   run_tree_kwargsresponse_containers'                                          r:   r   r     s)    "%%m4:K"":.Hv&D  *F"":.9'H#2#6#6&$  **..0M%9)9Ov&E/*=*=f*ED!!(F3Mx7G7G7K7K7MG!.?.Hg.

80DK ''++-J 	&(3K$$	& ~.		&
 >*	& ((	& ##%  +../EF


h
'C!!),G
 %t[E4L4L4N4NMML	
 #)''++M:"&&x0 N %!0!4!45K!L
 	
 !!$'I2E,,T2E >K''++-J1J1JN##%>)>)>JnGz*0bRI KK""&&	2X^$(Ik'K
:#'-FK +../EF	P!5f!=!C!C!E!!EA1!E  ! !Z0A4%H%H  !23 %(()9:N	F#F+F   (.B:3CDEKK""E*	TZRE**# + 
  $-$:$:$$% -!++//1 &,H
  ?$-$:$:3$?OD!##Ad3&@A$%224<	BLLN -%#%""8,#''6!,001GH KK&&**,>~,NOKK $$&8&CDI!
  	PLLA%1#NOO	P  	FLL7wbDEE	FP  	BLL.wzzl"QC@AA	Bs`   X 8
XX0X Y 0Y> X 
Y"YY
Y;Y66Y;>
Z8%Z33Z8c                     Ub  U" U5      n[        XUS9  g! [         a+  n[        R                  S[	        U5       35         SnAgSnAff = f)zHandle the end of run.Nr  z!Unable to process trace outputs: )r  r   rC   rD   r  )r  r   r   r   r   s        r:   r&  r&    sO    F('0Gy? F:47)DEEFs    
A!AAc                    [        U SS5      $ )Nr  F)getattrrj   s    r:   rd   rd     s    42E::r9   c                   U R                   " U0 UD6nUR                  5         [        UR                  5      nUR	                  SS5        UR	                  SS5        U R
                  R                  5        HZ  u  pVUR                  [        R                  R                  :X  d  M/  XT;   d  M6  UR                  XE   5        UR	                  U5        M\     U$ )z:Return a dictionary of inputs from the function signature.r   Ncls)bind_partialapply_defaultsr  	argumentsr   r   rO   r  rw   r  r	  rE   )r   r   r^   boundr  
param_namer  s          r:   _get_inputsr    s     ""D3F3E	U__%IMM&$MM%&11779
::**666 &  !67j) : r9   c                     [        U /UQ70 UD6$ ! [         a)  n[        R                  SU  SU 35        XS.s S nA$ S nAff = fNzFailed to get inputs for r  )r   r^   )r  r   rC   r  )r   r   r^   r   s       r:   _get_inputs_safer    sO    096t6v66 002aSAB//0s    
A?AAc                <   U R                   [        R                  :X  dG  [        U R                   5      [        :X  a+  [        S [        U R                   5       5       5      (       a  gUb  [        U R                   [        5      (       ay   [        USS9nUR                  U R                  5      nUbN  U[        R                  :H  =(       d4    [        U5      [        :H  =(       a    [        S [        U5       5       5      $  gg! [        [        [        4 a     gf = f)Nc              3  F   #    U  H  o[         R                  :H  v   M     g 7fr   r"   
Attachmentr  args     r:   r  !_is_attachment.<locals>.<genexpr>  s     P5Ocw)))5Os   !T)include_extrasc              3  H   #    U  H  nU[         R                  :H  v   M     g 7fr   r  r  s     r:   r  r    s"      #@C w111#@s    "F)
annotationr"   r  r   r   anyr   re   r"  r   r7   rm   	NameErrorrx  AttributeError)r  rh   
type_hintsresolved_annotations       r:   _is_attachmentr    s    7---5##$	1PXe>N>N5OPPP Ju'7'7==	'TBJ",.."<".*g.@.@@ 23y@  #+,?#@  /  9n5 		s   
A5D DDc                    U R                   R                  5        VVs1 s H  u  p#[        X15      (       d  M  UiM     snn$ s  snnf r   )r   rO   r  )r   rh   rm   r  s       r:   _attachment_args_helperr    sB    
 %//5577KD%& 	7  s
   AAi  )maxsizec                    [        X5      $ r   )r  r   rh   s     r:   _cached_attachment_argsr    s     #933r9   c                P     [        X5      $ ! [         a    [        X5      s $ f = fr   )r  rx  r  r  s     r:   _attachment_argsr    s,    8&y77 8&y778s   
 %%rj   c                   [        U /UQ70 UD6n[        X5      nU(       a.  0 0 pvUR                  5        H  u  pX;   a  XU'   M  XU'   M     Xg4$ U0 4$ ! [         a+  n
[        R                  SU  SU
 35        X#S.0 4s S n
A
$ S n
A
ff = fr  )r  r  rO   r   rC   rD   )r   rh   r   r^   inferredattachment_argsr+  r,  rQ   rR   r   s              r:   r  r    s    4y:4:6:*9;"$bK ('%&N !1I	 )
 &&| 429+RsCD/334s$   AA A 
B
 B?B
B
c                    U c/  [         R                  5        H  u  pUR                  S5        M     gU R                  5        H  u  p[         U   nUR                  U5        M!     g)zSet the tracing context.N)r1   rO   r=   )rP   rQ   rR   vars       r:   r]   r]     sQ    !'')DAEE$K *A
  r9   c              #  4  ^ ^#      U(       a  U U4S jnTS   R                  U5      nOTS   R                  [        T 5      nU(       a	  U" U5      nOUnU(       a  TS   (       ax  TR                  S5      (       db  TS   R                  S[        R                  R                  [        R                  R                  5      R                  5       SU0S.5        STS'   UR                  U5        Uv   M  ! [         a  n	U	R                  s S n	A	$ S n	A	ff = f7f)	NTc                    > TR                  S5      n U (       a)  [        U 5      nU(       a  U   [        T5      sS S S 5        $ [        T5      $ ! , (       d  f       N= fNr   )r7   r   nextr?   fresh_otel_contextr   r   s     r:   next_with_otel_context1_process_iterator.<locals>.next_with_otel_context)  sI    ,00;H-G-Q*-!3'+I "4!3	?* "4!3s   A
ArP   r   r  	new_tokenr@   rm   timer^   )r   r  r7   	add_eventdatetimenowtimezoneutc	isoformatr   StopIterationvalue)
r   r   r   r   rq   r   r  r   traced_itemr   s
   ``        r:   r   r     s     '#+ (	2667MN$Y/33D)D+D1"!),%))*?@@i(22 + ( 1 1 5 5$--11!#)+#*K"8 8<34NN;'JI J  wws/   DC/C5 5
D?D
DDDD)r   c                ^ ^#      U(       ad  U U4S jnU(       a&  [         R                  " U" 5       TS   S9I S h  vN nO[        S
0 [        TS   5      D6   U" 5       I S h  vN nS S S 5        OzU(       a5  [         R                  " [        R
                  " T 5      TS   S9I S h  vN nO>[        S
0 [        TS   5      D6   [        R
                  " T 5      I S h  vN nS S S 5        U(       a	  U" W5      n	OWn	U(       a  TS   (       ax  TR                  S5      (       db  TS   R                  S[        R                  R                  [        R                  R                  5      R                  5       SU	0S	.5        STS'   UR                  U	5        U7v   GM   GNd GN?! , (       d  f       N= f GN N! , (       d  f       N= f! [         a     g f = f7f)NTc                   >#    TR                  S5      n U (       a<  [        U 5      nU(       a*  U   [        R                  " T5      I S h  vN sS S S 5        $ [        R                  " T5      I S h  vN $  N+! , (       d  f       N.= f N7fr  )r7   r   r   py_anextr  s     r:   anext_with_otel_context8_process_async_iterator.<locals>.anext_with_otel_context]  si     ,00;H-G-Q*-!3-7-@-@-K'K "4!3!+!4!4Y!??? (L "4!3?s:   -BA8
A6A8#B1B	2B6A88
BBrP   r   r   r  r	  r@   r
  r8   )r   r   ra   rS   r   r  r7   r  r  r  r  r  r  r   StopAsyncIteration)
r   r   r   r   r   rq   r   r  r   r  s
   ``        r:   r   r   O  s    ;#@ #!(!4!4/1 -i 8" D ) -mI.FG &=%>> 
 #!(!4!4"++I6 -i 8" D ) -mI.FG &0%8%8%CC +D1"!),%))*?@@i(22 + ( 1 1 5 5$--11!#)+#*K"8 8<34NN;'Jq   ?   D 2  s   G6G F G F&$F#%F&)?G (F7)G F<F: F<$B=G #F&&
F40G :F<<
G
G 
GGGGTc                  b    \ rS rSrSr S     SS jjrSS jrS rS rS r	S	 r
SSS
 jjrSrg)_TracedStreamBasei  z%Base class for traced stream objects.Nc                    Xl         X l        SU l        X0l        / U l        US   (       a  US   R
                  S:H  U l        g SU l        g )NFr   r   )__ls_stream____ls_trace_container____ls_completed____ls_reduce_fn____ls_accumulated_output__r   __is_llm_run__)r   r   r   rn   s       r:   r0  _TracedStreamBase.__init__  sZ     $&5# % )24& y) I&//58 	  	r9   c                .    [        U R                  U5      $ r   )r  r  )r   rm   s     r:   __getattr___TracedStreamBase.__getattr__  s    t))400r9   c                |    [        [        [        U R                  5      [        U R                  5      -   5      5      $ r   )listr=   dirr{  r  rR  s    r:   __dir___TracedStreamBase.__dir__  s+    CDNN+c$2D2D.EEFGGr9   c                $    SU R                   < S3$ )Nz
Traceable())r  rR  s    r:   __repr___TracedStreamBase.__repr__  s    D..133r9   c                ,    [        U R                  5      $ r   )r"  r  rR  s    r:   __str___TracedStreamBase.__str__  s    4%%&&r9   c                     U R                   (       d  U R                  5          U R                  R	                  5         g ! [         a     N(f = f! [         a     g f = fr   )r!  
_end_tracer   r  __del__rR  s    r:   r7  _TracedStreamBase.__del__  sX    	((!	&&(  		  		s    !? A 
AA
AAc                    U R                   (       a  g  U R                  (       a  U R                  U R                  5      nOU R                  n[        U R                  UUS9  SU l         g ! SU l         f = f)Nr  T)r!  r"  r#  r  r   )r   r   reduced_outputs      r:   r6  _TracedStreamBase._end_trace  sg      	)$$!%!6!6t7U7U!V!%!?!?++& %)D!DD!s   AA* *	A3)r$  r#  r!  r"  r  r   r   )r   z$Union[Iterator[T], AsyncIterator[T]]r   r  rn   r  )rm   r"  r   rg  )r   r   r   r   r   r0  r'  r,  r0  r3  r7  r6  r   r8   r9   r:   r  r    sO    / )-	
4
 -
 &	
"1H4'	) )r9   r  c                  f   ^  \ rS rSrSr  S	       S
U 4S jjjrSS jrSS jrS rS r	Sr
U =r$ )r   i  z>A wrapper for synchronous stream objects that handles tracing.c                   > [         TU ]  UUUS9  Xl        [        U R                  U R                  U R
                  U R                  US9U l        g )Nr   r   rn   )r   r   rq   )r|  r0  r  r   r   r$  r#  __ls__gen__r   r   r   rn   rq   r{  s        r:   r0  _TracedStream.__init__  s\     	+ 	 	

 $,''**22'
r9   c                l     [        U R                  5      $ ! [         a    U R                  5         e f = fr   )r  r@  r  r6  rR  s    r:   __next___TracedStream.__next__  s4    	(()) 	OO	s    3c              #     #     U R                    S h  vN   U R                  5         g  N! [         a   n[        U5        U R                  US9  e S nAff = f7fNr   )r@  r6  r   r   )r   r   s     r:   r   _TracedStream.__iter__  sR     	'''' OO ( 	q!OO!O$	s0   A+ )+ A+ 
AAAAc                :    U R                   R                  5         U $ r   )r  rS  rR  s    r:   rS  _TracedStream.__enter__  s    $$&r9   c                     U R                   R                  XU5      U R                  U(       a  US9  $ S S9  $ ! U R                  U(       a  US9  f S S9  f = frG  )r  rV  r6  r   rK  exc_valexc_tbs       r:   rV  _TracedStream.__exit__  sM    	A%%..x&IOOX'O@4O@DOOX'O@4O@s	   9 A)r@  r  NN)r   Iterator[T]r   r  rn   r  rq   r  r   r  )r   rQ  )r   r   r   r   r   r0  rD  r   rS  rV  r   r  r{  s   @r:   r   r     sY    H )-,0

 -
 &	

 *
 
*A Ar9   r   c                  t   ^  \ rS rSrSr  S
       SU 4S jjjrSSS jjrSS jrSS jrS r	S r
S	rU =r$ )r   i
  z?A wrapper for asynchronous stream objects that handles tracing.c           	        > [         TU ]  UUUS9  Xl        [        U R                  U R                  U R
                  [        R                  " 5       U R                  US9U l	        g )Nr?  )r   r   r   r   r   rq   )
r|  r0  r  r   r   r$  r   r   r#  _TracedAsyncStream__ls_genrA  s        r:   r0  _TracedAsyncStream.__init__  sg     	+ 	 	

 $/((55**&>>@22'
r9   c                   #    [        5       n[        R                  " [        R                  " U R
                  XS95      I S h  vN   [        [        U5      5        g  N7f)NrY  )r   r   r   r   r   r6  r]   rS   )r   r   r[  s      r:   _aend_trace_TracedAsyncStream._aend_trace#  sK     nnn$$T__eG
 	
 	
 	056	
s   AAAAc                   #     [        [        [        R                  " U R                  5      I S h  vN 5      $  N! [
         a    U R                  5       I S h  vN    e f = f7fr   )r   r  r   r  rV  r  rY  rR  s    r:   	__anext___TracedAsyncStream.__anext__*  sO     	!4!4T]]!CCDDC! 	""$$$	s1   A$-< :
< A$< A!AA!!A$c                  #     U R                     S h  vN nU7v   M   N
 U R                  5       I S h  vN    g ! [         a    U R                  5       I S h  vN    e f = f7fr   )rV  rY  r   )r   r   s     r:   r   _TracedAsyncStream.__aiter__1  s]     	%"mm d
m ""$$$	  	""$$$	sF   A%= " "= "= A%9A%A"AA""A%c                V   #    U R                   R                  5       I S h  vN   U $  N7fr   )r  r]  rR  s    r:   r]  _TracedAsyncStream.__aenter__;  s'       ++--- 	.s   )')c                   #     U R                   R                  XU5      I S h  vN U R                  5       I S h  vN   $  N N! U R                  5       I S h  vN    f = f7fr   )r  r`  rY  rL  s       r:   r`  _TracedAsyncStream.__aexit__?  sP     	%++55hPP""$$$ Q$$""$$$sG   A"A A A A"AA" A A"AAAA")__ls_genr  rP  )r   AsyncIterator[T]r   r  rn   r  rq   r  r   r<  rR  )r   re  )r   r   r   r   r   r0  rY  r\  r   r]  r`  r   r  rS  s   @r:   r   r   
  s\    I )-,0
 
 -
 &	

 *
 
,7%% %r9   r   c                    U (       a  Ub	   U" U 5      $ U $ g ! [          a!  n[        R                  U5        U s S nA$ S nAff = fr   )r   rC   r   )r   rn   r   s      r:   r   r   F  sI      ))
 N  ! Qs    
A=AAc                h   U R                   nU(       a  UR                  b  UR                  R                  R                  R                  [        5      (       aS  UR                  nUR                  b:  UR                  R                  R                  R                  [        5      (       a  MS  Xl         g g r   )__traceback__tb_nexttb_framef_codeco_filenameendswith_EXCLUDED_FRAME_FNAME)r   tb_s     r:   r   r   R  s    
//C
kk%#,,*=*=*I*I*R*R!+
 +
 ++C kk%#,,*=*=*I*I*R*R!+
 +
  r9   c                 d    [         c   SSKn Sq [         $ [         $ ! [         a
    Sq  [         $ f = f)zCache for otel import check.Nr   TF)r3   opentelemetry.tracer  )opentelemetrys    r:   _is_otel_availablers  \  s@     	$&"O ?  	$#O	$s    //c                :   U (       a  [         R                  " S5      (       d  g[        5       (       d  gSSKJnJnJnJnJn  SSK	J
nJn  U" U R                  5      nU" U R                  5      n	U" UU	SU" UR                  5      U" 5       S9n
U" U
5      nU" U5      $ )zCreate OpenTelemetry context manager if OTEL is enabled and available.

Args:
    run_tree: The current run tree.

Returns:
    Context manager for use_span or None if not available.
OTEL_ENABLEDNr   )NonRecordingSpanSpanContext
TraceFlags
TraceStateuse_span)get_otel_span_id_from_uuidget_otel_trace_id_from_uuidF)trace_idspan_id	is_remotetrace_flagstrace_state)r#   is_env_var_truishrs  rq  rv  rw  rx  ry  rz  langsmith._internal._otel_utilsr{  r|  r}  r\   SAMPLED)r?   rv  rw  rx  ry  rz  r{  r|  r}  r~  span_contextnon_recording_spans               r:   r   r   i  s     522>BB 
 +8+<+<=H(5Gz112LL *,7&''r9   )r   r   )r?   rf  r   Generator[None, None, None])r-   r   r   rh  r   )rP   zOptional[contextvars.Context]r   dict[str, Any])r+   r}   r,   r   r-   r   r*   z@Optional[Union[run_trees.RunTree, Mapping, str, Literal[False]]]r.   z'Optional[Union[bool, Literal['local']]]r    r   r/   z Optional[Sequence[WriteReplica]]r0   r}   r^   r   r   r  )rh   r   r   z'TypeGuard[SupportsLangsmithExtra[P, R]])rh   Callable[P, R]rm   r}   r-   rd  r,   r   r    r   rn   0Optional[Callable[[Sequence], Union[dict, str]]]r+   r}   ro   r  rp   Optional[Callable[..., dict]]rq   r  r   SupportsLangsmithExtra[P, R])rh   r   r   bool)r?   rf  r   r   r^   r   r   z(Optional[schemas.ExtractedUsageMetadata])rh   r  r   r  rb  )r   rc  rm   r}   r-   rd  r,   r   r    r   rn   r  r+   r}   ro   r  rp   r  rq   r  r   r  r   r  r.   r2   r   re  r   z8Callable[[Callable[P, R]], SupportsLangsmithExtra[P, R]])r   r   r^   r   r   z/Union[Callable, Callable[[Callable], Callable]])r+   r}   r   r}   )r  r   r   r(   )r   zBaseException | Noner   re  r   r}   rP  )r  r  r   Optional[Any]r   rg  r   rh  )r   r  r   r{   r   r  )r   r{   r   r   r   r   ri  )rh   r   r   r%  r   r   r   r   r^   r   r   r  )
r  r  r   r  r   rg  r   r  r   rh  )rh   r   r   r  )r   inspect.Signaturer   r   r^   r   r   r  )r  zinspect.Parameterrh   r  r   r  )r   r  rh   r  r   zset[str])
r   r  r   r   rh   r  r^   r   r   z tuple[dict, schemas.Attachments])rP   r   )r   rQ  r   r  r   r  r   	list[Any]rq   r  r   r  r   zGenerator[T, None, Any])r   re  r   r  r   r  r   r  r   r  rq   r  r   r  r   zAsyncGenerator[T, None])r   r*  rn   r   r   r   )r   r   )r   r  )r?   r   )|r   
__future__r   r   
contextlibcontextvarsr  rf   rw   r  rW   collections.abcr   r   r   r   r   r	   r
   r   typingr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typing_extensionsr   r   r   r   langsmith._internal._context	_internalr5   	langsmithr    r   r!   r"   r#   langsmith._internalr$   r   langsmith.envr%   langsmith.run_treesr&   typesr'   r  r(   	getLoggerr   rC   r6   rH   rI   rJ   rK   rL   rM   rN   r1   r   rn  r3   r;   contextmanagerrA   rF   rS   ra   get_run_tree_contextrk   rt   ry   r{   r   r   r   r   rs   r*  r9  r  r#  r  r%  rG  r  r  rZ   r   r&  rd   r  r  r  r  	lru_cacher  r  r  r]   r   r   r  r  r   r   r   r   rs  r   r8   r9   r:   <module>r     s   7 "           %    $ I H / / ) / / 4 & ,#1			8	$''**NN""((##&==	40 	 3 "& &+
 // / /(	 .2A*AA$  #' $)-OS7;)-15+/B.B. B. '	B.
 MB. 5B. 'B. /B. )B. B. !B. B.L ,  ,0 $)-BF"&7;59(,
  *	
  ' @   5 3 & ":RYe R: C4 cN Xwq!t}  6 #BB B 	B
 .B 
'
'!' 
'
 
%,C ,0 $)-BF"&7;59(,>B)."FJC"C C *	C
 C 'C @C  C 5C 3C &C <C #'C C DC  >!C 
C&[	[	[	 5[	|W7 W7tp+h D)5 D Diu D&	,	,C	, 	, "%)2A"2A2A #2A 
	2Aj "1#11 !1n 15T
T$T .T 	T
 T Tr "%)7;	F"FF #F 5	F
 
F; ),8;(0 0),08;008 >B (: T"=A4 4(:44 #4 >B8 8(:88  $4 44 4 	4
 &4.$ +/00&0 0
 0 &0 (0 0v +/EE&E 	E
 E E &E (E EP CL9)
 9)x1A%wqz 1Ah9%*GAJ 9%x	
'(V &&	,, 


,, r9   