
    a
ier                       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 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/          Z0 G d de1          Z2 G d de2          Z3 G d de2          Z4 G d de2          Z5 G d de2          Z6 G d de2          Z7 G d de2          Z8 G d de2          Z9 G d de2          Z: G d de2          Z;dd"Z< G d# d$e=          Z> G d% d&e>          Z?ddd*Z@dd,ZAdd0ZBdd4ZCdd7ZD ejE        d89          dd=            ZFdd?ZGdd@ZHddBZIddEZJddGZKddHZLddIZM ejE        d89          ddK            ZNddNZOddQZPddTZQe!dUdVdd[            ZRe!	 ddUdVdd\            ZR ejE        d]9          	 ddUdVdd^            ZR ejE        d89          ddd`            ZS G da dbejT                  ZU G dc ddejT                  ZV G de dfe*          ZW ejX                    ZYejZ        ddl            Z[ddnZ\dddodduZ]ejZ        	 	 dddx            Z^ejZ        	 	 dddz            Z_dd{Z` ed|          Za	 dddZbddZcddZdddZe e(d          Zf G d de          ZgddZhddZiddZjddZk ejE        d9          dd            ZldddZmddZndS )zGeneric utility functions.    )annotationsN)	GeneratorIterableIteratorMappingSequence)FutureThreadPoolExecutor)AnyCallableLiteralOptionalTypeVarUnioncastoverload)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__     C:\Users\Dell Inspiron 16\Desktop\tws\AgrotaPowerBi\back-agrota-powerbi\mcp-client-agrota\venv\Lib\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$   2   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&   6   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*   >   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,   B   s        ////r   r,   c                      e Zd ZdZdS )LangSmithConflictErrorzThe resource already exists.Nr   r   r   r    r.   r.   F           &&&&r   r.   c                      e Zd ZdZdS )LangSmithConnectionErrorz&Couldn't connect to the LangSmith API.Nr   r   r   r    r1   r1   J           0000r   r1   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__r6   )selfr6   r5   r8   	__class__s       r    r=   z LangSmithExceptionGroup.__init__Q   s,     	$)&)))$r   )r5   r   r6   r7   r8   r   r9   r:   )r   r   r   r   r=   __classcell__r?   s   @r    r4   r4   N   sC        //% % % % % % % % % %r   r4   
identifierstrr9   c                    d|  dS )a%  Get the error message for an invalid prompt identifier.

    Used consistently across the codebase when parsing prompt identifiers fails.

    Args:
        identifier: The invalid identifier that was provided.

    Returns:
        A formatted error message explaining the valid formats.
    z#Invalid prompt identifier format: "z". Expected one of:
  - "prompt-name" (for private prompts)
  - "owner/prompt-name" (for prompts with explicit owner)
  - "prompt-name:commit-hash" (with commit reference)
  - "owner/prompt-name:commit-hash" (with owner and commit)r   )rB   s    r    !get_invalid_prompt_identifier_msgrE   Y   s!    	Gj 	G 	G 	Gr   c                      e Zd ZdZdS )LangSmithWarningzBase class for warnings.Nr   r   r   r    rG   rG   q   s        """"r   rG   c                      e Zd ZdZdS )LangSmithMissingAPIKeyWarningzWarning for missing API key.Nr   r   r   r    rI   rI   u   r/   r   rI   ctxOptional[dict]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_helpersrN   rO   _GLOBAL_TRACING_ENABLEDget_env_var)rJ   rY   rN   rO   tc
var_results         r    tracing_is_enabledr_   y   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_TRACKINGrS   rT   falser\   r   r   r    test_tracking_is_disabledre      s    333w>>r   
arg_groupstuple[str, ...]r   c                      d fd}|S )z7Validate specified keyword args are mutually exclusive.funcr   r9   c                L     t          j                   d fd            }|S )Nr5   r   r8   r9   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argr8   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)rp   	arg_groupr8   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 rn   r   )rp   icounts      r    ru   z@xor_args.<locals>.decorator.<locals>.wrapper.<locals>.<listcomp>   s!    PPPHAuUaZZaZZZr   c                F    g | ]}d                      |                   S ), )join)rp   rx   rf   s     r    ru   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: r{   )	enumerate
ValueErrorr|   )r5   r8   countsinvalid_groupsinvalid_group_namesrf   ri   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   )r5   r   r8   r   r9   r   )	functoolswraps)ri   r   rf   s   ` r    	decoratorzxor_args.<locals>.decorator   sC    				) 	) 	) 	) 	) 	) 
		)  r   )ri   r   r9   r   r   )rf   r   s   ` r    xor_argsr      s)         ( r   response(Union[requests.Response, httpx.Response]r:   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	HTTPErrorrC   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]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   rn   )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.MessagerS   type&Unexpected format for stored message: z Message does not have a type.)r~   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   r8   r   z Message does not have kwargs.datar   z Message does not have data.)r~   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          )a  Extract messages from the given inputs dictionary.

    Args:
        inputs: The inputs dictionary.

    Returns:
        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   )rp   r   s     r    ru   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   r~   )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: The outputs dictionary.

    Returns:
        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   rn   z3Chat examples expect exactly one generation. Found z generations: r   r   z"Unexpected format for generation: z%. Generation does not have a message.)r~   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: The inputs dictionary.

    Returns:
        str: The prompt.

    Raises:
        ValueError: If the prompt is not found or if multiple prompts are present.
    promptpromptsrn   r   z$Multiple prompts in run with inputs z!. Please create example manually.z)Could not find prompt in run with inputs r   )r   r~   )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   rn   zMultiple generations in run: r   r   zNo text in generation: )r~   r   r   s      r    get_llm_generation_from_outputsr   C  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FileNotFoundErrorr~   r   r   r    get_docker_compose_commandr   P  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   k  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: The object to check.

    Returns:
        bool: True if the object is similar to `BaseMessage`, `False` otherwise.
    r   Nr   r   )allr   getattrrC   r   hasattr)r   s    r    is_base_message_liker   w  st     wsIt44c::ws$7>>EEC  JZV0D0Dc%J%J	
  r   r   Optional[str]c                B    | dS t          t          |                     S )z2Check if the given environment variable is truish.NF)	is_truishr\   )r   s    r    is_env_var_truishr     s"    }u[''(((r   )	LANGSMITH	LANGCHAIN)
namespacesnamerU   r   tuplec                   d S Nr   r   rU   r   s      r    r\   r\     s	     #r   c                   d S r   r   r   s      r    r\   r\     s	     Cr   d   c                     fd|D             }|D ]? t           j                                       }||                                dk    r|c S @|S )a  Retrieve an environment variable from a list of namespaces.

    Args:
        name: The name of the environment variable.
        default: The default value to return if the environment variable is not found.
        namespaces: A tuple of namespaces to search for the environment variable.

            Defaults to `('LANGSMITH', 'LANGCHAINs')`.

    Returns:
        The value of the environment variable if found, otherwise the default value.
    c                    g | ]	}| d  
S )_r   )rp   	namespacer   s     r    ru   zget_env_var.<locals>.<listcomp>  s'    ???y	""D""???r   NrS   )osenvironro   strip)r   rU   r   namesr   s   `    r    r\   r\     sh    & @???J???E  
t$$"!4!4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SESSIONrU   NrT   )r   r   ro   r\   )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 )FilterPoolFullWarningzGFilter `urllib3` warnings logged when the connection pool isn't reused.rS   r   rC   hostr9   r:   c                X    t                                          |           || _        dS )zInitialize the `FilterPoolFullWarning` filter.

        Args:
            name: The name of the filter. Defaults to `""`.
            host: 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   )rS   rS   )r   rC   r  rC   r9   r:   r9   r`   )r   r   r   r   r=   r  r@   rA   s   @r    r  r    s\        QQ      % % % % % % % %r   r  c                      e Zd ZdZddZdS )FilterLangSmithRetryz!Filter for retries from this lib.r9   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    r2   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: The cache path.

    Returns:
        The cache path if provided, otherwise the value from the `LANGSMITH_TEST_CACHE`
        environment variable.
    N
TEST_CACHErT   rd   )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 )zAFilter request headers based on `ignore_hosts` and `allow_hosts`.c              3  L   K   | ]}j                             |          V  d S r   )url
startswith)rp   r  r   s     r    rr   z)filter_request_headers.<locals>.<genexpr>(  s3      RRTGK22488RRRRRRr   NrS   c              3     K   | ]Q}|                     d           rj                             |          n|k    p                    d|           V  RdS ))zhttp://zhttps://r   N)r.  r-  endswith)rp   r  r   request_hosts     r    rr   z)filter_request_headers.<locals>.<genexpr>3  s       	
 	
  ??#:;;O&&t,,,!T)N\-B-B:t::-N-N	
 	
 	
 	
 	
 	
r   )anyurllib_parseurlparser-  	Exceptionhostnameheaders)r   r(  r)  
parsed_urlhost_matchesr1  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methodr;  bodyauthorizationz
Set-Cookiec                (    t          |           S )Nr'  )r:  )r   r)  r(  s    r    <lambda>zwith_cache.<locals>.<lambda>e  s    .D,K/
 /
 /
 r   )
serializercassette_library_dirrecord_modematch_onfilter_headersbefore_record_request)vcrImportErrorlangsmith._internalr?  patch_urllib3r   r;  splitVCRr0  use_cassette)r;  r(  r)  rO  rR  	cache_dir
cache_filels_vcrs    ``     r    
with_cacherY  D  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 )r>  N)rY  )r;  r(  r)  s      r    with_optional_cacher\  m  s       lK88 	 	EEE	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   (,,c                     t          j        t          j                     } d | D             }d                    |          S )Nc                    g | ]}d |v|	S )z
langsmith/r   )rp   lines     r    ru   z_format_exc.<locals>.<listcomp>~  s"    LLLt<t3K3Kd3K3K3Kr   rS   )	tracebackformat_exceptionsysexc_infor|   )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 rw   _middle_copy)rp   kvrm  rl  rj  s      r    
<dictcomp>z _middle_copy.<locals>.<dictcomp>  sZ     
 
 
 1 D)VaZ88,4FQJ; ;
 
 
r   c           	     :    g | ]}t          |d z             S rw   rq  rp   itemrm  rl  rj  s     r    ru   z _middle_copy.<locals>.<listcomp>  +    PPPDT4FQJ??PPPr   c              3  B   K   | ]}t          |d z             V  dS )rn   Nrq  rw  s     r    rr   z_middle_copy.<locals>.<genexpr>  s5      UU\$i!DDUUUUUUr   c           	     :    h | ]}t          |d z             S rw   rq  rw  s     r    	<setcomp>z_middle_copy.<locals>.<setcomp>  ry  r   )	r   r   r   r   r   itemslistr   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_copyr    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   tuple[str, str, str]c                   | rC|                      d          dk    s*|                     d          s|                     d          rt          t	          |                     |                     dd          }|d         }t          |          dk    r|d         nd}d|v r>|                    dd          \  }}|r|st          t	          |                     |||fS |st          t	          |                     d||fS )a3  Parse a string in the format of `owner/name:hash`, `name:hash`, `owner/name`, or `name`.

    Args:
        identifier: The prompt identifier to parse.

    Returns:
        A tuple containing `(owner, name, hash)`.

    Raises:
        ValueError: If the identifier doesn't match the expected formats.
    /rn   :r   latest-)ry   r.  r0  r~   rE   rS  r   )rB   parts
owner_namecommitownerr   s         r    parse_prompt_identifierr    s*    HC  1$$  %% %s## % ::FFGGGS!$$EqJUaU1XXXF
j &&sA..t 	LD 	L>zJJKKKdF"" 	L>zJJKKK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.ri   Callable[P, T]r5   P.argsr8   P.kwargsr9   	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  r   partialcontextvarscopy_contextrun)r>   ri   r5   r8   r?   s       r    r  z ContextThreadPoolExecutor.submit  ss      ww~~a !,..2D;?  CI  
 
 	
r   Nrn   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  )rp   r   s     r    ru   z1ContextThreadPoolExecutor.map.<locals>.<listcomp>!  s!    QQQ1K,..QQQr   r   r5   r   r9   rg  c                 D                                      j        g| R  S r   )popr  )r5   contextsr  s    r    _wrapped_fnz2ContextThreadPoolExecutor.map.<locals>._wrapped_fn#  s&    %8<<>>%b040000r   r  )r5   r   r9   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   )ri   r  r5   r  r8   r  r9   r  )
r  r  r  r  r  r  r  r   r9   r  )r   r   r   r   r  r  r@   rA   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.comrT   z!LangSmith API URL cannot be empty"'r  )r   rC   r\   r   r&   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_KEYrT   r  r  r\   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_IDrT   r  r  r  )r  workspace_id_s     r    get_workspace_idr  D  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)r3  urlsplitnetlocrS  socketgethostbynamer.  gaierror)r-  r  ips      r    _is_localhostr  P  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/apirn   r   )r;  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)r3  r4  r  rC   r;  r0  rsplit
urlunparse_replacer  r.  )r  r  r8  linknew_paths        r    get_host_urlr  e  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   rn   __call__r?   )callablerC   r   r   r   r   r  _get_function_nameri   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   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.
    rV   1)r   rC   r   r`   )ri  s    r    r   r     s>     #s 3yy{{f$2s
299r   )rB   rC   r9   rC   r   )rJ   rK   r9   rL   r  )rf   rg   r9   r   )r   r   r9   r:   )r   r   r9   rC   )r   r   r   rC   r9   r:   )r   r   r9   rC   )r   r   r9   r   )r   r   r9   r   )r   r   r9   r   )r   r   r9   r   )r   r   r9   rC   )r   r   r9   rC   )r9   r   )r   r   r9   r   )r   r   r9   r`   )r   r   r9   r`   )r   rC   rU   rC   r   r   r9   rC   )r   rC   rU   r:   r   r   r9   r   )r   rC   rU   r   r   r   r9   r   )T)r9   r   )r  r  r  r  r9   r  )r#  r   r9   r   )r   r   r(  r*  r)  r*  r9   r   )NN)r;  r<  r(  r*  r)  r*  r9   r  )r;  rZ  r(  r*  r)  r*  r9   r  )r9   rC   )rh  r   )
ri  rg  rj  rk  rl  r   rm  r   r9   rg  )ri  rg  r9   rg  )r  rC   r  rC   r9   r`   )rB   rC   r9   r  )r  r   r9   rC   )r  r   r9   r   )r  r   r9   r   )r-  rC   r9   r`   )r  r   r  rC   )r   )r  r   r  r   r9   rC   )ri  r   r9   r`   )or   
__future__r   
contextlibr  r  r   r   loggingr   pathlibr  r   rb  	threadingr`  collections.abcr   r   r   r   r   concurrent.futuresr	   r
   typingr   r   r   r   r   r   r   r   urllibr   r3  r   r   typing_extensionsr   urllib3.utilr   	langsmithr   
ls_schemas	getLoggerr   r   r5  r   r"   r$   r&   r(   r*   r,   r.   r1   r4   rE   UserWarningrG   rI   r_   re   r   r   r   	lru_cacher   r   r   r   r   r   r   r   r   r   r   r   r\   r  Filterr  r  r  RLockr  contextmanagerr"  r&  r:  rY  r\  rf  rg  rr  r  r  r  r  r  r  r  r  r  r  r  r   r   r   r    <module>r     s8	       " " " " " "                				       



         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 % % %   0# # # # #{ # # #' ' ' ' '$4 ' ' '         0? ? ? ?
   4        Q        
   &   &8 8 8 8P P P P&9 9 9 9:L L L L2
$ 
$ 
$ 
$ Q    4	 	 	 	   $) ) ) ) 

 3	     
 
  3	     
 S!!! " 3	     "!4 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   