a
    ”˜ëjo  ã                   @  sò  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 -e.¡Z/G dd„ de0ƒZ1G dd„ de1ƒZ2G dd„ de1ƒZ3G dd„ de1ƒZ4G dd„ de1ƒZ5G dd„ de1ƒZ6G dd„ de1ƒZ7G dd„ de1ƒZ8G dd„ de1ƒZ9G dd„ de1ƒZ:G dd „ d e;ƒZ<G d!d"„ d"e<ƒZ=d´d#d$d%œd&d'„Z>d(d)œd*d+„Z?d,d-d.œd/d0„Z@d1d2d3œd4d5„ZAd6d7d8œd9d:„ZBejCd;d<�d=d7d2d>œd?d@„ƒZDdAd7dBœdCdD„ZEdAdAdBœdEdF„ZFdAdGdBœdHdI„ZGdAdJdKœdLdM„ZHdAdGdNœdOdP„ZIdAd7dKœdQdR„ZJdAd7dNœdSdT„ZKejCd;d<�dUd)œdVdW„ƒZLdXdYdBœdZd[„ZMd\d(d]œd^d_„ZNd`d(daœdbdc„ZOejCddd<�dµdedfœd7d`dgd`dhœdidj„ƒZPejCd;d<�d¶d`d)œdldm„ƒZQG dndo„ doejRƒZSG dpdq„ dqejRƒZTG drds„ dse)ƒZUe V¡ ZWejXdtdudvdwœdxdy„ƒZYd`d`dzœd{d|„ZZddd}œd~ddd~d€œd�d‚„Z[ejXd·dƒdddvd„œd…d†„ƒZ\ejXd¸d‡dddvd„œdˆd‰„ƒZ]d7d)œdŠd‹„Z^edŒƒZ_d¹dŒdŽd=d=dŒd�œd�d‘„Z`dŒdŒd’œd“d”„Zad7d7d(d•œd–d—„Zbd7d˜d™œdšd›„Zce'dœƒZdG d�dž„ džeƒZed`d7dŸœd d¡„Zfd`d`d¢œd£d¤„Zgd`d`d¥œd¦d§„Zhd7d(d¨œd©dª„ZiejCd«d<�d`d7d¬œd­d®„ƒZjdºd-d=d7d¯œd°d±„Zkd~d(d’œd²d³„ZldS )»zGeneric utility functions.é    )ÚannotationsN)Ú	GeneratorÚIterableÚIteratorÚMappingÚSequence)ÚFutureÚThreadPoolExecutor)ÚAnyÚCallableÚLiteralÚOptionalÚTypeVarÚUnionÚcast)Úparse)Ú	ParamSpec)ÚRetry)Úschemasc                   @  s   e Zd ZdZdS )ÚLangSmithErrorz=An error occurred while communicating with the LangSmith API.N©Ú__name__Ú
__module__Ú__qualname__Ú__doc__© r   r   úN/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langsmith/utils.pyr   )   s   r   c                   @  s   e Zd ZdZdS )ÚLangSmithAPIErrorz9Internal server error while communicating with LangSmith.Nr   r   r   r   r   r   -   s   r   c                   @  s   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   r   c                   @  s   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   r   c                   @  s   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   r    c                   @  s   e Zd ZdZdS )ÚLangSmithAuthErrorz-Couldn't authenticate with the LangSmith API.Nr   r   r   r   r   r!   =   s   r!   c                   @  s   e Zd ZdZdS )ÚLangSmithNotFoundErrorz%Couldn't find the requested resource.Nr   r   r   r   r   r"   A   s   r"   c                   @  s   e Zd ZdZdS )ÚLangSmithConflictErrorzThe resource already exists.Nr   r   r   r   r   r#   E   s   r#   c                   @  s   e Zd ZdZdS )ÚLangSmithConnectionErrorz&Couldn't connect to the LangSmith API.Nr   r   r   r   r   r$   I   s   r$   c                      s,   e Zd ZdZdddddœ‡ fdd„Z‡  ZS )ÚLangSmithExceptionGroupz%Port of ExceptionGroup for Py < 3.11.r
   zSequence[Exception]ÚNone)ÚargsÚ
