
    	ha                    P   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mZm	Z	 ddl
m
Z
mZ ddlmZmZmZmZ ddlmZmZmZmZ ddlmZ 	 dd	lmZmZ n# e$ r dd	lmZmZ Y nw xY wddlZddlZddlZ ddl!m"c m#Z# dd
l$m%Z& ddl$m'Z' ddl(m)Z)m*Z*m+Z+m,Z,m-Z-  ej.        e/          Z0 G d ded          Z1dZ2 ej3        e2 d          Z4e45                    d          Z6 ej3        e2 d          Z7 ej3        e2 d          Z8 ej3        e2 d          Z9 ej3        e2 d          Z: ej3        d          Z; ed e<                      Z= ej>                    Z? ej@        ee	e1                           dd          ZA ej@        eeB                  dd          ZC ed e<                      ZDdZEdHd!ZFeDeDeDeDeDfdId*ZGdJd-ZH G d. d/e&jI                  ZJ G d0 d1          ZK ejL        d23          dKd6            ZMdLd7ZNdMd;ZOdNd=ZPdOdAZQdPdFZRe#jS        aTd#eUdG<   d/d/gZVdS )QzSchemas for the LangSmith API.    )annotationsN)MappingSequence)datetimetimezone)AnyOptionalUnioncast)NAMESPACE_DNSUUIDuuid4uuid5)	TypedDict)Fieldroot_validator)schemas)utils)ID_TYPE
RUN_TYPE_TClient_dumps_json_ensure_uuidc                  8    e Zd ZU ded<   ded<   ded<   ded<   dS )WriteReplicaOptional[str]api_urlapi_keyproject_nameOptional[dict]updatesN)__name__
__module____qualname____annotations__     `/var/www/html/web-builder-api.evdpl.com/venv/lib/python3.11/site-packages/langsmith/run_trees.pyr   r   $   sB         r'   r   F)totalz
langsmith-traceutf-8metadatatagsprojectreplicas__omit_auto_outputs	_REPLICASdefault_DISTRIBUTED_PARENT_ID$   init_kwargsr   returnr   c                     t           2t          5  t           t          di | a d d d            n# 1 swxY w Y   t           S )Nr&   )_CLIENT_LOCKr   )r6   s    r(   get_cached_clientr;   E   s     	0 	0 //;//	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 Ns   /33clientOptional[Client]enabledOptional[bool]r   r   Optional[list[str]]Optional[dict[str, Any]]c                   t           5  | t          ur| a|t          ur+t          j                            |           |t          _        |t          ur+t          j                            |           |t          _        |t          ur+t          j	                            |           |t          _
        |t          ur+t          j                            |           |t          _        ddd           dS # 1 swxY w Y   dS )a	  Configure global LangSmith tracing context.

    This function allows you to set global configuration options for LangSmith
    tracing that will be applied to all subsequent traced operations. It modifies
    context variables that control tracing behavior across your application.

    Do this once at startup to configure the global settings in code.

    If, instead, you wish to only configure tracing for a single invocation,
    use the `tracing_context` context manager instead.

    Args:
        client: A LangSmith Client instance to use for all tracing operations.
            If provided, this client will be used instead of creating new clients.
            Pass `None` to explicitly clear the global client.
        enabled: Whether tracing is enabled. Can be:
            - `True`: Enable tracing and send data to LangSmith
            - `False`: Disable tracing completely
            - `"local"`: Enable tracing but only store data locally
            - `None`: Clear the setting (falls back to environment variables)
        project_name: The LangSmith project name where traces will be sent.
            This determines which project dashboard will display your traces.
            Pass `None` to explicitly clear the project name.
        tags: A list of tags to be applied to all traced runs. Tags are useful
            for filtering and organizing runs in the LangSmith UI.
            Pass `None` to explicitly clear all global tags.
        metadata: A dictionary of metadata to attach to all traced runs.
            Metadata can store any additional context about your runs.
            Pass `None` to explicitly clear all global metadata.

    Returns:
        None

    Examples:
        Basic configuration:
        >>> import langsmith as ls
        >>> # Enable tracing with a specific project
        >>> ls.configure(enabled=True, project_name="my-project")

        Set global trace masking:
        >>> def hide_keys(data):
        ...     if not data:
        ...         return {}
        ...     return {k: v for k, v in data.items() if k not in ["key1", "key2"]}
        >>> ls.configure(
        ...     client=ls.Client(
        ...         hide_inputs=hide_keys,
        ...         hide_outputs=hide_keys,
        ...     )
        ... )

        Adding global tags and metadata:
        >>> ls.configure(
        ...     tags=["production", "v1.0"],
        ...     metadata={"environment": "prod", "version": "1.0.0"},
        ... )

        Disabling tracing:
        >>> ls.configure(enabled=False)
    N)r:   	_SENTINELr9   _context_TRACING_ENABLEDset_GLOBAL_TRACING_ENABLED_PROJECT_NAME_GLOBAL_PROJECT_NAME_TAGS_GLOBAL_TAGS	_METADATA_GLOBAL_METADATA)r<   r>   r   r-   r,   s        r(   	configurerN   N   s&   H 
 1 1""G)##%))'222/6H,y(("&&|444,8H)y  Nt$$$$(H!9$$""8,,,(0H%1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1s   CC11C58C5data!ls_schemas.ExtractedUsageMetadatac                ~    h d}t          |                                           |z
  }|rt          d|           | S )z2Validate that the dict only contains allowed keys.>
   
input_cost
total_costoutput_costinput_tokenstotal_tokensoutput_tokensinput_cost_detailsinput_token_detailsoutput_cost_detailsoutput_token_detailsz#Unexpected keys in usage metadata: )rF   keys
ValueError)rO   allowed_keys
extra_keyss      r(   !validate_extracted_usage_metadatar`      sT      L TYY[[!!L0J MKzKKLLLKr'   c                  "    e Zd ZU dZded<    ee          Zded<    ed          Zded	<    ed
           Z	ded<    edd          Z
ded<    edd          Zded<    eeddhi          Zded<    ed d          Zded<    edd          Zded <    ee          Zd!ed"<    ee          Zd#ed$<    ee          Zd%ed&<   	  edd          Zd'ed(<    ed)d*+          Zded,<    ed)d-+          Zded.<    ed/d0+          Zd1ed2<    edd3+          Zd4ed5<    G d6 d7          Z ed8          d~d;            Z ed/8          d~d<            Zedd>            Zedd@            Z fdAZ e!e!e!e!e!dBddKZ"ddMZ#ddOZ$ddPZ%ddQZ&ddSZ'ddddddTdd[Z(	 ddddddddddddd\dddZ)de Z*ddhZ+	 dddjZ,dddmZ-d/dnddpZ.ddqZ/ddrZ0e1ddu            Z2e1ddw            Z3e1ddz            Z4dd|Z5d} Z6 xZ7S )RunTreez1Run Schema with back-references for posting runs.strname)default_factoryr   idchainr2   run_typec                 >    t          j        t          j                  S N)r   nowr   utcr&   r'   r(   <lambda>zRunTree.<lambda>   s    hl9S9S r'   r   
start_timeNT)r3   excludeOptional[RunTree]
parent_runr   parent_dotted_order__all__parent_run_id)re   ro   zlist[RunTree]
child_runsc                 ,    t          j                    pdS )Nr3   )r   get_tracer_projectr&   r'   r(   rm   zRunTree.<lambda>   s     8 : : Gi r'   r   )re   aliassession_name
project_id)r3   rx   Optional[UUID]
session_iddictextrar@   r-   z
list[dict]eventszOptional[Any]	ls_client z!The order of the run in the tree.)r3   descriptiondotted_orderzThe trace id of the run.trace_idFz3Whether to allow filesystem access for attachments.r?   dangerously_allow_filesystemz8Projects to replicate this run to with optional updates. Optional[Sequence[WriteReplica]]r/   c                      e Zd ZdZdZdZdZdS )RunTree.ConfigzPydantic model configuration.TignoreN)r"   r#   r$   __doc__arbitrary_types_allowedallow_population_by_field_namer~   r&   r'   r(   Configr      s%        ++"&)-&r'   r   )prevaluesr7   c                   |                     d          R|                     d          =d|d         v r|d         d         |d<   n!d|d         v r|d         d         d         |d<   |                     d          d|d<   d|v r|                    d          |d<   nd	|v r|                    d	          |d<   |                     d          sd|d<   |                    d
d          }||j        |d<   |j        |d<   d|vrt	                      |d<   d|vr||j        |d<   n|d         |d<   t          t          |                    di                      |                     d          g |d<   |                     d          g |d<   |                     d          i |d<   |                     d          i |d<   |                     d          t                                           |d<   t          |d                   |d<   |S )zAssign name to the run.rd   N
serializedrf   Unnamedr<   r   _clientrq   rt   rr   r   r~   r   r-   outputsattachmentsr/   )getpoprf   r   r   r   r   r}   
setdefaultr1   _ensure_write_replicas)clsr   rq   s      r(   infer_defaultszRunTree.infer_defaults   s;    ::f%&**\*B*B*N---!'!5f!=v---!'!5d!;B!?v::f%&F6Nv"(**X"6"6F;&  "(**Y"7"7F;zz+&& 	'"&F;ZZd33
!&0mF?#,6,CF()v 77F4LV##%%/%8z""%+D\z"T6$$Wb11222::h'!F8::f%F6N::i  ( "F9::m$$,$&F=!::j!!)!*F:3F:4FGGzr'   c                    |                     d          }|r|                                r|S t          |d         |d                   }|                     d          }||dz   |z   |d<   n||d<   |S )z#Ensure the dotted order of the run.r   rn   rf   rr   N.)r   strip_create_current_dotted_order)r   r   current_dotted_orderrr   s       r(   ensure_dotted_orderzRunTree.ensure_dotted_order  s      &zz.99 	$8$>$>$@$@ 	M;< &, 
  
 %jj)>??*%83%>AU%UF>""%9F>"r'   r   c                D    | j         t                      | _         | j         S )zReturn the client.)r   r;   selfs    r(   r<   zRunTree.client  s!    
 >!.00DN~r'   r=   c                    | j         S rj   )r   r   s    r(   r   zRunTree._client(  s     ~r'   c                f    |dk    r	|| _         dS t                                          ||          S )zSet the _client specially.r   N)r   super__setattr__)r   rd   value	__class__s      r(   r   zRunTree.__setattr__-  s5     9"DNNN77&&tU333r'   )inputsr   r-   r,   usage_metadatar   Optional[Mapping[str, Any]]r   Optional[Sequence[str]]r,   r   +Optional[ls_schemas.ExtractedUsageMetadata]Nonec                  |t           urt          |          | _        |t           ur0| j                            di                               |pi            |t           ur(d| j        d<   |i | _        nt          |          | _        |t           ur-d| j        t          <   |i | _	        nt          |          | _	        |t           ur-t          |          | j                            di           d<   dS dS )a  Set the inputs, outputs, tags, and metadata of the run.

        If performed, this will override the default behavior of the
        end() method to ignore new outputs (that would otherwise be added)
        by the @traceable decorator.

        If your LangChain or LangGraph versions are sufficiently up-to-date,
        this will also override the default behavior of LangChainTracer.

        Args:
            inputs: The inputs to set.
            outputs: The outputs to set.
            tags: The tags to set.
            metadata: The metadata to set.
            usage_metadata: Usage information to set.

        Returns:
            None
        r,   Finputs_is_truthyNTr   )NOT_PROVIDEDlistr-   r~   r   updater   r}   OVERRIDE_OUTPUTSr   r`   )r   r   r   r-   r,   r   s         r(   rF   zRunTree.set5  s    8 |##T

DI<''J!!*b1188RHHH%% .3DJ)*~ "6ll,&&+/DJ'(!#G}}--1.AA J!!*b112BCCC .-r'   Union[Sequence[str], str]c                    t          |t                    r|g}| j        g | _        | j                            |           dS )zAdd tags to the run.N)
isinstancerc   r-   extend)r   r-   s     r(   add_tagszRunTree.add_tagsh  sF    dC   	6D9DI	r'   dict[str, Any]c                    | j         i | _         t          t          | j                                       di           }|                    |           dS )zAdd metadata to the run.Nr,   )r~   r   r}   r   r   )r   r,   	metadata_s      r(   add_metadatazRunTree.add_metadatap  sL    :DJtTZ00;;JKK	"""""r'   c                V    | j         i | _         | j                             |           dS )Upsert the given outputs into the run.

        Args:
            outputs (Dict[str, Any]): A dictionary containing the outputs to be added.

        Returns:
            None
        N)r   r   )r   r   s     r(   add_outputszRunTree.add_outputsw  s/     <DLG$$$$$r'   c                j    | j         i | _         | j                             |           d| j        d<   dS )r   NFr   )r   r   r~   )r   r   s     r(   
add_inputszRunTree.add_inputs  s>     ;DK6""" */
%&&&r'   TUnion[ls_schemas.RunEvent, Sequence[ls_schemas.RunEvent], Sequence[dict], dict, str]c                ~   | j         g | _         t          |t                    r| j                             |           dS t          |t                    rN| j                             dt          j        t          j                  	                                |d           dS | j         
                    |           dS )a~  Add an event to the list of events.

        Args:
            events (Union[ls_schemas.RunEvent, Sequence[ls_schemas.RunEvent],
                    Sequence[dict], dict, str]):
                The event(s) to be added. It can be a single event, a sequence
                of events, a sequence of dictionaries, a dictionary, or a string.

        Returns:
            None
        Neventrd   timemessage)r   r   r}   appendrc   r   rk   r   rl   	isoformatr   )r   r   s     r(   	add_eventzRunTree.add_event  s    * ;DKfd## 	'Kv&&&&&$$ 		'K#$L66@@BB%      Kv&&&&&r'   )r   errorend_timer   r,   r    r   r   Optional[datetime]'Optional[Sequence[ls_schemas.RunEvent]]rA   c               V   |pt          j        t          j                  | _        | j                            t                    s+|)| j        s|| _        n| j        	                    |           ||| _
        ||                     |           ||                     |           dS dS )z/Set the end time of the run and all child runs.N)r   rk   r   rl   r   r~   r   r   r   r   r   r   r   )r   r   r   r   r   r,   s         r(   endzRunTree.end  s     !>HL$>$> z~~.// 	1"| 1#*DLLL''000DJNN6"""h'''''  r'   )run_idr   r   r   r   reference_example_idrn   r   r-   r~   r   r   r   Optional[ID_TYPE]r   r   r    Optional[ls_schemas.Attachments]c               T   |pd|i}t          di d|dt          |          d|d|pi d|pi d|d|d|d	|	pt          j        t          j                  d
|
d|pi d| d| j        d| j        d| j        d|d|pi d| j	        }| j
                            |           |S )z Add a child run to the run tree.rd   rf   r   r   r   r   rh   r   rn   r   r~   rq   r   r/   r   r-   r   r   r&   )rb   r   r   rk   r   rl   ry   r/   r   r   ru   r   )r   rd   rh   r   r   r   r   r   r   rn   r   r-   r~   r   serialized_runs                   r(   create_childzRunTree.create_child  sJ   $ !2VTN 
 
 

F###
 #{
 <R	

 Mr
 %
 X
 "6!5
 "?X\(,%?%?
 X
 +2
 t
 **
 ]]
 nn
  !
" $)r#
$ *.)J)J%
( 	s###
r'   c                    |                      h dd          }| j        | j                                        |d<   | j        | j                                        |d<   |S )N>   r   r   ru   T)ro   exclude_noner   r   )r}   r   copyr   )r   	self_dicts     r(   _get_dicts_safezRunTree._get_dicts_safe  sm    II777d  
 
	 ;""&+"2"2"4"4Ih<##'<#4#4#6#6Ii r'   	parent_idrun_dictc                *   |                     d          x}r|                    d          }d}t          |          }t          |          D ],\  }}|t           d         }t          |          |k    r|} n-|Y||dz   d         }	d                    |	          |d<   |	r't          |	d         t           d                   |d<   n|d         |d<   t          |                     d                    |k    r|                    dd           dS dS )	zSlice the parent id from dotted order.

        Additionally check if the current run is a child of the parent. If so, update
        the parent_run_id to None, and set the trace id to the new root id after
        parent_id.
        r   r   N   r   r   rf   rt   )r   splitrc   	enumerateTIMESTAMP_LENGTHjoinr   r   )
r   r   r   r   segs	start_idxidxpartseg_idtrimmed_segss
             r(   _slice_parent_idzRunTree._slice_parent_id	  s<    $<<777< 	:%%c**DIII&t__  	T//001v;;)++ #IE , $#IMOO4+.88L+A+A( :+/QAQ@Q@R@R0S+T+THZ((+3D>HZ(x||O,,--::LL$///// ;:r'   r!   c                P   |                                  }|| j        k    r|S |rG|                    dd          r1t                                          }|r|                     ||           |d         }t          t          | d|           }|                    d          }|rt          t          | d|           }nd}|                    d          }	|	rt          t          |	 d|           }
nd}
|                    d          r|d                             d	          }g }|dd
         D ]]}t          t          |t           d          d|           }|	                    |dt                    t          |          z              ^|	                    |d
         dt                    t          |          z              d	                    |          }nd}t          j        |          }|                    |||
||d           |r|                    |           |S )zDRewrites ids/dotted_order for a given project with optional updates.rerootFrf   :r   Nrt   r   r   r   )rf   r   rt   r   ry   )r   ry   r   r4   r   r   r   r   r   r   rc   r   r   deepish_copyr   )r   r   r!   r   distributed_parent_idold_idnew_id	old_trace	new_traceparent
new_parentr   rebuiltr   repldotteddups                    r(   _remap_for_projectzRunTree._remap_for_project'  sm    ''))4,,,O 	Gw{{8U33 	G$:$>$>$@$@!$ G%%&;XFFF$}&@&@,&@&@AALL,,	 	m	-J-JL-J-JKKIIIo.. 	}.H.H,.H.HIIJJJ<<'' 	N+11#66DGSbS	 E E!d,<+<+=+=&>#O#O#O#O  t$6&6%6$67#d))CDDDDNN48$6&6%6$67#f++EFFFXXg&&FFF **

%!+ & , 	
 	
 	
  	 JJw
r'   exclude_child_runsboolc           	        | j         r| j         D ]}|                    d          p| j        }|                    d          }|                     ||          } | j        j        di ||                    d          |                    d          d n&|                                 } | j        j        di | | j        rjd | j        D             }| j        	                    dt          j        t          j                                                  t          |          d           |s | j        D ]}|                    d	
           dS dS )z,Post the run tree to the API asynchronously.r   r!   r   r   )r   r   c                ,    g | ]}t          |          S r&   )rc   ).0rd   s     r(   
<listcomp>z RunTree.post.<locals>.<listcomp>n  s    ;;;$CII;;;r'   uploaded_attachmentr   F)r  Nr&   )r/   r   ry   r   r<   
create_runr   r   r   r   r   rk   r   rl   r   rF   ru   post)	r   r  replicar   r!   r   kwargsr\   	child_runs	            r(   r	  zRunTree.post^  s   = 	-=  &{{>::Od>O!++i0022<II&&  #KK	22#KK	22     	 ))++F"DK",,V,,, 	;;$*:;;;DK1$L66@@BB"4yy    " 	9!_ 9 9	%8888	9 	99 9r'   )exclude_inputsr  c                  | j         s|                                  d | j                                        D             }	 |rAt	          d | j        D             d          r fd|                                D             }n4# t          $ r'}t                              d|            Y d}~nd}~ww xY w| j	        r| j	        D ]u}|
                    d          p| j        }|
                    d          }|                     ||          }| j                            |d         |d	         |rdn|d
         |d         |
                    d          |
                    d          |
                    d          |
                    d          |
                    d          |
                    d          |
                    d          |
                    d          |
                    d          |
                    d          ||
                    d          |
                    d                     wdS | j                            | j        | j        |rdn!| j        r| j                                        nd| j        r| j                                        nd| j        | j        | j        | j        | j         | j        | j        | j        | j        | j        |           dS )zPatch the run tree to the API in a background thread.

        Args:
            exclude_inputs: whether to exclude inputs from the patch request.
        c                D    i | ]\  }}t          |t                    ||S r&   )r   tuple)r  avs      r(   
<dictcomp>z!RunTree.patch.<locals>.<dictcomp>  s=     
 
 
QAu9M9M
q
 
 
r'   c              3  L   K   | ]}|                     d           dk    |V   dS )rd   r  N)r   )r  evs     r(   	<genexpr>z RunTree.patch.<locals>.<genexpr>  sD        66&>>-BBB BBBB r'   Nc                0    i | ]\  }}|d          v||S )r   r&   )r  r  r  uploadeds      r(   r  z!RunTree.patch.<locals>.<dictcomp>  s9     # # # AqHY$777 1777r'   z'Error filtering attachments to upload: r   r!   rd   rf   r   r   r   rt   ry   r   r   r   r   r   r-   r~   r   r   )rd   r   r   r   r   rt   ry   r   r   r   r   r   r-   r~   r   r   r   )rd   r   r   r   r   rt   ry   r   r   r   r   r   r-   r~   r   )r   r   r   itemsnextr   	Exceptionloggerwarningr/   r   ry   r   r<   
update_runrd   rf   r   r   r   r   rt   r   r   r   r-   r~   )	r   r  r   er
  r   r!   r   r  s	           @r(   patchzRunTree.patchz  s6    } 	HHJJJ
 
!-3355
 
 
	J  "&+  
    # # # #$/$5$5$7$7# # #K
  	J 	J 	JNNHQHHIIIIIIII	J= -	=  &{{>::Od>O!++i0022<II&&!&)#D>#1I44x7I$Y/",,w//"*,,"?"?!)n!=!=)16L)M)M%\\*55!)n!=!=%\\*55#<<11!f--",,w// +#KK	22#KK	22# '    	 0 K""Yw &GDD04E$+**,,,/3|E))+++j"0!.%)%>!.{Yj'' #     s   AB 
B6B11B6c                    dS )z"Wait for all _futures to complete.Nr&   r   s    r(   waitzRunTree.wait  s    r'   c                8    | j                             |           S )zReturn the URL of the run.)r   )r<   get_run_urlr   s    r(   get_urlzRunTree.get_url  s    {&&4&000r'   r  r   c                V    t           |i}t          t           | j        |fi |          S )zwCreate a new 'child' span from the provided dotted order.

        Returns:
            RunTree: The new span.
        )LANGSMITH_DOTTED_ORDERr   rb   from_headers)r   r   r  headerss       r(   from_dotted_orderzRunTree.from_dotted_order  s8     #L
 G-S-g@@@@AAAr'   configc           	     f   	 ddl m}m} ddlm}m} ddlm n"# t          $ r}t          d          |d}~ww xY w|1 |t          |t                    rt          ||          nd          }nt          ||          }|                    d          x}	rt          |	||f          r|	j        rt          fd|	j        D             d          x}
r[|
j                            t#          |	j                            x}r|j        r|j        }|j        |d	<   |j        |d
<   |j        |d<   |j        |d<   |j        |d<   t1          t3          |j        pg |                    dg           z                       |d<   |j        |d<   |                    di           }|                    di           }|                    |j                   n9t?          |
d          r'|	j        |
j         v r|
j         |	j                 d         }ndS |
j!        |d<   |
j"        |d<   tG          j$        |fi |S dS )zCreate a new 'child' span from the provided runnable config.

        Requires langchain to be installed.

        Returns:
            Optional[RunTree]: The new span or None if
                no parent span information is found.
        r   )AsyncCallbackManagerCallbackManager)RunnableConfigensure_config)LangChainTracerz{RunTree.from_runnable_config requires langchain-core to be installed. You can install it with `pip install langchain-core`.N	callbacksc              3  <   K   | ]}t          |          |V  d S rj   )r   )r  tr1  s     r(   r  z/RunTree.from_runnable_config.<locals>.<genexpr>  s2      NN1z!_/M/MNQNNNNNNr'   rh   r   r   rn   r   r-   rd   r~   r,   	order_mapr   r<   r   )% langchain_core.callbacks.managerr-  r.  langchain_core.runnablesr/  r0   langchain_core.tracers.langchainr1  ImportErrorr   r}   r   r   rt   r  handlersrun_maprc   r   rh   r   r   rn   r   sortedrF   r-   rd   r   r   r,   hasattrr5  r<   r   rb   r*  )r   r+  r  r-  r.  r/  r0  r  config_cbtracerr   r   extra_r   r1  s                  @r(   from_runnable_configzRunTree.from_runnable_config  s   	        ONNNNNNNHHHHHHH 	 	 	H  	
 >#m0:640H0HR^V,,,d GG >622G ;;{+++R	E21EFGG	E  	E
 NNNNNNN  	E ~))#b.>*?*?@@@ cFV "/%(\z"#&:x $'Ky!'*~|$%(\z"!'CH,SVZZPR=S=S8S(T(T!U!Uv!$v**7B77"--j"==	  ....-- "2BfFV2V2V%/0@A!Dt%}F8%+%8F>",\DDVDDDts    
949r)  -Mapping[Union[str, bytes], Union[str, bytes]]c           	     6   |                                 }t          t          t                   |                    t
                              }|sQt          t          t                   |                    t                              }|sdS |                    d          }|	                                }t          |          }|d         d         }||d<   |d         d         |d<   ||d<   t          |          d	k    r|d
         d         |d<   |                    d          pt          j        t          j                  |d<   |                    d          pd|d<   |                    d          pd|d<   t                               |          }	|	j        s|	j        r|                    di           |d<   |d                             di           |d         d<   i |	j        |d         d         }
|
|d         d<   t+          t-          |	j        |                    dg           z                       }||d<   |	j        r
|	j        |d<   |	j        r
|	j        |d<   t3          di |}t4                              t          |j                             |S )a  Create a new 'parent' span from the provided headers.

        Extracts parent span information from the headers and creates a new span.
        Metadata and tags are extracted from the baggage header.
        The dotted order and trace id are extracted from the trace header.

        Returns:
            Optional[RunTree]: The new span or None if
                no parent span information is found.
        Nr+   r   r   r   r   rf   r      rt   rn   rh   rg   rd   r   r~   r,   r-   r   r/   r&   )r   r   r	   rc   r   r'  bytesLANGSMITH_DOTTED_ORDER_BYTESdecoder   _parse_dotted_orderlenr   rk   r   rl   _Baggager(  r,   r-   r   r<  rF   r   r/   rb   r4   rf   )r   r)  r  	init_argslangsmith_tracelangsmith_trace_bytesrr   parsed_dotted_orderr   baggager,   r-   run_trees                r(   r(  zRunTree.from_headers   s    KKMM	x}gkk:P.Q.QRR 	D$(-I!J!J% %! ) 3::7CCO-335512EFF&q)!, (	*-b1!4	$$7	.!"##q(()<R)@)CIo& #,--"="= #
LB
 B
	, !*j 9 9 DW	*%MM&11=X	&''00 	%w| 	%!*!5!5gr!B!BIg-6w-?-J-JB. .Igz* N'*Mi.@.LMH-5Igz*#glY]]62-F-FFGGHHD $If 	=(/(<In% 	5$+$4Ij!''Y'' 	""3x{#3#3444r'   dict[str, str]c                    i }| j         r| j        |t           <   t          | j                            di           | j        | j        | j                  }|	                                |d<   |S )z.Return the RunTree as a dictionary of headers.r,   r,   r-   r   r/   rQ  )
r   r   r'  rL  r~   r   r-   ry   r/   	to_header)r   r)  rQ  s      r(   
to_headerszRunTree.to_headers`  sw    = 	E373DG-/0Z^^J33*]	
 
 
 %..00	r'   c           	     H    d| j          d| j         d| j         d| j         d	S )z5Return a string representation of the RunTree object.zRunTree(id=z, name='z', run_type='z', dotted_order='z'))rf   rd   rh   r   r   s    r(   __repr__zRunTree.__repr__n  sV    O$' O O49 O OO O9=9JO O O	
