
    	hun                       d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlmZmZmZmZmZ ddlmZmZ ddlmZmZmZmZmZmZm Z  ddl!m"Z# ddl$Z$ddl%Z%ddl&m'Z' dd	l(m)Z) dd
l*m+Z,  ej-        e.          Z/ G d de0          Z1 G d de1          Z2 G d de1          Z3 G d de1          Z4 G d de1          Z5 G d de1          Z6 G d de1          Z7 G d de1          Z8 G d de1          Z9 G d de1          Z: G d d e;          Z< G d! d"e<          Z=ddd'Z>dd)Z?dd-Z@dd1ZAdd5ZB ejC        d67          dd;            ZDdd=ZEdd>ZFdd@ZGddCZHddEZIddFZJddGZK ejC        d67          ddI            ZLddLZMddOZN ejC        dP7          	 ddQdRddX            ZO ejC        d67          dddZ            ZP G d[ d\ejQ                  ZR G d] d^ejQ                  ZS G d_ d`e)          ZT ejU                    ZVejW        ddf            ZXddhZYdddiddoZZejW        	 	 dddr            Z[ejW        	 	 dddt            Z\dduZ] edv          Z^	 ddd}Z_dd~Z`ddZaddZb e'd          Zc G d de          ZdddZeddZfddZgddZh ejC        d7          dd            ZidddZjddZkdS )zGeneric utility functions.    )annotationsN)	GeneratorIterableIteratorMappingSequence)FutureThreadPoolExecutor)AnyCallableLiteralOptionalTypeVarUnioncast)parse)	ParamSpec)Retry)schemasc                      e Zd ZdZdS )LangSmithErrorz=An error occurred while communicating with the LangSmith API.N__name__
__module____qualname____doc__     \/var/www/html/web-builder-api.evdpl.com/venv/lib/python3.11/site-packages/langsmith/utils.pyr   r   )   s        GGGGr   r   c                      e Zd ZdZdS )LangSmithAPIErrorz9Internal server error while communicating with LangSmith.Nr   r   r   r   r!   r!   -   s        CCCCr   r!   c                      e Zd ZdZdS )LangSmithRequestTimeoutz*Client took too long to send request body.Nr   r   r   r   r#   r#   1   s        4444r   r#   c                      e Zd ZdZdS )LangSmithUserErrorzAUser error caused an exception when communicating with LangSmith.Nr   r   r   r   r%   r%   5   s        KKKKr   r%   c                      e Zd ZdZdS )LangSmithRateLimitErrorz7You have exceeded the rate limit for the LangSmith API.Nr   r   r   r   r'   r'   9   s        AAAAr   r'   c                      e Zd ZdZdS )LangSmithAuthErrorz-Couldn't authenticate with the LangSmith API.Nr   r   r   r   r)   r)   =   s        7777r   r)   c                      e Zd ZdZdS )LangSmithNotFoundErrorz%Couldn't find the requested resource.Nr   r   r   r   r+   r+   A   s        ////r   r+   c                      e Zd ZdZdS )LangSmithConflictErrorzThe resource already exists.Nr   r   r   r   r-   r-   E           &&&&r   r-   c                      e Zd ZdZdS )LangSmithConnectionErrorz&Couldn't connect to the LangSmith API.Nr   r   r   r   r0   r0   I           0000r   r0   c                  $     e Zd ZdZd
 fd	Z xZS )LangSmithExceptionGroupz%Port of ExceptionGroup for Py < 3.11.argsr   