exceptionsÚkwargsÚreturnc                  s   t ƒ j|i |¤Ž || _dS )zInitialize.N)ÚsuperÚ__init__r(   )Úselfr(   r'   r)   ©Ú	__class__r   r   r,   P   s    z LangSmithExceptionGroup.__init__)r   r   r   r   r,   Ú__classcell__r   r   r.   r   r%   M   s   r%   c                   @  s   e Zd ZdZdS )ÚLangSmithWarningzBase class for warnings.Nr   r   r   r   r   r1   [   s   r1   c                   @  s   e Zd ZdZdS )ÚLangSmithMissingAPIKeyWarningzWarning for missing API key.Nr   r   r   r   r   r2   _   s   r2   zOptional[dict]zUnion[bool, Literal['local']])Úctxr*   c                 C  sv   ddl m  m} ddlm}m} | p*|ƒ }|d dur@|d S |ƒ rJdS |jdurZ|jS tdtddd	�d	�}|d
kS )z"Return True if tracing is enabled.r   N)Úget_current_run_treeÚget_tracing_contextZenabledTZ
TRACING_V2ZTRACINGÚ ©ÚdefaultÚtrue)Zlangsmith._internal._contextÚ	_internalÚ_contextZlangsmith.run_helpersr4   r5   Z_GLOBAL_TRACING_ENABLEDÚget_env_var)r3   r;   r4   r5   ZtcZ
var_resultr   r   r   Útracing_is_enabledc   s    

r=   Úbool©r*   c                   C  s   t ddd�dkS )z"Return True if testing is enabled.ZTEST_TRACKINGr6   r7   Úfalse©r<   r   r   r   r   Útest_tracking_is_disabled{   s    rB   ztuple[str, ...]r   )Ú
arg_groupsr*   c                    s   dddœ‡ fdd„}|S )z7Validate specified keyword args are mutually exclusive.r   )Úfuncr*   c                   s&   t  ˆ ¡ddddœ‡‡ fdd„ƒ}|S )Nr
   )r'   r)   r*   c                    s\   ‡ fdd„ˆD ƒ}dd„ t |ƒD ƒ}|rN‡fdd„|D ƒ}tdd |¡› �ƒ‚ˆ| i ˆ ¤ŽS )z3Validate exactly one arg in each group is not None.c                   s"   g | ]}t ‡ fd d„|D ƒƒ‘qS )c                 3  s    | ]}ˆ   |¡d urdV  qd S )Né   )Úget)Ú.0Úarg©r)   r   r   Ú	<genexpr>ˆ   ó    zJxor_args.<locals>.decorator.<locals>.wrapper.<locals>.<listcomp>.<genexpr>)Úsum)rG   Z	arg_grouprI   r   r   Ú
<listcomp>‡   s   ÿz@xor_args.<locals>.decorator.<locals>.wrapper.<locals>.<listcomp>c                 S  s   g | ]\}}|d kr|‘qS ©rE   r   )rG   ÚiÚcountr   r   r   rM   ‹   rK   c                   s   g | ]}d   ˆ | ¡‘qS )ú, )Újoin)rG   rO   ©rC   r   r   rM   �   rK   zFExactly one argument in each of the following groups must be defined: rQ   )Ú	enumerateÚ
ValueErrorrR   )r'   r)   ÚcountsZinvalid_groupsZinvalid_group_names)rC   rD   rI   r   Úwrapper„   s    
þþÿz,xor_args.<locals>.decorator.<locals>.wrapper)Ú	functoolsÚwraps)rD   rW   rS   )rD   r   Ú	decoratorƒ   s    zxor_args.<locals>.decoratorr   )rC   rZ   r   rS   r   Úxor_args€   s    r[   z(Union[requests.Response, httpx.Response]r&   )Úresponser*   c              
   C  s”   z|   ¡  W n‚ tjyF } z t t|ƒ| j¡|‚W Y d}~nRd}~0  tjyŽ } z0tjt|ƒ› d| j› �| j| d�|‚W Y d}~n