r'   )r   r}   r7   r}   )r7   r   )r7   r=   )r   r   r   r   r-   r   r,   r   r   r   r7   r   )r-   r   r7   r   )r,   r   r7   r   )r   r   r7   r   )r   r   r7   r   )r   r   r7   r   )r   r    r   r   r   r   r   r   r,   rA   r7   r   )rg   )rd   rc   rh   r   r   r   r   r    r   r    r   r    r   r   r   r{   rn   r   r   r   r-   r@   r~   r    r   r   r7   rb   )r   rc   r   r}   r7   r   rj   )r   rc   r!   r    r7   r}   )T)r  r  r7   r   )r  r  r7   r   )r7   r   r7   rc   )r   rc   r  r   r7   rb   )r+  r    r  r   r7   rp   )r)  rC  r  r   r7   rp   )r7   rS  )8r"   r#   r$   r   r%   r   r   rf   rh   rn   rq   rr   r   ru   ry   r|   r}   r~   r-   r   r   r   r   r   r/   r   r   r   r   propertyr<   r   r   r   rF   r   r   r   r   r   r   r   r   r   r   r	  r   r"  r%  classmethodr*  rB  r(  rW  rY  __classcell__)r   s   @r(   rb   rb      s        ;;IIIuU+++B++++E'***H**** 51S1STTTJTTTT$)E$$E$E$EJEEEE).tT)J)J)JJJJJ %_-.! ! !J     GG  L     "'t<!H!H!HJHHHH%---E---- %d ; ; ;D;;;;t444F4444$uT4@@@I@@@@ C  L     U23MNNNHNNNN385#X4 4 4      27N2 2 2H    
        ^& & & &P ^       X    X4 4 4 4 4 /;/;(40<FR1 1 1 1 1 1f   # # # #% % % %/ / / / "' "' "' "'N #'#'+:>-1( ( ( ( ( (:  '(
 %)%)!%"&#/3)-'+$( $8<( ( ( ( ( (T  0 0 0 0> <@5 5 5 5 5n9 9 9 9 98 /4 K K K K K KZ   1 1 1 1 B B B [B > > > [>@ = = = [=~   
 
 
 
 
 
 
