
    Ngb                       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 ddlmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z" 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/        e0          Z1 G d
 de2          Z3 G d de3          Z4 G d de3          Z5 G d de3          Z6 G d de3          Z7 G d de3          Z8 G d de3          Z9 G d de3          Z: G d de3          Z; G d de<          Z= G d de=          Z>ddd$Z?dd&Z@dd*ZAdd.ZBdd2ZC ejD        d34          dd8            ZEdd:ZFdd;ZGdd=ZHdd@ZIddBZJddCZKddDZL ejD        d34          ddF            ZMddIZNddLZO ejD        dM4          	 ddNdOddU            ZP ejD        d34          dddW            ZQ G dX dYejR                  ZS G dZ d[ejR                  ZT G d\ d]e+          ZU ejV                    ZWejX        ddc            ZYddeZZejX        	 dddj            Z[ejX        	 dddl            Z\ddmZ] e dn          Z^	 ddduZ_ddvZ`ddyZadd|Zb e)d}          Zc G d~ de          ZdddZeddZfddZg ejD        d4          dd            ZhdddZidS )zGeneric utility functions.    )annotationsN)FutureThreadPoolExecutor)AnyCallableDict	GeneratorIterableIteratorListLiteralMappingOptionalSequenceTuple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__     K/var/www/html/ai-engine/env/lib/python3.11/site-packages/langsmith/utils.pyr   r   0   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$   4   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&   8   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(   <   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*   @   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,   D   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.   H   s        ////r!   r.   c                      e Zd ZdZdS )LangSmithConflictErrorzThe resource already exists.Nr   r    r!   r"   r0   r0   L           &&&&r!   r0   c                      e Zd ZdZdS )LangSmithConnectionErrorz&Couldn't connect to the LangSmith API.Nr   r    r!   r"   r3   r3   P           0000r!   r3   c                      e Zd ZdZdS )LangSmithWarningzBase class for warnings.Nr   r    r!   r"   r6   r6   W   s        """"r!   r6   c                      e Zd ZdZdS )LangSmithMissingAPIKeyWarningzWarning for missing API key.Nr   r    r!   r"   r8   r8   [   r1   r!   r8   ctxOptional[dict]returnUnion[bool, Literal['local']]c                    ddl m}m} | p	 |            }|d         |d         S  |            rdS t          dt          dd	          	          }|d
k    S )z"Return True if tracing is enabled.r   )get_current_run_treeget_tracing_contextenabledNT
TRACING_V2TRACING defaulttrue)langsmith.run_helpersr>   r?   get_env_var)r9   r>   r?   tc
var_results        r"   tracing_is_enabledrK   _   s    OOOOOOOO		%##%%B
 
)} )} t\;yRT3U3U3UVVVJr!   boolc                 ,    t          dd          dk    S )z"Return True if testing is enabled.TEST_TRACKINGrC   rD   falserH   r    r!   r"   test_tracking_is_disabledrQ   r   s    333w>>r!   
arg_groupsTuple[str, ...]r   c                      d fd}|S )z7Validate specified keyword args are mutually exclusive.funcr   r;   c                L     t          j                   d fd            }|S )Nargsr   kwargsr;   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argrX   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)r^   	arg_grouprX   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 r\   r    )r^   icounts      r"   rc   z@xor_args.<locals>.decorator.<locals>.wrapper.<locals>.<listcomp>   s!    PPPHAuUaZZaZZZr!   c                F    g | ]}d                      |                   S ), )join)r^   rf   rR   s     r"   rc   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: ri   )	enumerate
ValueErrorrj   )rW   rX   countsinvalid_groupsinvalid_group_namesrR   rU   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!   )rW   r   rX   r   r;   r   )	functoolswraps)rU   rp   rR   s   ` r"   	decoratorzxor_args.<locals>.decoratorz   sC    				) 	) 	) 	) 	) 	) 
		)  r!   )rU   r   r;   r   r    )rR   rs   s   ` r"   xor_argsrt   w   s)         ( r!   response(Union[requests.Response, httpx.Response]Nonec                    	 |                                   dS # t          j        $ r-}t          j        t          |          | j                  |d}~ww xY w)z&Raise an error with the response text.N)raise_for_statusrequests	HTTPErrorstrtext)ru   es     r"   raise_for_status_with_textr      s^    ?!!##### ? ? ? Q77Q>?s    A(AA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!   r\   )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.MessagerC   type&Unexpected format for stored message: z Message does not have a type.)rl   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   rX   r   z Message does not have kwargs.datar   z Message does not have data.)rl   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   )r^   r   s     r"   rc   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   rl   )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   r\   z3Chat examples expect exactly one generation. Found z generations: r   r   z"Unexpected format for generation: z%. Generation does not have a message.)rl   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promptsr\   r   z$Multiple prompts in run with inputs z!. Please create example manually.z)Could not find prompt in run with inputs r   )r   rl   )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   r\   zMultiple generations in run: r   r}   zNo text in generation: )rl   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FileNotFoundErrorrl   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   G  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   S  st     wsIt44c::ws$7>>EEC  JZV0D0Dc%J%J	
  r!   d   )	LANGSMITH	LANGCHAIN)
namespacesnamerE   Optional[str]r   r   c               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    )r^   	namespacer   s     r"   rc   zget_env_var.<locals>.<listcomp>y  s'    ???y	""D""???r!   )osenvironr]   )r   rE   r   namesr   s   `    r"   rH   rH   e  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SESSIONrE   NrD   )r   r   r]   rH   )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.rC   r   r|   hostr;   rw   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)super__init___host)selfr   r   	__class__s      r"   r   zFilterPoolFullWarning.__init__  s(     	


r!   rL   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!   )rC   rC   )r   r|   r   r|   r;   rw   r;   rL   )r   r   r   r   r   r   __classcell__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.r;   rL   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     r4   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_CACHErD   rP   )r  s    r"   get_cache_dirr    s"     |T2222r!   pathUnion[str, pathlib.Path]ignore_hostsOptional[Sequence[str]]c              #    K   	 ddl }n# t          $ r t          d          w xY wddlm} |                                 dfd}t
          j                            |           \  }}|                    |	                    d	          s|	                    d
          rdnd|dg dddg|          }|
                    |          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]")_patchrequestr   r;   c                V     rt           fdD                       rd S i  _         S )Nc              3  L   K   | ]}j                             |          V  d S N)url