exceptionsSequence[Exception]kwargsreturnNonec               H     t                      j        |i | || _        dS )zInitialize.N)super__init__r5   )selfr5   r4   r7   	__class__s       r   r<   z LangSmithExceptionGroup.__init__P   s,     	$)&)))$r   )r4   r   r5   r6   r7   r   r8   r9   )r   r   r   r   r<   __classcell__r>   s   @r   r3   r3   M   sC        //% % % % % % % % % %r   r3   c                      e Zd ZdZdS )LangSmithWarningzBase class for warnings.Nr   r   r   r   rB   rB   [   s        """"r   rB   c                      e Zd ZdZdS )LangSmithMissingAPIKeyWarningzWarning for missing API key.Nr   r   r   r   rD   rD   _   r.   r   rD   ctxOptional[dict]r8   Union[bool, Literal['local']]c                    ddl mc m} ddlm}m} | p	 |            }|d         |d         S  |            rdS |j        |j        S t          dt          dd	          	          }|d
k    S )z"Return True if tracing is enabled.r   N)get_current_run_treeget_tracing_contextenabledT
TRACING_V2TRACING defaulttrue)langsmith._internal._context	_internal_contextlangsmith.run_helpersrI   rJ   _GLOBAL_TRACING_ENABLEDget_env_var)rE   rT   rI   rJ   tc
var_results         r   tracing_is_enabledrZ   c   s     433333333OOOOOOOO		%##%%B
 
)} )} t'3//\;yRT3U3U3UVVVJr   boolc                 ,    t          dd          dk    S )z"Return True if testing is enabled.TEST_TRACKINGrN   rO   falserW   r   r   r   test_tracking_is_disabledr`   {   s    333w>>r   
arg_groupstuple[str, ...]r   c                      d fd}|S )z7Validate specified keyword args are mutually exclusive.funcr   r8   c                L     t          j                   d fd            }|S )Nr4   r   r7   r8   c                     fdD             }d t          |          D             }|r3fd|D             }t          dd                    |                      | i S )z3Validate exactly one arg in each group is not None.c                F    g | ]}t          fd |D                       S )c              3  F   K   | ]}                     |          dV  d S )N   )get).0argr7   s     r   	<genexpr>zJxor_args.<locals>.decorator.<locals>.wrapper.<locals>.<listcomp>.<genexpr>   s2      JJ#fjjoo.IA.I.I.I.IJJr   )sum)rk   	arg_groupr7   s     r   
<listcomp>z@xor_args.<locals>.decorator.<locals>.wrapper.<locals>.<listcomp>   sF        JJJJJJJJJ  r   c                $    g | ]\  }}|d k    |S ri   r   )rk   icounts      r   rp   z@xor_args.<locals>.decorator.<locals>.wrapper.<locals>.<listcomp>   s!    PPPHAuUaZZaZZZr   c                F    g | ]}d                      |                   S ), )join)rk   rs   ra   s     r   rp   z@xor_args.<locals>.decorator.<locals>.wrapper.<locals>.<listcomp>   s)    &X&X&XAtyyA'?'?&X&X&Xr   zFExactly one argument in each of the following groups must be defined: rv   )	enumerate
ValueErrorrw   )r4   r7   countsinvalid_groupsinvalid_group_namesra   rd   s    `   r   wrapperz,xor_args.<locals>.decorator.<locals>.wrapper   s       !+  F QP	&0A0APPPN &X&X&X&X&X&X&X# 9		"5669 9  
 4((((r   )r4   r   r7   r   r8   r   )	functoolswraps)rd   r}   ra   s   ` r   	decoratorzxor_args.<locals>.decorator   sC    				) 	) 	) 	) 	) 	) 
		)  r   )rd   r   r8   r   r   )ra   r   s   ` r   xor_argsr      s)         ( r   response(Union[requests.Response, httpx.Response]r9   c                :   	 |                                   dS # t          j        $ r-}t          j        t          |          | j                  |d}~wt
          j        $ r9}t          j        t          |           d| j         | j        |           |d}~ww xY w)z&Raise an error with the response text.Nz: )requestr   )raise_for_statusrequests	HTTPErrorstrtexthttpxHTTPStatusErrorr   )r   es     r   raise_for_status_with_textr      s    	!!##### ? ? ? Q77Q>    #1vv(((($
 
 
 		s     B(AB!4BBenuUnion[enum.Enum, str]r   c                H    t          | t          j                  r| j        S | S )zGet the value of a string enum.)
isinstanceenumEnumvalue)r   s    r   get_enum_valuer      s#    #ty!! yJr   ri   )maxsizelevelintmessagec                <    t                               | |           dS )z4Log a message at the specified level, but only once.N)_LOGGERlog)r   r   s     r   log_oncer      s     KKwr   Mapping[str, Any]c                    | st          d          d| v rKd| vrt          d|  d          | d         d                             dd                                          S d	| vrt          d
|  d          | d	         S )NMessage is empty.lcid*Unexpected format for serialized message: z Message does not have an id.MessagerN   type&Unexpected format for stored message: z Message does not have a type.)ry   replacelowerr   s    r   _get_message_typer      s     .,---ww0W 0 0 0   t}R ((B77==???  1 1 1 1   vr   c                    | st          d          d| v rd| vrt          d|  d          | d         S d| vrt          d|  d          | d         S )	Nr   r   r7   r   z Message does not have kwargs.datar   z Message does not have data.)ry   r   s    r   _get_message_fieldsr      s     .,---w7""1W 1 1 1   x    / / / /   vr   dict[str, Any]c                H    t          |           }t          |           }||dS )z&Extract message from a message object.r   r   )r   r   )r   message_typemessage_datas      r   _convert_messager      s*    $W--L&w//L ,777r   inputslist[dict[str, Any]]c                    d| v rd | d         D             S d| v rt          | d                   gS t          d|  d          )aG  Extract messages from the given inputs dictionary.

    Args:
        inputs (Mapping[str, Any]): The inputs dictionary.

    Returns:
        List[Dict[str, Any]]: A list of dictionaries representing
            the extracted messages.

    Raises:
        ValueError: If no message(s) are found in the inputs dictionary.
    messagesc                ,    g | ]}t          |          S r   )r   )rk   r   s     r   rp   z,get_messages_from_inputs.<locals>.<listcomp>   s!    LLLg ))LLLr   r   z-Could not find message(s) in run with inputs .)r   ry   )r   s    r   get_messages_from_inputsr      sc     VLL
9KLLLLF 	!23344
NVNNN
O
OOr   outputsc                   d| vrt          d|  d          | d         }t          |          dk    r#t          dt          |           d| d          |d         }d|vrt          d	| d
          t          |d                   S )a'  Retrieve the message generation from the given outputs.

    Args:
        outputs (Mapping[str, Any]): The outputs dictionary.

    Returns:
        Dict[str, Any]: The message generation.

    Raises:
        ValueError: If no generations are found or if multiple generations are present.
    generations,No generations found in in run with output: r   ri   z3Chat examples expect exactly one generation. Found z generations: r   r   z"Unexpected format for generation: z%. Generation does not have a message.)ry   lenr   r   r   first_generations      r   #get_message_generation_from_outputsr      s     G##RRRRSSS-(K
;1E+&&E E6AE E E
 
 	
 #1~(((31A 3 3 3
 
 	
 ,Y7888r   c                    d| v r| d         S d| v r6| d         }t          |          dk    r|d         S t          d|  d          t          d|  d          )	zRetrieve the prompt from the given inputs.

    Args:
        inputs (Mapping[str, Any]): The inputs dictionary.

    Returns:
        str: The prompt.

    Raises:
        ValueError: If the prompt is not found or if multiple prompts are present.
    promptpromptsri   r   z$Multiple prompts in run with inputs z!. Please create example manually.z)Could not find prompt in run with inputs r   )r   ry   )r   r   s     r   get_prompt_from_inputsr     s     6hF#w<<11:/6 / / /
 
 	
 JJJJ
K
KKr   c                    d| vrt          d|  d          | d         }t          |          dk    rt          d|           |d         }d|vrt          d|           |d         S )	z(Get the LLM generation from the outputs.r   r   r   ri   zMultiple generations in run: r   r   zNo text in generation: )ry   r   r   s      r   get_llm_generation_from_outputsr   .  s    G##RRRRSSS-(K
;1FFFGGG"1~%%%E3CEEFFFF##r   	list[str]c                 R   	 t          j        g dt           j        t           j                   ddgS # t           j        t          f$ r] 	 t          j        ddgt           j        t           j                   dgcY S # t           j        t          f$ r t          d          w xY ww xY w)z7Get the correct docker compose command for this system.)dockercompose	--version)stdoutstderrr   r   zdocker-composer   zNeither 'docker compose' nor 'docker-compose' commands are available. Please install the Docker server following the instructions for your operating system at https://docs.docker.com/engine/install/)
subprocess
check_callDEVNULLCalledProcessErrorFileNotFoundErrorry   r   r   r   get_docker_compose_commandr   ;  s    ...%%	
 	
 	
 	

 )$$)+<=   	!!;/!)!)   
 %%%%%-/@A 	 	 	E  	s!   03 B&
/A<9B&<&B""B&ls_schemas.BaseMessageLikedictc                    | j         d| j        id}| j        r*t          | j                  dk    ri | j        |d         d<   |S )z*Convert a LangChain message to an example.contentr   r   r   additional_kwargs)r   r   r   r   )r   	converteds     r   convert_langchain_messager   V  s`     GO,! !I
   OS)B%C%Ca%G%G1NG4M1N	&-.r   objobjectc           
        t          t          t          | dd          t                    t          t          | dd          t                    t          | d          o"t          t          | d          t                    g          S )zCheck if the given object is similar to BaseMessage.

    Args:
        obj (object): The object to check.

    Returns:
        bool: True if the object is similar to BaseMessage, False otherwise.
    r   Nr   r   )allr   getattrr   r   hasattr)r   s    r   is_base_message_liker   b  st     wsIt44c::ws$7>>EEC  JZV0D0Dc%J%J	
  r   d   )	LANGSMITH	LANGCHAIN)
