HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //proc/1233/root/usr/local/lib/python3.10/dist-packages/langsmith/__pycache__/utils.cpython-310.pyc
o

���g;e�@s�dZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlmZmZddlmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"ddl#m$Z%ddl&Z&ddl'Z'ddl(m)Z)ddl*m+Z+dd	l,m-Z.e�/e0�Z1Gd
d�de2�Z3Gdd
�d
e3�Z4Gdd�de3�Z5Gdd�de3�Z6Gdd�de3�Z7Gdd�de3�Z8Gdd�de3�Z9Gdd�de3�Z:Gdd�de3�Z;Gdd�de<�Z=Gdd�de=�Z>d�d�d$d%�Z?d�d'd(�Z@d�d,d-�ZAd�d1d2�ZBd�d6d7�ZCejDd8d9�d�d=d>��ZEd�d@dA�ZFd�dBdC�ZGd�dEdF�ZHd�dIdJ�ZId�dLdM�ZJd�dNdO�ZKd�dPdQ�ZLejDd8d9�d�dSdT��ZMd�dWdX�ZNd�d[d\�ZOejDd]d9�	d�d^d_�d�dedf��ZPejDd8d9�d�d�dhdi��ZQGdjdk�dkejR�ZSGdldm�dmejR�ZTGdndo�doe+�ZUe�V�ZWejXd�dudv��ZYd�dxdy�ZZejX	d�d�d~d��Z[ejX	d�d�d�d���Z\d�d�d��Z]e d��Z^	d�d�d�d��Z_d�d�d��Z`d�d�d��Zad�d�d��Zbe)d��ZcGd�d��d�e�Zdd�d�d��Zed�d�d��Zfd�d�d��ZgejDd�d9�d�d�d���Zhd�d�d�d��Zid�d�d��ZjdS)�zGeneric utility functions.�)�annotationsN)�Future�ThreadPoolExecutor)�Any�Callable�Dict�	Generator�Iterable�Iterator�List�Literal�Mapping�Optional�Sequence�Tuple�TypeVar�Union�cast)�parse)�	ParamSpec)�Retry)�schemasc@�eZdZdZdS)�LangSmithErrorz=An error occurred while communicating with the LangSmith API.N��__name__�
__module__�__qualname__�__doc__�rr�:/usr/local/lib/python3.10/dist-packages/langsmith/utils.pyr0�rc@r)�LangSmithAPIErrorz9Internal server error while communicating with LangSmith.Nrrrrr r"4r!r"c@r)�LangSmithRequestTimeoutz*Client took too long to send request body.Nrrrrr r#8r!r#c@r)�LangSmithUserErrorzAUser error caused an exception when communicating with LangSmith.Nrrrrr r$<r!r$c@r)�LangSmithRateLimitErrorz7You have exceeded the rate limit for the LangSmith API.Nrrrrr r%@r!r%c@r)�LangSmithAuthErrorz-Couldn't authenticate with the LangSmith API.Nrrrrr r&Dr!r&c@r)�LangSmithNotFoundErrorz%Couldn't find the requested resource.Nrrrrr r'Hr!r'c@r)�LangSmithConflictErrorzThe resource already exists.Nrrrrr r(Lr!r(c@r)�LangSmithConnectionErrorz&Couldn't connect to the LangSmith API.Nrrrrr r)Pr!r)c@r)�LangSmithWarningzBase class for warnings.Nrrrrr r*Wr!r*c@r)�LangSmithMissingAPIKeyWarningzWarning for missing API key.Nrrrrr r+[r!r+�ctx�Optional[dict]�return�Union[bool, Literal['local']]cCsTddlm}m}|p|�}|ddur|dS|�rdStdtddd	�d	�}|d
kS)z"Return True if tracing is enabled.r)�get_current_run_tree�get_tracing_context�enabledNT�
TRACING_V2�TRACING���default�true)�langsmith.run_helpersr0r1�get_env_var)r,r0r1�tc�
var_resultrrr �tracing_is_enabled_s
r=�boolcCstddd�dkS)z"Return True if testing is enabled.�
TEST_TRACKINGr5r6�false�r:rrrr �test_tracking_is_disabledrsrB�
arg_groups�Tuple[str, ...]rcsd�fdd�}|S)z7Validate specified keyword args are mutually exclusive.�funcrr.cst���d��fdd��}|S)N�argsr�kwargsr.cs\�fdd��D�}dd�t|�D�}|r'�fdd�|D�}tdd�|������|i���S)z3Validate exactly one arg in each group is not None.cs"g|]
}t�fdd�|D���qS)c3s"�|]}��|�durdVqdS)N�)�get)�.0�arg�rGrr �	<genexpr>�� zJxor_args.<locals>.decorator.<locals>.wrapper.<locals>.<listcomp>.<genexpr>)�sum)rJ�	arg_grouprLrr �
<listcomp>~s��z@xor_args.<locals>.decorator.<locals>.wrapper.<locals>.<listcomp>cSsg|]
\}}|dkr|�qS�rHr)rJ�i�countrrr rQ�scsg|]	}d��|��qS)�, )�join)rJrS�rCrr rQ��zFExactly one argument in each of the following groups must be defined: rU)�	enumerate�
ValueErrorrV)rFrG�counts�invalid_groups�invalid_group_names)rCrErLr �wrapper{s
���z,xor_args.<locals>.decorator.<locals>.wrapper)rFrrGrr.r)�	functools�wraps)rEr^rW)rEr �	decoratorzszxor_args.<locals>.decoratorN)rErr.rr)rCrarrWr �xor_argswsrb�response�(Union[requests.Response, httpx.Response]�Nonec
Cs>z|��WdStjy}z
t�t|�|j�|�d}~ww)z&Raise an error with the response text.N)�raise_for_status�requests�	HTTPError�str�text)rc�errr �raise_for_status_with_text�s��rl�enu�Union[enum.Enum, str]ricCst|tj�r	|jS|S)zGet the value of a string enum.)�
isinstance�enum�Enum�value)rmrrr �get_enum_value�srsrH)�maxsize�level�int�messagecCst�||�dS)z4Log a message at the specified level, but only once.N)�_LOGGER�log)rurwrrr �log_once�srz�Mapping[str, Any]cCsd|std��d|vr"d|vrtd|�d���|dd�dd���Sd	|vr.td
|�d���|d	S)N�Message is empty.�lc�id�*Unexpected format for serialized message: z Message does not have an id.����Messager5�type�&Unexpected format for stored message: z Message does not have a type.)rZ�replace�lower�rwrrr �_get_message_type�s
�
�r�cCsT|std��d|vrd|vrtd|�d���|dSd|vr&td|�d���|dS)	Nr|r}rGrz Message does not have kwargs.�datar�z Message does not have data.)rZr�rrr �_get_message_fields�s
�
�r��Dict[str, Any]cCst|�}t|�}||d�S)z&Extract message from a message object.�r�r�)r�r�)rw�message_type�message_datarrr �_convert_message�s
r��inputs�List[Dict[str, Any]]cCs@d|vr
dd�|dD�Sd|vrt|d�gStd|�d���)aGExtract 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.
    �messagescSsg|]}t|��qSr)r�)rJrwrrr rQ��z,get_messages_from_inputs.<locals>.<listcomp>rwz-Could not find message(s) in run with inputs �.)r�rZ)r�rrr �get_messages_from_inputs�s