startswith)r^   r   r  s     r"   r`   z>with_cache.<locals>._filter_request_headers.<locals>.<genexpr>  s3      VV 6 6t < <VVVVVVr!   )anyheaders)r  r  s   `r"   _filter_request_headersz+with_cache.<locals>._filter_request_headers  sA     	CVVVVVVVVV 	4r!   z.yamlz.ymlyamljsonnew_episodes)urimethodr  bodyauthorizationz
Set-Cookie)
serializercassette_library_dirrecord_modematch_onfilter_headersbefore_record_request)r  r   r;   r   )vcrImportErrorlangsmith._internalr  patch_urllib3r   r  splitVCRendswithuse_cassette)r  r  r.  r1  r   	cache_dir
cache_filels_vcrs    `      r"   
with_cacher9    s     





 
 
 
.
 
 	

 <;;;;;!!!      GMM$//IzWW ""7++/9/B/B6/J/JFF& #222'65   F 
		Z	(	(                   s   
 $	CC"C"Optional[Union[str, pathlib.Path]]c              #  t   K   | /t          | |          5  dV  ddd           dS # 1 swxY w Y   dS dV  dS )r  N)r9  )r  r  s     r"   with_optional_cacher<    s       l++ 	 	EEE	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   '++c                     t          j        t          j                     } d | D             }d                    |          S )Nc                    g | ]}d |v|	S )z
langsmith/r    )r^   lines     r"   rc   z_format_exc.<locals>.<listcomp>  s"    LLLt<t3K3Kd3K3K3Kr!   rC   )	tracebackformat_exceptionsysexc_inforj   )tb_linesfiltered_liness     r"   _format_excrF    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 re   _middle_copy)r^   kvrM  rL  rJ  s      r"   
<dictcomp>z _middle_copy.<locals>.<dictcomp>4  sZ     
 
 
 1 D)VaZ88,4FQJ; ;
 
 
r!   c           	     :    g | ]}t          |d z             S re   rQ  r^   itemrM  rL  rJ  s     r"   rc   z _middle_copy.<locals>.<listcomp>;  +    PPPDT4FQJ??PPPr!   c              3  B   K   | ]}t          |d z             V  dS )r\   NrQ  rW  s     r"   r`   z_middle_copy.<locals>.<genexpr>=  s5      UU\$i!DDUUUUUUr!   c           	     :    h | ]}t          |d z             S re   rQ  rW  s     r"   	<setcomp>z_middle_copy.<locals>.<setcomp>?  rY  r!   )	r   r   r
  r   r   itemslisttupleset)rI  rJ  rL  rM  clscopiers    ```  r"   rR  rR  &  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reprrR  )rI  rJ  r~   s      r"   deepish_copyrh  D  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)	packagingrl  r   )ri  rj  rl  currenttargets        r"   is_version_greater_or_equalrp  Y  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.
    /r\   zInvalid identifier format: :r   latest-)rg   r  r4  rl   r2  r   )rq  parts
owner_namecommitownerr   s         r"   parse_prompt_identifierr|  b  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.rU   Callable[P, T]rW   P.argsrX   P.kwargsr;   	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   rG  rq   partialcontextvarscopy_contextrun)r   rU   rW   rX   r   s       r"   r  z ContextThreadPoolExecutor.submit  ss      ww~~a !,..2D;?  CI  
 
 	
r!   Nr\   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  )r^   r   s     r"   rc   z1ContextThreadPoolExecutor.map.<locals>.<listcomp>  s!    QQQ1K,..QQQr!   r   rW   r   r;   rG  c                 D                                      j        g| R  S r  )popr  )rW   contextsr  s    r"   _wrapped_fnz2ContextThreadPoolExecutor.map.<locals>._wrapped_fn  s&    %8<<>>%b040000r!   r  )rW   r   r;   rG  )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!   )rU   r  rW   r  rX   r  r;   r  )
r  r  r  r  r  r  r  r   r;   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.comrD   z!LangSmith API URL cannot be empty"'rt  )r   r|   rH   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_KEYrD   r  r  )rH   r  )r  api_key_s     r"   get_api_keyr    sd    !-ww;yRV3W3W3WHx~~//t>>!!#&&,,S111r!   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.
    ru  r   z	127.0.0.1z0.0.0.0z::F)urllib_parseurlsplitnetlocr2  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                   | r| S t          j        |          }t          |          rd}nt          |j                                      d          rWt          |j                                      dd          d         }t          j        |                    |                    }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/apir\   r   )r  zeu.zhttps://eu.smith.langchain.comzdev.zhttps://dev.smith.langchain.comzhttps://smith.langchain.com)r  urlparser  r|   r  r4  rsplit
urlunparse_replacer  r  )r  r  
parsed_urllinknew_paths        r"   get_host_urlr    s      &w//JW 
-!	Z_			&	&v	.	. -z''..vq99!<&z':':':'I'IJJ	Z			*	*5	1	1 -/	Z			*	*6	2	2 -0,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   r\   __call__r   )callabler|   r   r   r   rq   r  _get_function_namerU   r   r  )r  r  s     r"   r  r    s    qyyy2wwr: {"i'(( 6!"'519555r: :2{## 	)j(I(I 	)<((!"+uqy999r77Nr!   r  )r9   r:   r;   r<   r   )rR   rS   r;   r   )ru   rv   r;   rw   )r   r   r;   r|   )r   r   r   r|   r;   rw   )r   r   r;   r|   )r   r   r;   r   )r   r   r;   r   )r   r   r;   r   )r   r   r;   r   )r   r   r;   r|   )r   r   r;   r|   )r;   r   )r   r   r;   r   )r   r   r;   rL   )r   r|   rE   r   r   r   r;   r   )T)r;   r   )r  r  r  r  r;   r  )r  r   r;   r   )r  r  r  r  r;   r  )r  r:  r  r  r;   r  )r;   r|   )rH  r   )
rI  rG  rJ  rK  rL  r   rM  r   r;   rG  )rI  rG  r;   rG  )ri  r|   rj  r|   r;   rL   )rq  r|   r;   rr  )r  r   r;   r|   )r  r   r;   r   )r  r|   r;   rL   )r  r   r  r|   )r   )r  r   r  r   r;   r|   )jr   
__future__r   
contextlibr  rd  r   rq   loggingr   pathlibr  r   rB  	threadingr@  concurrent.futuresr   r   typingr   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   urllibr   r  httpxrz   typing_extensionsr   urllib3.utilr   	langsmithr   
ls_schemas	getLoggerr   r   	Exceptionr   r$   r&   r(   r*   r,   r.   r0   r3   UserWarningr6   r8   rK   rQ   rt   r   r   	lru_cacher   r   r   r   r   r   r   r   r   r   r   rH   r   Filterr   r   r   RLockr  contextmanagerr  r  r9  r<  rF  rG  rR  rh  rp  r|  r}  r  r  r  r  r  r  r    r!   r"   <module>r     sC       " " " " " "                				       



         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# # # # #{ # # #' ' ' ' '$4 ' ' '         &? ? ? ?
   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 LP' ' ' ' 'T  -1	 	 	 	 	# # # # GCLL EF    <' ' ' '*    '  '  '  'F IcNND
 D
 D
 D
 D
 2 D
 D
 D
N> > > >2 2 2 2   * Q    &      r!   