namespacesnamerP   Optional[str]r   tuplec               x      fd|D             }|D ]' t           j                                       }||c S (|S )a+  Retrieve an environment variable from a list of namespaces.

    Args:
        name (str): The name of the environment variable.
        default (Optional[str], optional): The default value to return if the
            environment variable is not found. Defaults to None.
        namespaces (Tuple, optional): A tuple of namespaces to search for the
            environment variable. Defaults to ("LANGSMITH", "LANGCHAINs").

    Returns:
        Optional[str]: The value of the environment variable if found,
            otherwise the default value.
    c                    g | ]	}| d  
S )_r   )rk   	namespacer   s     r   rp   zget_env_var.<locals>.<listcomp>  s'    ???y	""D""???r   )osenvironrj   )r   rP   r   namesr   s   `    r   rW   rW   t  sZ    ( @???J???E  
t$$LLL Nr   Tc           
         t           j                            dt          dt          d| rdnd                              S )z,Get the project name for a LangSmith tracer.HOSTED_LANGSERVE_PROJECT_NAMEPROJECTSESSIONrP   NrO   )r   r   rj   rW   )return_default_values    r   get_tracer_projectr     sY     :>>
 	(  0D#N99$  		
 	
 	
  r   c                  .     e Zd ZdZdd fdZdd
Z xZS )FilterPoolFullWarningzFFilter urrllib3 warnings logged when the connection pool isn't reused.rN   r   r   hostr8   r9   c                X    t                                          |           || _        dS )zInitialize the FilterPoolFullWarning filter.

        Args:
            name (str, optional): The name of the filter. Defaults to "".
            host (str, optional): The host to filter. Defaults to "".
        N)r;   r<   _host)r=   r   r   r>   s      r   r<   zFilterPoolFullWarning.__init__  s(     	


r   r[   c                H    |                                 }d|vrdS | j        |vS )zJurllib3.connectionpool:Connection pool is full, discarding connection: ...z.Connection pool is full, discarding connectionT)
getMessager   r=   recordmsgs      r   filterzFilterPoolFullWarning.filter  s0    !!;3FF4z$$r   )rN   rN   )r   r   r   r   r8   r9   r8   r[   )r   r   r   r   r<   r  r?   r@   s   @r   r   r     s\        PP      % % % % % % % %r   r   c                      e Zd ZdZddZdS )FilterLangSmithRetryz!Filter for retries from this lib.r8   r[   c                2    |                                 }d|vS )z!Filter retries from this library.LangSmithRetry)r   r  s      r   r  zFilterLangSmithRetry.filter  s      !!s**r   Nr  )r   r   r   r   r  r   r   r   r  r    s.        +++ + + + + +r   r  c                      e Zd ZdZdS )r	  z&Wrapper to filter logs with this name.Nr   r   r   r   r	  r	    r1   r   r	  loggerlogging.LoggerfiltersSequence[logging.Filter]Generator[None, None, None]c              #  (  K   t           5  |D ]}|                     |           	 ddd           n# 1 swxY w Y   	 dV  t           5  |D ]B}	 |                     |           # t          $ r t                              d           Y ?w xY w	 ddd           dS # 1 swxY w Y   dS # t           5  |D ]B}	 |                     |           # t          $ r t                              d           Y ?w xY w	 ddd           w # 1 swxY w Y   w xY w)zTemporarily adds specified filters to a logger.

    Parameters:
    - logger: The logger to which the filters will be added.
    - filters: A sequence of logging.Filter objects to be temporarily added
        to the logger.
    NzFailed to remove filter)_FILTER_LOCK	addFilterremoveFilterBaseExceptionr   warning)r  r  r  s      r   filter_logsr    s1      
 % % 	% 	%FV$$$$	%% % % % % % % % % % % % % % %? 	? 	?! ? ??''////$ ? ? ?OO$=>>>>>??	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	?\ 	? 	?! ? ??''////$ ? ? ?OO$=>>>>>??	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	?s   266B* 	BA%$B%$B	BBBB!$B!*D2D8CD$C52D4C55D9DD		DD	Dcachec                ,    | | S t          dd          S )zGet the testing cache directory.

    Args:
        cache (Optional[str]): The cache path.

    Returns:
        Optional[str]: The cache path if provided, otherwise the value
        from the LANGSMITH_TEST_CACHE environment variable.
    N