r��outputscCsrd|vrtd|�d���|d}t|�dkr#tdt|��d|�d���|d}d|vr3td	|�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�rHz3Chat examples expect exactly one generation. Found z generations: rrwz"Unexpected format for generation: z%. Generation does not have a message.)rZ�lenr��r�r��first_generationrrr �#get_message_generation_from_outputs�s"���
�r�cCsTd|vr|dSd|vr"|d}t|�dkr|dStd|�d���td|�d���)	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�promptsrHrz$Multiple prompts in run with inputs z!. Please create example manually.z)Could not find prompt in run with inputs r�)r�rZ)r�r�rrr �get_prompt_from_inputss
�r�cCs`d|vrtd|�d���|d}t|�dkrtd|����|d}d|vr,td|����|dS)	z(Get the LLM generation from the outputs.r�r�r�rHzMultiple generations in run: rrjzNo text in generation: )rZr�r�rrr �get_llm_generation_from_outputssr��	List[str]cCszztjgd�tjtjd�ddgWStjtfy<ztjddgtjtjd�dgWYStjtfy;td��ww)z7Get the correct docker compose command for this system.)�docker�compose�	--version)�stdout�stderrr�r�zdocker-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/)�
subprocess�
check_call�DEVNULL�CalledProcessError�FileNotFoundErrorrZrrrr �get_docker_compose_command,s*�
����r��ls_schemas.BaseMessageLike�dictcCs<|jd|jid�}|jrt|j�dkri|j�|dd<|S)z*Convert a LangChain message to an example.�contentr�rr��additional_kwargs)r�r�r�r�)rw�	convertedrrr �convert_langchain_messageGs�r��obj�objectcCs@ttt|dd�t�tt|dd�t�t|d�ott|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�r�)�allro�getattrrir��hasattr)r�rrr �is_base_message_likeSs	��r��d)�	LANGSMITH�	LANGCHAIN)�
namespaces�namer7�
Optional[str]r�rcs<�fdd�|D�}|D]�tj���}|dur|Sq|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.
    csg|]	}|�d����qS)�_r)rJ�	namespace�r�rr rQyrXzget_env_var.<locals>.<listcomp>N)�os�environrI)r�r7r��namesrrrr�r r:es�r:Tc	Cs&tj�dtdtd|rdndd�d��S)z,Get the project name for a LangSmith tracer.�HOSTED_LANGSERVE_PROJECT_NAME�PROJECT�SESSIONr7Nr6)r�r�rIr:)�return_default_valuerrr �get_tracer_project�s���r�cs.eZdZdZd
d�fdd	�
Zddd�Z�ZS)�FilterPoolFullWarningzFFilter urrllib3 warnings logged when the connection pool isn't reused.r5r�ri�hostr.recst��|�||_dS)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)�super�__init__�_host)�selfr�r���	__class__rr r��s
zFilterPoolFullWarning.__init__r>cCs|��}d|vr
dS|j|vS)zJurllib3.connectionpool:Connection pool is full, discarding connection: ...z.Connection pool is full, discarding connectionT)�
getMessager��r��record�msgrrr �filter�s
zFilterPoolFullWarning.filter)r5r5)r�rir�rir.re�r.r>)rrrrr�r��
__classcell__rrr�r r��s
r�c@seZdZdZddd�ZdS)�FilterLangSmithRetryz!Filter for retries from this lib.r.r>cCs|��}d|vS)z!Filter retries from this library.�LangSmithRetry)r�r�rrr r��szFilterLangSmithRetry.filterNr�)rrrrr�rrrr r��sr�c@r)r�z&Wrapper to filter logs with this name.Nrrrrr r��r!r��logger�logging.Logger�filters�Sequence[logging.Filter]�Generator[None, None, None]ccs��t�|D]}|�|�qWd�n1swYz3dVWt�#|D]}z|�|�Wq'ty>t�d�Yq'wWd�dS1sJwYdSt�"|D]}z|�|�WqVtymt�d�YqVwWd�w1sxwYw)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.
    NzFailed to remove filter)�_FILTER_LOCK�	addFilter�removeFilter�
BaseExceptionrx�warning)r�r�r�rrr �filter_logs�s2�����(����r��cachecCs|dur|Stddd�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.
    N�
TEST_CACHEr6rA)r�rrr �
get_cache_dir�s
r��path�Union[str, pathlib.Path]�ignore_hosts�Optional[Sequence[str]]c#s��zddl}Wntytd��wddlm}|��d�fdd	�}tj�|�\}}|j|�	d
�s8|�	d�r:dnd
|dgd�ddg|d�}|�
|��dVWd�dS1s[wYdS)�Use a cache for requests.rNzNvcrpy is required to use caching. Install with:pip install -U "langsmith[vcr]")�_patch�requestrr.cs(�rt�fdd��D��rdSi�_�S)Nc3s�|]	}�j�|�VqdS�N)�url�
startswith)rJr��r�rr rM�s�z>with_cache.<locals>._filter_request_headers.<locals>.<genexpr>)�any�headersr��r�r�r �_filter_request_headers�sz+with_cache.<locals>._filter_request_headersz.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�rr.r)�vcr�ImportError�langsmith._internalr��
patch_urllib3r�r��split�VCR�endswith�use_cassette)r�r�rrr��	cache_dir�
cache_file�ls_vcrrr�r �
with_cache�s6������"�r�"Optional[Union[str, pathlib.Path]]ccsJ�|dur t||��dVWd�dS1swYdSdVdS)r�N)r)r�r�rrr �with_optional_caches�"�
rcCs&tjt���}dd�|D�}d�|�S)NcSsg|]}d|vr|�qS)z
langsmith/r)rJ�linerrr rQsz_format_exc.<locals>.<listcomp>r5)�	traceback�format_exception�sys�exc_inforV)�tb_lines�filtered_linesrrr �_format_excs
r�T��val�memo�Dict[int, Any]�	max_depth�_depthcs�t|�}t|dd�}|durz|��WStyYnw��kr#|St|t�r5���fdd�|��D�St|t�rE���fdd�|D�St|t�rWt���fdd�|D��St|t�rg���fdd	�|D�S|S)
N�__deepcopy__c	s2i|]\}}t|���d�t|���d��qSrR��_middle_copy)rJ�k�v�r rrrr �
<dictcomp>4s���z _middle_copy.<locals>.<dictcomp>csg|]}t|���d��qSrRr"�rJ�itemr&rr rQ;�z _middle_copy.<locals>.<listcomp>c3s"�|]}t|���d�VqdS)rHNr"r(r&rr rM=rNz_middle_copy.<locals>.<genexpr>csh|]}t|���d��qSrRr"r(r&rr �	<setcomp>?r*z_middle_copy.<locals>.<setcomp>)	r�r�r�ror��items�list�tuple�set)rrrr �cls�copierrr&r r#&s*
�
�


r#c
CsRi}zt�||�WSty(}zt�dt|��t||�WYd}~Sd}~ww)z�Deep copy a value with a compromise for uncopyable objects.

    Args:
        val: The value to be deep copied.

    Returns:
        The deep copied value.
    zFailed to deepcopy input: %sN)�copy�deepcopyr�rx�debug�reprr#)rrrkrrr �deepish_copyDs	��r6�current_version�target_versioncCs(ddlm}|�|�}|�|�}||kS)zGCheck if the current version is greater or equal to the target version.r)�version)�	packagingr9r)r7r8r9�current�targetrrr �is_version_greater_or_equalYs

r=�
identifier�Tuple[str, str, str]cCs�|r|�d�dks|�d�s|�d�rtd|����|�dd�}|d}t|�dkr.|dnd}d|vrL|�dd�\}}|r@|sGtd|����|||fS|sUtd|����d||fS)aEParse 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.
    �/rHzInvalid identifier format: �:r�latest�-)rTr�r
rZrr�)r>�parts�
owner_name�commit�ownerr�rrr �parse_prompt_identifierbs&
���

rH�Pcs8eZdZdZd�fd
d�Zdd
d�d�fdd�Z�ZS)�ContextThreadPoolExecutorz?ThreadPoolExecutor that copies the context to the child thread.rE�Callable[P, T]rF�P.argsrG�P.kwargsr.�	Future[T]cs6t��ttdtftjt��j	|g|�Ri|����S)aCSubmit 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��submitrrrr_�partial�contextvars�copy_context�run)r�rErFrGr�rr rO�s

�����z ContextThreadPoolExecutor.submitNrH��timeout�	chunksize�fn�Callable[..., T]�	iterables�
Iterable[Any]rU�Optional[float]rVrv�Iterator[T]csFdd�tt|d��D��d��fdd	�}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.
        cSsg|]}t���qSr)rQrR)rJr�rrr rQ�r�z1ContextThreadPoolExecutor.map.<locals>.<listcomp>rrFrr.rcs���j�g|�R�Sr�)�poprS)rF��contextsrWrr �_wrapped_fn�sz2ContextThreadPoolExecutor.map.<locals>._wrapped_fnrTN)rFrr.r)�ranger�r��map)r�rWrUrVrYr`r�r^r rb�s���zContextThreadPoolExecutor.map)rErKrFrLrGrMr.rN)