r'   rb   c                  \    e Zd ZdZ	 	 	 	 dddZedd            Zedd            ZddZdS )rL  zBaggage header information.Nr,   Optional[dict[str, str]]r-   r@   r   r   r/   r   c                J    |pi | _         |pg | _        || _        |pg | _        dS )zInitialize the Baggage object.NrU  )r   r,   r-   r   r/   s        r(   __init__z_Baggage.__init__y  s1     !BJB	( Br'   header_valuer7   c                   |s
 |             S i }g }d}d}	 |                     d          D ]}|                     dd          \  }}|t          k    r2t          j        t          j                            |                    }Y|t          k    r3t          j                            |                               d          }|t          k    r t          j                            |          }|t          k    rt          j        t          j                            |                    }	g }
|	D ]}t          |t          t          f          rSt          |          dk    r@|
                    t          ddt!          |d                   |d                              qt          |t"                    r)|
                    t%          t          |                     t&                              d|            |
}n4# t*          $ r'}t&                              d	|            Y d}~nd}~ww xY w | ||||
          S )z4Create a Baggage object from the given header value.N,=r   rE  r   r   r   r   r!   z#Unknown replica format in baggage: zError parsing baggage header: rU  )r   LANGSMITH_METADATAjsonloadsurllibparseunquoteLANGSMITH_TAGSLANGSMITH_PROJECTLANGSMITH_REPLICASr   r  r   rK  r   r   rc   r}   r   r  r  r  )r   rb  r,   r-   r   r/   itemkeyr   replicas_dataparsed_replicasreplica_itemr  s                r(   from_headerz_Baggage.from_header  su     	355L15$	A$**3// !/ !/!ZZQ//