TEST_CACHErO   r_   )r  s    r   get_cache_dirr    s"     |T2222r   ignore_hostsallow_hostsr   r   r  Optional[Sequence[str]]r  c                   |rt           fd|D                       rdS |rU	 t          j         j                  }n# t          $ r Y dS w xY w|j        pdt           fd|D                       }|sdS i  _         S )z=Filter request headers based on ignore_hosts and allow_hosts.c              3  L   K   | ]}j                             |          V  d S N)url
startswith)rk   r   r   s     r   rm   z)filter_request_headers.<locals>.<genexpr>  s3      RRTGK22488RRRRRRr   NrN   c              3     K   | ]Q}|                     d           rj                             |          n|k    p                    d|           V  RdS ))zhttp://zhttps://r   N)r#  r"  endswith)rk   r   r   request_hosts     r   rm   z)filter_request_headers.<locals>.<genexpr>  s       	
 	
  ??#:;;O&&t,,,!T)N\-B-B:t::-N-N	
 	
 	
 	
 	
 	
r   )anyurllib_parseurlparser"  	Exceptionhostnameheaders)r   r  r  
parsed_urlhost_matchesr&  s   `    @r   filter_request_headersr/    s      RRRR\RRRRR t 	%.w{;;JJ 	 	 	44	 "*0b 	
 	
 	
 	
 	
 $	
 	
 	
 	
 	
  	4GONs   ? 
AApathUnion[str, pathlib.Path]c           	   #    K   	 ddl }n# t          $ r t          d          w xY wddlm} |                                 t
          j                            |           \  }}|                    |	                    d          s|	                    d          rdnd|d	g d
ddgfd          }|
                    |          5  dV  ddd           dS # 1 swxY w Y   dS )Use a cache for requests.r   NzNvcrpy is required to use caching. Install with:pip install -U "langsmith[vcr]")_patchz.yamlz.ymlyamljsonnew_episodes)urimethodr0  bodyauthorizationz
Set-Cookiec                (    t          |           S )Nr  )r/  )r   r  r  s    r   <lambda>zwith_cache.<locals>.<lambda>8  s    .D,K/
 /
 /
 r   )
serializercassette_library_dirrecord_modematch_onfilter_headersbefore_record_request)vcrImportErrorlangsmith._internalr4  patch_urllib3r   r0  splitVCRr%  use_cassette)r0  r  r  rD  rG  	cache_dir
cache_filels_vcrs    ``     r   
with_cacherN    s     




 
 
 
.
 
 	

 <;;;;;!!!GMM$//IzWW ""7++/9/B/B6/J/JFF& #222'6
 
 
 
 
   F  
		Z	(	(                   s    %CC!C"Optional[Union[str, pathlib.Path]]c              #  v   K   | 0t          | ||          5  dV  ddd           dS # 1 swxY w Y   dS dV  dS )r3  N)rN  )r0  r  r  s      r   with_optional_cacherQ  @  s       lK88 	 	EEE	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   (,,c                     t          j        t          j                     } d | D             }d                    |          S )Nc                    g | ]}d |v|	S )z
langsmith/r   )rk   lines     r   rp   z_format_exc.<locals>.<listcomp>Q  s"    LLLt<t3K3Kd3K3K3Kr   rN   )	tracebackformat_exceptionsysexc_inforw   )tb_linesfiltered_liness     r   _format_excr[  N  s:    )3<>>:HLLxLLLN77>"""r   T   valmemodict[int, Any]	max_depth_depthc                   t          |           }t          |dd           }|	  |          S # t          $ r Y nw xY wk    r| S t          | t                    r"fd|                                 D             S t          | t                    rfd| D             S t          | t                    rt          fd| D                       S t          | t                    rfd| D             S | S )N__deepcopy__c           
     h    i | ].\  }}t          |d z             t          |d z             /S rr   _middle_copy)rk   kvrb  ra  r_  s      r   
<dictcomp>z _middle_copy.<locals>.<dictcomp>f  sZ     
 
 
 1 D)VaZ88,4FQJ; ;
 
 
r   c           	     :    g | ]}t          |d z             S rr   rf  rk   itemrb  ra  r_  s     r   rp   z _middle_copy.<locals>.<listcomp>m  +    PPPDT4FQJ??PPPr   c              3  B   K   | ]}t          |d z             V  dS )ri   Nrf  rl  s     r   rm   z_middle_copy.<locals>.<genexpr>o  s5      UU\$i!DDUUUUUUr   c           	     :    h | ]}t          |d z             S rr   rf  rl  s     r   	<setcomp>z_middle_copy.<locals>.<setcomp>q  rn  r   )	r   r   r  r   r   itemslistr   set)r^  r_  ra  rb  clscopiers    ```  r   rg  rg  X  sg    s))CS.$//F	6$<< 	 	 	D	
#t 

 
 
 
 
 
 			
 
 
 	
 #t QPPPPPPCPPPP#u VUUUUUUQTUUUUUU#s QPPPPPPCPPPPJs   