rWrXrYrZrUr[rVrvr.r\)rrrrrOrbr�rrr�r rJ�s�rJ�api_urlcCs@|p
tttddd��}|��std��|���d��d��d�S)zBGet the LangSmith API URL from the environment or the given value.�ENDPOINTzhttps://api.smith.langchain.comr6z!LangSmith API URL cannot be empty�"�'r@)rrir:�stripr$�rstrip)rc�_api_urlrrr �get_api_url�s��rj�api_keycCs@|dur|ntddd�}|dus|��sdS|���d��d�S)z8Get the API key from the environment or the given value.N�API_KEYr6rerf)r:rg)rk�api_key_rrr �get_api_key�srnr�cCsVzt�|�j�d�d}t�|�}|dkp|�d�p|�d�WStjy*YdSw)z�Check if the URL is localhost.

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

    Returns:
    -------
    bool
        True if the URL is localhost, False otherwise.
    rArz	127.0.0.1z0.0.0.0z::F)�urllib_parse�urlsplit�netlocr�socket�
gethostbynamer��gaierror)r�rq�iprrr �
_is_localhost�s

�rv��web_urlcCs�|r|St�|�}t|�rd}|St|j��d�r/t|j��dd�d}t�|j|d��}|St|j��d�rMt|j��dd�d}t�|j|d��}|St|j	��
d�rYd}|St|j	��
d	�red
}|St|j	��
d�rqd}|Sd
}|S)z1Get the host URL based on the web URL or API URL.zhttp://localhostz/apirHr)r�z/api/v1zeu.zhttps://eu.smith.langchain.comzdev.zhttps://dev.smith.langchain.comzbeta.z https://beta.smith.langchain.comzhttps://smith.langchain.com)ro�urlparservrir�r
�rsplit�
urlunparse�_replacerqr�)rxrc�
parsed_url�link�new_pathrrr �get_host_url�s2
��	����r�rW�depthcCs�|dkst|�st|�St|d�r|jSt|tj�r"t|j|d�St|d�r>t|d�r6t|j	d�r6|j	jSt|j
|d�St|�S)NrwrrH�__call__r�)�callablerir�rror_rP�_get_function_namerEr�r�)rWr�rrr r�s