d}~0 0 dS )z&Raise an error with the response text.Nz: )Úrequestr\   )Úraise_for_statusÚrequestsÚ	HTTPErrorÚstrÚtextÚhttpxZHTTPStatusErrorr]   )r\   Úer   r   r   Úraise_for_status_with_textš   s    (ýüre   zUnion[enum.Enum, str]ra   )Úenur*   c                 C  s   t | tjƒr| jS | S )zGet the value of a string enum.)Ú
isinstanceÚenumÚEnumÚvalue)rf   r   r   r   Úget_enum_valueª   s    rk   rE   )ÚmaxsizeÚint)ÚlevelÚmessager*   c                 C  s   t  | |¡ dS )z4Log a message at the specified level, but only once.N)Ú_LOGGERÚlog)rn   ro   r   r   r   Úlog_once±   s    rr   zMapping[str, Any])ro   r*   c                 C  sh   | st dƒ‚d| v rDd| vr,t d| › d�ƒ‚| d d  dd¡ ¡ S d	| vr\t d
| › d�ƒ‚| d	 S d S )NúMessage is empty.ÚlcÚidú*Unexpected format for serialized message: z Message does not have an id.éÿÿÿÿÚMessager6   Útypeú&Unexpected format for stored message: z Message does not have a type.)rU   ÚreplaceÚlower©ro   r   r   r   Ú_get_message_type·   s    
ÿ
ÿr~   c                 C  sX   | st dƒ‚d| v r4d| vr,t d| › d�ƒ‚| d S d| vrLt d| › d�ƒ‚| d S d S )	Nrs   rt   r)   rv   z Message does not have kwargs.Údatarz   z Message does not have data.)rU   r}   r   r   r   Ú_get_message_fieldsÊ   s    
ÿ
ÿr€   zdict[str, Any]c                 C  s   t | ƒ}t| ƒ}||dœS )z&Extract message from a message object.©ry   r   )r~   r€   )ro   Zmessage_typeZmessage_datar   r   r   Ú_convert_messageÝ   s    r‚   zlist[dict[str, Any]])Úinputsr*   c                 C  sD   d| v rdd„ | d D ƒS d| v r0t | d ƒgS td| › d�ƒ‚dS )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                 S  s   g | ]}t |ƒ‘qS r   )r‚   )rG   ro   r   r   r   rM   ò   rK   z,get_messages_from_inputs.<locals>.<listcomp>ro   z-Could not find message(s) in run with inputs Ú.N)r‚   rU   )rƒ   r   r   r   Úget_messages_from_inputsä   s
    r†   )Úoutputsr*   c                 C  sr   d| vrt d| › d�ƒ‚| d }t|ƒdkrFt dt|ƒ› d|› d�ƒ‚|d }d|vrft 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…   rE   z3Chat examples expect exactly one generation. Found z generations: r   ro   z"Unexpected format for generation: z%. Generation does not have a message.)rU   Úlenr‚   ©r‡   rˆ   Zfirst_generationr   r   r   Ú#get_message_generation_from_outputsø   s"    ÿÿÿ