2 
??c                    i }	 t          j        | |          S # t          $ rB}t                              dt          |                     t          | |          cY d}~S d}~ww xY w)zDeep copy a value with a compromise for uncopyable objects.

    Args:
        val: The value to be deep copied.

    Returns:
        The deep copied value.
    zFailed to deepcopy input: %sN)copydeepcopyr  r   debugreprrg  )r^  r_  r   s      r   deepish_copyr|  v  s{     D'}S$''' ' ' '
 	4d1gg>>>C&&&&&&&&'s    
A%7A A% A%current_versiontarget_versionc                n    ddl m} |                    |           }|                    |          }||k    S )zGCheck if the current version is greater or equal to the target version.r   )version)	packagingr  r   )r}  r~  r  currenttargets        r   is_version_greater_or_equalr    sA    !!!!!!mmO,,G]]>**Ffr   
identifiertuple[str, str, str]c                   | rC|                      d          dk    s*|                     d          s|                     d          rt          d|            |                     dd          }|d         }t          |          dk    r|d         nd}d|v r4|                    dd          \  }}|r|st          d|            |||fS |st          d|            d||fS )aE  Parse a string in the format of owner/name:hash, name:hash, owner/name, or name.

    Args:
        identifier (str): The prompt identifier to parse.

    Returns:
        Tuple[str, str, str]: A tuple containing (owner, name, hash).

    Raises:
        ValueError: If the identifier doesn't match the expected formats.
    /ri   zInvalid identifier format: :r   latest-)rt   r#  r%  ry   rH  r   )r  parts