r�rcCs(|dup|dkp|dkp|dkp|dkS)z�Check if the value is truish.

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

    Returns:
        bool: True if the value is truish, False otherwise.
    Tr8�True�TRUE�1r)rrrr �	is_truish%s(	r�r�)r,r-r.r/r�)rCrDr.r)rcrdr.re)rmrnr.ri)rurvrwrir.re)rwr{r.ri)rwr{r.r{)rwr{r.r�)r�r{r.r�)r�r{r.r�)r�r{r.ri)r�r{r.ri)r.r�)rwr�r.r�)r�r�r.r>)r�rir7r�r�rr.r�)T)r.r�)r�r�r�r�r.r�)r�r�r.r�)r�r�r�r�r.r�)r�rr�r�r.r�)r.ri)rr)
rrrrrrvr rvr.r)rrr.r)r7rir8rir.r>)r>rir.r?)rcr�r.ri)rkr�r.r�)r�rir.r>)rxr�rcri)r)rWrr�rvr.ri)rrr.r>)kr�
__future__r�
contextlibrQr2rpr_�loggingr��pathlibrrr�r�	threadingr�concurrent.futuresrr�typingrrrrr	r
rrr
rrrrrr�urllibrro�httpxrg�typing_extensionsr�urllib3.utilr�	langsmithr�
ls_schemas�	getLoggerrrx�	Exceptionrr"r#r$r%r&r'r(r)�UserWarningr*r+r=rBrbrlrs�	lru_cacherzr�r�r�r�r�r�r�r�r�r�r:r��Filterr�r�r��RLockr��contextmanagerr�r�rrrrr#r6r=rHrIrJrjrnrvr�r�r�rrrr �<module>s�D


















��


�*�
�


	#
G