ÿrŒ   c                 C  sX   d| v r| d S d| v rD| d }t |ƒdkr4|d S td| › d�ƒ‚td| › d�ƒ‚d	S )
züRetrieve 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ÚpromptsrE   r   z$Multiple prompts in run with inputs z!. Please create example manually.z)Could not find prompt in run with inputs r…   N)rŠ   rU   )rƒ   rŽ   r   r   r   Úget_prompt_from_inputs  s    
ÿr�   c                 C  s`   d| vrt d| › d�ƒ‚| d }t|ƒdkr:t d|› �ƒ‚|d }d|vrXt d|› �ƒ‚|d S )	z(Get the LLM generation from the outputs.rˆ   r‰   r…   rE   zMultiple generations in run: r   rb   zNo text in generation: )rU   rŠ   r‹   r   r   r   Úget_llm_generation_from_outputs.  s    r�   z	list[str]c                   C  s†   z"t jg d¢t jt jd� ddgW S  t jtfy€   z$t jddgt jt jd� dgW  Y S  t jtfyz   tdƒ‚Y n0 Y n0 dS )	z7Get the correct docker compose command for this system.)ÚdockerÚcomposeú	--version)ÚstdoutÚstderrr‘   r’   zdocker-composer“   zÆNeither '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/N)Ú
subprocessÚ
check_callÚDEVNULLÚCalledProcessErrorÚFileNotFoundErrorrU   r   r   r   r   Úget_docker_compose_command;  s&    ý
ýÿr›   zls_schemas.BaseMessageLikeÚdictc                 C  s<   | j d| jidœ}| jr8t| jƒdkr8i | j¥|d d< |S )z*Convert a LangChain message to an example.Úcontentr�   r   r   Úadditional_kwargs)ry   r�   rž   rŠ   )ro   Z	convertedr   r   r   Úconvert_langchain_messageV  s    þrŸ   Úobject)Úobjr*   c                 C  s@   t tt| ddƒtƒtt| ddƒtƒt| dƒo:tt| dƒtƒgƒS )zÊCheck 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ž   ry   )Úallrg   Úgetattrra   rœ   Úhasattr)r¡   r   r   r   Úis_base_message_likeb  s    	ýÿr¥   zOptional[str])rj   r*   c                 C  s   t t| ƒƒS )z2Check if the given environment variable is truish.)Ú	is_truishr<   )rj   r   r   r   Úis_env_var_truisht  s    r§   éd   )Z	LANGSMITHZ	LANGCHAIN)Ú
namespacesÚtuple)Únamer8   r©   r*   c                  s<   ‡ fdd„|D ƒ}|D ] ‰ t j ˆ ¡}|dur|  S q|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                   s   g | ]}|› d ˆ › �‘qS )Ú_r   )rG   Ú	namespace©r«   r   r   rM   �  rK   zget_env_var.<locals>.<listcomp>N)ÚosÚenvironrF   )r«   r8   r©   Únamesrj   r   r®   r   r<   y  s    
r<   Tc              	   C  s&   t j dtdtd| rdndd�d�¡S )z,Get the project name for a LangSmith tracer.ZHOSTED_LANGSERVE_PROJECT_NAMEZPROJECTZSESSIONr8   Nr7   )r¯   r°   rF   r<   )Zreturn_default_valuer   r   r   Úget_tracer_project•  s    ÿüúr²   c                      s:   e Zd ZdZdddddœ‡ fdd„Zdd	œd
d„Z‡  ZS )ÚFilterPoolFullWarningzFFilter urrllib3 warnings logged when the connection pool isn't reused.r6   ra   r&   )r«   Úhostr*   c                   s   t ƒ  |¡ || _dS )zÔInitialize 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.   r   r   r,   ¬  s    zFilterPoolFullWarning.__init__r>   r?   c                 C  s   |  ¡ }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Úmsgr   r   r   Úfilter¶  s    zFilterPoolFullWarning.filter)r6   r6   )r   r   r   r   r,   rº   r0   r   r   r.   r   r³   ©  s   
r³   c                   @  s   e Zd ZdZddœdd„ZdS )ÚFilterLangSmithRetryz!Filter for retries from this lib.r>   r?   c                 C  s   |  ¡ }d|vS )z!Filter retries from this library.ÚLangSmithRetry)r¶   r·   r   r   r   rº   Á  s    zFilterLangSmithRetry.filterN)r   r   r   r   rº   r   r   r   r   r»   ¾  s   r»   c                   @  s   e Zd ZdZdS )r¼   z&Wrapper to filter logs with this name.Nr   r   r   r   r   r¼   È  s   r¼   zlogging.LoggerzSequence[logging.Filter]zGenerator[None, None, None])ÚloggerÚfiltersr*   c                 c  sþ   t �$ |D ]}|  |¡ q
W d  ƒ n1 s.0    Y  zddV  W t �F |D ]0}z|  |¡ W qL tyz   t d¡ Y qL0 qLW d  ƒ qú1 s’0    Y  n\t �F |D ]0}z|  |¡ W q¨ tyÖ   t d¡ Y q¨0 q¨W d  ƒ n1 sî0    Y  0 dS )zåTemporarily 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ÚBaseExceptionrp   Úwarning)r½   r¾   rº   r   r   r   Úfilter_logsÏ  s"    *2ûrÄ   )Úcacher*   c                 C  s   | dur| S t ddd�S )zðGet 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.
    NZ
TEST_CACHEr7   rA   )rÅ   r   r   r   Úget_cache_diré  s    
rÆ   ©Úignore_hostsÚallow_hostsr
   zOptional[Sequence[str]])r]   rÈ   rÉ   r*   c                  s|   |rt ‡ fdd„|D ƒƒrdS |rrzt ˆ j¡}W n tyF   Y dS 0 |jpPd‰t ‡ ‡fdd„|D ƒƒ}|srdS i ˆ _ˆ S )z=Filter request headers based on ignore_hosts and allow_hosts.c                 3  s   | ]}ˆ j  |¡V  qd S ©N)ÚurlÚ
startswith©rG   r´   ©r]   r   r   rJ      rK   z)filter_request_headers.<locals>.<genexpr>Nr6   c                 3  s<   | ]4}|  d ¡rˆ j  |¡nˆ|kp2ˆ d|› �¡V  qdS ))zhttp://zhttps://r…   N)rÌ   rË   ÚendswithrÍ   ©r]   Úrequest_hostr   r   rJ     s   ýÿ)ÚanyÚurllib_parseÚurlparserË   Ú	ExceptionÚhostnameÚheaders)r]   rÈ   rÉ   Ú
parsed_urlZhost_matchesr   rÐ   r   Úfilter_request_headersø  s    
ø
rÙ   zUnion[str, pathlib.Path])ÚpathrÈ   rÉ   r*   c              	   #  sÀ   zddl }W n ty&   tdƒ‚Y n0 ddlm} | ¡  tj | ¡\}}|j| 	d¡sd| 	d¡rhdnd|d	g d
¢ddg‡ ‡fdd„d�}| 
|¡� dV  W d  ƒ n1 s²0    Y  dS )úUse a cache for requests.r   NzNvcrpy is required to use caching. Install with:pip install -U "langsmith[vcr]")Ú_patchz.yamlz.ymlZyamlÚjsonZnew_episodes)ÚuriÚmethodrÚ   ÚbodyÚauthorizationz
Set-Cookiec                   s   t | ˆˆ d�S )NrÇ   )rÙ   rÎ   ©rÉ   rÈ   r   r   Ú<lambda>=  s   ÿzwith_cache.<locals>.<lambda>)Ú
serializerZcassette_library_dirZrecord_modeZmatch_onZfilter_headersZbefore_record_request)ÚvcrÚImportErrorZlangsmith._internalrÜ   Úpatch_urllib3r¯   rÚ   ÚsplitZVCRrÏ   Zuse_cassette)rÚ   rÈ   rÉ   rå   rç   Ú	cache_dirZ
cache_fileZls_vcrr   râ   r   Ú
with_cache  s.    ÿ
ÿÿôrê   z"Optional[Union[str, pathlib.Path]]c                 c  sF   | dur<t | ||ƒ� dV  W d  ƒ qB1 s00    Y  ndV  dS )rÛ   N)rê   )rÚ   rÈ   rÉ   r   r   r   Úwith_optional_cacheE  s    &rë   c                  C  s&   t jt ¡ Ž } dd„ | D ƒ}d |¡S )Nc                 S  s   g | ]}d |vr|‘qS )z
langsmith/r   )rG   Úliner   r   r   rM   V  rK   z_format_exc.<locals>.<listcomp>r6   )Ú	tracebackÚformat_exceptionÚsysÚexc_inforR   )Ztb_linesZfiltered_linesr   r   r   Ú_format_excS  s    rñ   ÚTé   zdict[int, Any])ÚvalÚmemoÚ	max_depthÚ_depthr*   c                   sÒ   t | ƒ}t|dd ƒ}|d ur:z
|ˆƒW S  ty8   Y n0 ˆ ˆkrF| S t| tƒrj‡ ‡‡fdd„|  ¡ D ƒS t| tƒrŠ‡ ‡‡fdd„| D ƒS t| tƒr®t‡ ‡‡fdd„| D ƒƒS t| tƒrÎ‡ ‡‡fdd	„| D ƒS | S )
NÚ__deepcopy__c              	     s2   i | ]*\}}t |ˆˆˆ d  ƒt |ˆˆˆ d  ƒ“qS rN   ©Ú_middle_copy)rG   ÚkÚv©r÷   rö   rõ   r   r   Ú
<dictcomp>k  s   ýÿz _middle_copy.<locals>.<dictcomp>c                   s   g | ]}t |ˆˆˆ d  ƒ‘qS rN   rù   ©rG   Úitemrý   r   r   rM   r  rK   z _middle_copy.<locals>.<listcomp>c                 3  s    | ]}t |ˆˆˆ d  ƒV  qdS )rE   Nrù   rÿ   rý   r   r   rJ   t  rK   z_middle_copy.<locals>.<genexpr>c                   s   h | ]}t |ˆˆˆ d  ƒ’qS rN   rù   rÿ   rý   r   r   Ú	<setcomp>v  rK   z_middle_copy.<locals>.<setcomp>)	ry   r£   rÂ   rg   rœ   ÚitemsÚlistrª   Úset)rô   rõ   rö   r÷   ÚclsÚcopierr   rý   r   rú   ]  s(    

ü


rú   )rô   r*   c              
   C  sV   i }zt  | |¡W S  tyP } z&t dt|ƒ¡ t| |ƒW  Y d}~S d}~0 0 dS )z¢Deep 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Â   rp   ÚdebugÚreprrú   )rô   rõ   rd   r   r   r   Údeepish_copy{  s    	r  )Úcurrent_versionÚtarget_versionr*   c                 C  s(   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Útargetr   r   r   Úis_version_greater_or_equal�  s    

r  ztuple[str, str, str])Ú
identifierr*   c                 C  s¸   | r&|   d¡dks&|  d¡s&|  d¡r4td| › �ƒ‚|  dd¡}|d }t|ƒdkr\|d nd}d|v r˜| dd¡\}}|r€|sŽtd| › �ƒ‚|||fS |sªtd| › �ƒ‚d||fS d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.
    ú/rE   zInvalid identifier format: ú:r   Zlatestú-N)rP   rÌ   rÏ   rU   rè   rŠ   )r  ÚpartsZ
owner_nameÚcommitÚownerr«   r   r   r   Úparse_prompt_identifier™  s(    ÿþýü
r  ÚPc                      sN   e Zd ZdZdddddœ‡ fdd„Zd	d
dœddddddœ‡ fdd„Z‡  ZS )ÚContextThreadPoolExecutorz?ThreadPoolExecutor that copies the context to the child thread.zCallable[P, T]zP.argszP.kwargsz	Future[T])rD   r'   r)   r*   c                   s6   t ƒ  ttdtf tjt ¡ 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ò   rX   ÚpartialÚcontextvarsÚcopy_contextÚrun)r-   rD   r'   r)   r.   r   r   r  Â  s    

ÿÿÿþÿz ContextThreadPoolExecutor.submitNrE   ©ÚtimeoutÚ	chunksizezCallable[..., T]zIterable[Any]zOptional[float]rm   zIterator[T])ÚfnÚ	iterablesr#  r$  r*   c                  sL   dd„ t t|d ƒƒD ƒ‰ dddœ‡ ‡fd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                 S  s   g | ]}t  ¡ ‘qS r   )r  r   )rG   r¬   r   r   r   rM   ù  rK   z1ContextThreadPoolExecutor.map.<locals>.<listcomp>r   r
   rò   )r'   r*   c                    s   ˆ   ¡ jˆg| ¢R Ž S rÊ   )Úpopr!  )r'   ©Zcontextsr%  r   r   Ú_wrapped_fnû  s    z2ContextThreadPoolExecutor.map.<locals>._wrapped_fnr"  )ÚrangerŠ   r+   Úmap)r-   r%  r#  r$  r&  r)  r.   r(  r   r+  Û  s    ÿþüzContextThreadPoolExecutor.map)r   r   r   r   r  r+  r0   r   r   r.   r   r  ¿  s
   ûr  )Úapi_urlr*   c                 C  s@   | pt ttddd�ƒ}| ¡ s&tdƒ‚| ¡  d¡ d¡ d¡S )zBGet the LangSmith API URL from the environment or the given value.ZENDPOINTzhttps://api.smith.langchain.comr7   z!LangSmith API URL cannot be emptyú"ú'r  )r   ra   r<   Ústripr   Úrstrip)r,  Z_api_urlr   r   r   Úget_api_url  s    þþr1  )Úapi_keyr*   c                 C  s@   | dur| n
t ddd�}|du s(| ¡ s,dS | ¡  d¡ d¡S )z8Get the API key from the environment or the given value.NZAPI_KEYr7   r-  r.  ©r<   r/  )r2  Zapi_key_r   r   r   Úget_api_key  s    r4  )Úworkspace_idr*   c                 C  s@   | dur| n
t ddd�}|du s(| ¡ s,dS | ¡  d¡ d¡S )zGet workspace ID.NZWORKSPACE_IDr7   r-  r.  r3  )r5  Zworkspace_id_r   r   r   Úget_workspace_id  s    ÿ
ýr6  )rË   r*   c                 C  sZ   z>t  | ¡j d¡d }t |¡}|dkp<| d¡p<| d¡W S  tjyT   Y dS 0 dS )zÄCheck 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::FN)rÓ   ÚurlsplitÚnetlocrè   ÚsocketÚgethostbynamerÌ   Úgaierror)rË   r8  Úipr   r   r   Ú_is_localhost(  s    
r=  é   )Úweb_urlr,  c                 C  sÞ   | r| S t  |¡}t|ƒr d}nºt|jƒ d¡rZt|jƒ dd¡d }t  |j|d�¡}n€t|jƒ d¡r”t|jƒ dd¡d }t  |j|d�¡}nFt|j	ƒ 
d¡rªd}n0t|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/apirE   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)rÓ   rÔ   r=  ra   rÚ   rÏ   ÚrsplitÚ
urlunparseÚ_replacer8  rÌ   )r?  r,  rØ   ÚlinkÚnew_pathr   r   r   Úget_host_url=  s&    
rE  )r%  Údepthr*   c                 C  s„   |dkst | ƒst| ƒS t| dƒr(| jS t| tjƒrDt| j|d ƒS t| dƒr|t| dƒrlt| j	dƒrl| j	jS t| j
|d ƒS t| ƒS )Nr>  r   rE   Ú__call__r/   )Úcallablera   r¤   r   rg   rX   r  Ú_get_function_namerD   r/   rG  )r%  rF  r   r   r   rI  V  s    

rI  c                 C  s&   t | tƒr|  ¡ dkp| dkS t| ƒS )zžCheck if the value is truish.

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

    Returns:
        bool: True if the value is truish, False otherwise.
    r9   Ú1)rg   ra   r|   r>   )rô   r   r   r   r¦   h  s    	
r¦   )N)N)T)NN)NN)ró   r   )r   )mr   Ú
__future__r   Ú
contextlibr  r  rh   rX   Úloggingr¯   Úpathlibr9  r–   rï   Ú	threadingrí   Úcollections.abcr   r   r   r   r   Úconcurrent.futuresr   r	   Útypingr
   r   r   r   r   r   r   Úurllibr   rÓ   rc   r_   Ztyping_extensionsr   Zurllib3.utilr   Z	langsmithr   Z
ls_schemasÚ	getLoggerr   rp   rÕ   r   r   r   r   r    r!   r"   r#   r$   r%   ÚUserWarningr1   r2   r=   rB   r[   re   rk   Ú	lru_cacherr   r~   r€   r‚   r†   rŒ   r�   r�   r›   rŸ   r¥   r§   r<   r²   ÚFilterr³   r»   r¼   ÚRLockr¿   ÚcontextmanagerrÄ   rÆ   rÙ   rê   rë   rñ   rò   rú   r  r  r  r  r  r1  r4  r6  r=  rE  rI  r¦   r   r   r   r   Ú<module>   sÂ   $	



 þü

ü$  ý(  ý ÿ	#G