owner_namecommitownerr   s         r   parse_prompt_identifierr    s*    EC  1$$  %% %s## % CzCCDDDS!$$EqJUaU1XXXF
j &&sA..t 	ID 	IG:GGHHHdF"" 	IG:GGHHHJ&&r   Pc                  8     e Zd ZdZd fd
Zdddd fdZ xZS )ContextThreadPoolExecutorz?ThreadPoolExecutor that copies the context to the child thread.rd   Callable[P, T]r4   P.argsr7   P.kwargsr8   	Future[T]c           
         t                                          t          t          dt          f         t          j        t          j                    j	        |g|R i |                    S )aC  Submit a function to the executor.

        Args:
            func (Callable[..., T]): The function to submit.
            *args (Any): The positional arguments to the function.
            **kwargs (Any): The keyword arguments to the function.

        Returns:
            Future[T]: The future for the function.
        .)
r;   submitr   r   r\  r~   partialcontextvarscopy_contextrun)r=   rd   r4   r7   r>   s       r   r  z ContextThreadPoolExecutor.submit  ss      ww~~a !,..2D;?  CI  
 
 	
r   Nri   timeout	chunksizefnCallable[..., T]	iterablesIterable[Any]r  Optional[float]r  r   Iterator[T]c                   d t          t          |d                             D             d	fd} t                      j        |g|R ||dS )
a  Return an iterator equivalent to stdlib map.

        Each function will receive its own copy of the context from the parent thread.

        Args:
            fn: A callable that will take as many arguments as there are
                passed iterables.
            timeout: The maximum number of seconds to wait. If None, then there
                is no limit on the wait time.
            chunksize: The size of the chunks the iterable will be broken into
                before being passed to a child process. This argument is only
                used by ProcessPoolExecutor; it is ignored by
                ThreadPoolExecutor.

        Returns:
            An iterator equivalent to: map(func, *iterables) but the calls may
            be evaluated out-of-order.

        Raises:
            TimeoutError: If the entire result iterator could not be generated
                before the given timeout.
            Exception: If fn(*args) raises for any values.
        c                4    g | ]}t          j                    S r   )r  r  )rk   r   s     r   rp   z1ContextThreadPoolExecutor.map.<locals>.<listcomp>  s!    QQQ1K,..QQQr   r   r4   r   r8   r\  c                 D                                      j        g| R  S r!  )popr  )r4   contextsr  s    r   _wrapped_fnz2ContextThreadPoolExecutor.map.<locals>._wrapped_fn  s&    %8<<>>%b040000r   r  )r4   r   r8   r\  )ranger   r;   map)r=   r  r  r  r  r  r  r>   s    `    @r   r  zContextThreadPoolExecutor.map  s    < RQc)A,>O>O8P8PQQQ	1 	1 	1 	1 	1 	1 	1 uww{

 
 	
 
 
 	
r   )rd   r  r4   r  r7   r  r8   r  )
r  r  r  r  r  r  r  r   r8   r  )r   r   r   r   r  r  r?   r@   s   @r   r  r    ss        II
 
 
 
 
 
: $((
 (
 (
 (
 (
 (
 (
 (
 (
 (
 (
 (
r   r  api_urlc                .   | p#t          t          t          dd                    }|                                st	          d          |                                                    d                              d                              d          S )zBGet the LangSmith API URL from the environment or the given value.ENDPOINTzhttps://api.smith.langchain.comrO   z!LangSmith API URL cannot be empty"'r  )r   r   rW   stripr%   rstrip)r  _api_urls     r   get_api_urlr    s     $5	
 	
 	
 H >> F !DEEE>>!!#&&,,S1188===r   api_keyc                    | | nt          dd          }||                                sdS |                                                    d                              d          S )z8Get the API key from the environment or the given value.NAPI_KEYrO   r  r  rW   r  )r  api_key_s     r   get_api_keyr    sd    !-ww;yRV3W3W3WHx~~//t>>!!#&&,,S111r   workspace_idc                    | | nt          dd          }||                                sdS |                                                    d                              d          S )zGet workspace ID.NWORKSPACE_IDrO   r  r  r  )r  workspace_id_s     r   get_workspace_idr    sr     # 	666 
 M$7$7$9$9t  &&s++11#666r   r"  c                   	 t          j        |           j                            d          d         }t	          j        |          }|dk    p)|                    d          p|                    d          S # t          j        $ r Y dS w xY w)zCheck if the URL is localhost.

    Parameters
    ----------
    url : str
        The URL to check.

    Returns:
    -------
    bool
        True if the URL is localhost, False otherwise.
    r  r   z	127.0.0.1z0.0.0.0z::F)r(  urlsplitnetlocrH  socketgethostbynamer#  gaierror)r"  r  ips      r   _is_localhostr  #  s    &s++288==a@!&))[ SBMM)$<$<Sd@S@SS?   uus   A5A8 8B
B   web_urlc                T   | r| S t          j        |          }t          |          rd}n|t          |j                                      d          rWt          |j                                      dd          d         }t          j        |                    |                    }nt          |j                                      d          rWt          |j                                      dd          d         }t          j        |                    |                    }nt          |j	                  
                    d          rd}nVt          |j	                  
                    d	          rd
}n,t          |j	                  
                    d          rd}nd}|S )z1Get the host URL based on the web URL or API URL.zhttp://localhostz/apiri   r   )r0  z/api/v1zeu.zhttps://eu.smith.langchain.comzdev.zhttps://dev.smith.langchain.comzbeta.z https://beta.smith.langchain.comzhttps://smith.langchain.com)r(  r)  r  r   r0  r%  rsplit
urlunparse_replacer  r#  )r  r  r-  linknew_paths        r   get_host_urlr  8  s     &w//JW -!	Z_			&	&v	.	. -z''..vq99!<&z':':':'I'IJJ	Z_			&	&y	1	1 
-z''..y!<<Q?&z':':':'I'IJJ	Z			*	*5	1	1 -/	Z			*	*6	2	2 -0	Z			*	*7	3	3 -1,Kr   r  depthc                   |dk    st          |           st          |           S t          | d          r| j        S t	          | t
          j                  rt          | j        |dz             S t          | d          rIt          | d          r!t          | j	        d          r| j	        j        S t          | j
        |dz             S t          |           S )Nr  r   ri   __call__r>   )callabler   r   r   r   r~   r  _get_function_namerd   r>   r  )r  r  s     r   r  r  Q  s    qyyy2wwr: {"i'(( 6!"'519555r: :2{## 	)j(I(I 	)<((!"+uqy999r77Nr   c                    t          | t                    r|                                 dk    p| dk    S t          |           S )zCheck if the value is truish.

    Args:
        val (Any): The value to check.

    Returns:
        bool: True if the value is truish, False otherwise.
    rQ   1)r   r   r   r[   )r^  s    r   	is_truishr  c  s>     #s 3yy{{f$2s
299r   r!  )rE   rF   r8   rG   r  )ra   rb   r8   r   )r   r   r8   r9   )r   r   r8   r   )r   r   r   r   r8   r9   )r   r   r8   r   )r   r   r8   r   )r   r   r8   r   )r   r   r8   r   )r   r   r8   r   )r   r   r8   r   )r   r   r8   r   )r8   r   )r   r   r8   r   )r   r   r8   r[   )r   r   rP   r   r   r   r8   r   )T)r8   r   )r  r  r  r  r8   r  )r  r   r8   r   )r   r   r  r  r  r  r8   r   )NN)r0  r1  r  r  r  r  r8   r  )r0  rO  r  r  r  r  r8   r  )r8   r   )r]  r   )
r^  r\  r_  r`  ra  r   rb  r   r8   r\  )r^  r\  r8   r\  )r}  r   r~  r   r8   r[   )r  r   r8   r  )r  r   r8   r   )r  r   r8   r   )r  r   r8   r   )r"  r   r8   r[   )r  r   r  r   )r   )r  r   r  r   r8   r   )r^  r   r8   r[   )lr   
__future__r   
contextlibr  rx  r   r~   loggingr   pathlibr  r   rW  	threadingrU  collections.abcr   r   r   r   r   concurrent.futuresr	   r
   typingr   r   r   r   r   r   r   urllibr   r(  r   r   typing_extensionsr   urllib3.utilr   	langsmithr   
ls_schemas	getLoggerr   r   r*  r   r!   r#   r%   r'   r)   r+   r-   r0   r3   UserWarningrB   rD   rZ   r`   r   r   r   	lru_cacher   r   r   r   r   r   r   r   r   r   r   rW   r   Filterr   r  r	  RLockr  contextmanagerr  r  r/  rN  rQ  r[  r\  rg  r|  r  r  r  r  r  r  r  r  r  r  r  r   r   r   <module>r     s       " " " " " "                				       



         L L L L L L L L L L L L L L 9 9 9 9 9 9 9 9                  ) ( ( ( ( (   ' ' ' ' ' '       + + + + + +
'
H
%
%H H H H HY H H HD D D D D D D D5 5 5 5 5n 5 5 5L L L L L L L LB B B B Bn B B B8 8 8 8 8 8 8 80 0 0 0 0^ 0 0 0' ' ' ' '^ ' ' '1 1 1 1 1~ 1 1 1% % % % %n % % %# # # # #{ # # #' ' ' ' '$4 ' ' '         0? ? ? ?
   4        Q        
   &   &8 8 8 8P P P P(9 9 9 9:L L L L2
$ 
$ 
$ 
$ Q    4	 	 	 	   $ S!!! " 3	     "!6 Q     &% % % % %GN % % %*+ + + + +7> + + +1 1 1 1 1U 1 1 1 y   ? ? ? ?23 3 3 3$ -1+/	! ! ! ! ! !H  -1+/% % % % %P  -1+/
 
 
 
 
# # # # GCLL EF    <' ' ' '*    '  '  '  'F IcNND
 D
 D
 D
 D
 2 D
 D
 D
N> > > >2 2 2 2	7 	7 	7 	7   * Q    0    $     r   