U,,,#z&,*>*>u*E*EFFHHN**!<//66<<SAADD---#)<#7#7#>#>LL...$(Jv|/C/CE/J/J$K$KM:<O(5 % %&|eT]CC% #L 1 1Q 6 6 ,22 ,,0,014\!_1E1E,8O	!" !" !"    (d;; %+224l3S3STTTT"NN Tl T T   %.HC!/D  	A 	A 	ANN?A??@@@@@@@@	A sD|h
 
 
 	
s   G)H   
H1
H,,H1r)  Mapping[Union[str, bytes], Any]c                    d|v r|                      |d                   S d|v rA|                      t          t          |d                                       d                    S |                      d           S )NrQ  s   baggager+   )ru  r   rG  rI  )r   r)  s     r(   r(  z_Baggage.from_headers  sp    ??79#56667""??4wz/B#C#C#J#J7#S#STTT??4(((r'   rc   c                   g }| j         rPt          | j                   }|                    t           dt          j                            |                      | j        rVd                    | j                  }|                    t           dt          j                            |                      | j	        rA|                    t           dt          j                            | j	                              | j
        rPt          | j
                  }|                    t           dt          j                            |                      d                    |          S )z,Return the Baggage object as a header value.z	metadata=rd  ztags=zproject=z	replicas=)r,   r   r   LANGSMITH_PREFIXrj  rk  quoter-   r   r   r/   )r   r  serialized_metadataserialized_tagsserialized_replicass        r(   rV  z_Baggage.to_header  s\   = 	"-dm"<"<LL#WWfl.@.@AT.U.UWW   9 	!hhty11OLL#OO&,*<*<_*M*MOO    	LL#TTV\-?-?@Q-R-RTT   = 	"-dm"<"<LL#WWfl.@.@AT.U.UWW   xxr'   )NNNN)r,   r_  r-   r@   r   r   r/   r   )rb  r   r7   rL  )r)  rv  r7   rL  rZ  )	r"   r#   r$   r   ra  r\  ru  r(  rV  r&   r'   r(   rL  rL  v  s        %% .2$(&*59' ' ' ' ' 0
 0
 0
 [0
d ) ) ) [)     r'   rL  r   )maxsizeenv_varlist[WriteReplica]c           	     P   | sg S 	 t          j        |           }t          |t                    r=g }|D ]5}t          |t                    s0t
                              dt          |          j                    H|	                    d          }|	                    d          }t          |t                    s0t
                              dt          |          j                    t          |t                    s0t
                              dt          |          j                    |                    t          |                    d          |dd                     7|S t          |t                    rt          |           g }|                                D ]\  }}|                    d          }t          |t                    r'|                    t          ||dd                     Vt
                              d	| d
t          |          j                    |S t
                              dt          |          j                    g S # t           j        $ r  t$          $ r)}t
                              d|            g cY d}~S d}~ww xY w)zParse write replicas from LANGSMITH_RUNS_ENDPOINTS environment variable value.

    Supports array format [{"api_url": "x", "api_key": "y"}] and object format
    {"url": "key"}.
    zBInvalid item type in LANGSMITH_RUNS_ENDPOINTS: expected dict, got r   r   zGInvalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got zGInvalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got /Nrf  z7Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL z: expected string, got u   Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON list of objects with api_url and api_key properties, or object mapping url->apiKey, got u   Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON list of objects with api_url and api_key properties, or object mapping url->apiKey: )rh  ri  r   r   r}   r  r  typer"   r   rc   r   r   rstrip_check_endpoint_env_unsetr  r   LangSmithUserErrorr  )	r  parsedr/   rp  r   r   urlrq  r  s	            r(   "_parse_write_replicas_from_env_varr    s-     	NG$$fd## B	H    !$-- NND.24jj.AD D   ((9--((9--!'3// NNI04W0FI I   !'3// NNI04W0FI I     's 3 3 '%) $	      O%% 	%f---H"LLNN  Sjjooc3'' OO$$'$')-$(	      NNEE E04S		0BE E  
 ONN<$(LL$9< <  
 I#      !! !	
 	
 	

 						s+   E&I# -CI# 20I# #J%<J J% J%c                 H    t          j        d          } t          |           S )zFGet write replicas from LANGSMITH_RUNS_ENDPOINTS environment variable.RUNS_ENDPOINTS)r   get_env_varr  )r  s    r(   _get_write_replicas_from_envr  6  s!     011G-g666r'   r  rS  r   c                    ddl }| r>|                    d          s|                    d          rt          j        d          dS dS )zECheck if endpoint environment variables conflict with runs endpoints.r   NLANGSMITH_ENDPOINTLANGCHAIN_ENDPOINTz]You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS.)osgetenvr   r  )r  r  s     r(   r  r  =  si    III 
299122 
bii@T6U6U 
&,
 
 	

 
 
 
r'   r   c                @    | t                      S t          |           S )z(Convert replicas to WriteReplica format.)r  r   )r/   s    r(   r   r   H  s$     +--- >>r'   r   rc   list[tuple[datetime, UUID]]c                D    |                      d          }d |D             S )zParse the dotted order string.r   c                    g | ]B}t          j        |d t                    d          t          |t           d                    fCS )N%Y%m%dT%H%M%S%fZ)r   strptimer   r   )r  r   s     r(   r  z'_parse_dotted_order.<locals>.<listcomp>V  sf       
  d#5%5$5#568JKK''(()**	
  r'   )r   )r   partss     r(   rJ  rJ  S  s8    s##E 
    r'   rn   r   r   r{   c                    | pt          j        t          j                  }|pt	                      }|                    d          t          |          z   S )z Create the current dotted order.r  )r   rk   r   rl   r   strftimerc   )rn   r   stid_s       r(   r   r   _  sF     
	1x|HL11B

EGGC;;)**SXX55r'   r9   )r6   r   r7   r   )
r<   r=   r>   r?   r   r   r-   r@   r,   rA   )rO   rP   r7   rP   )r  r   r7   r  )r7   r  )r  rS  r7   r   )r/   r   r7   r  )r   rc   r7   r  )rn   r   r   r{   r7   rc   )Wr   
__future__r   	functoolsrh  loggingsyscollections.abcr   r   r   r   typingr   r	   r
   r   uuidr   r   r   r   typing_extensionsr   pydantic.v1r   r   r9  pydanticcontextvars	threadingurllib.parserj  langsmith._internal._context	_internalrD   	langsmithr   
ls_schemasr   langsmith.clientr   r   r   r   r   	getLoggerr"   r  r   ry  internr'  encoderH  rg  rm  rn  ro  r   objectr   Lockr:   
ContextVarr1   rc   r4   rC   r   r;   rN   r`   RunBaserb   rL  	lru_cacher  r  r  r   rJ  r   _GLOBAL_CLIENTr9   r%   rs   r&   r'   r(   <module>r     s   $ $ $ " " " " " "       



 - - - - - - - - ' ' ' ' ' ' ' ' - - - - - - - - - - - - 2 2 2 2 2 2 2 2 2 2 2 2 ' ' ' ' ' '111111111                         / / / / / / / / / + + + + + +       S S S S S S S S S S S S S S		8	$	$    9E       #'7$>$>$>?? 5<<WEE SZ#3 = = =>> /55566CJ"2;;;<< SZ#3 = = =>> 3:344 tD&&((##	 EK"8H\,B#CD  	 ?/>d    Dvvxx  	      )'"+ ))2R1 R1 R1 R1 R1j   .y

 y

 y

 y

 y

j  y

 y

 y

xb b b b b b b bJ QW W W  Wt7 7 7 7
 
 
 
   	 	 	 	6 6 6 6 %3 3 3 3 3i
 s   	A A"!A"