
    Uivo                    *   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; G d d e<      Z= G d! d"e=      Z>dZd[d#Z?d\d$Z@d]d%ZA	 	 	 	 d^d&ZBd_d'ZC ej                  d()      d`d*       ZEdad+ZFdbd,ZGdcd-ZHddd.ZIded/ZJdfd0ZKdgd1ZL ej                  d()      dhd2       ZMdid3ZNdjd4ZOdkd5ZPe!d6d7	 	 	 	 	 	 	 dld8       ZQe!	 dZd6d7	 	 	 	 	 	 	 dmd9       ZQ ej                  d:)      	 dZd6d7	 	 	 	 	 	 	 dnd;       ZQ ej                  d()      dodpd<       ZR G d= d>ej                        ZT G d? d@ej                        ZU G dA dBe*      ZV ej                         ZXej                  	 	 	 	 	 	 dqdC       ZZdrdDZ[dddE	 	 	 	 	 	 	 dsdFZ\ej                  	 	 dt	 	 	 	 	 	 	 dudG       Z]ej                  	 	 dt	 	 	 	 	 	 	 dvdH       Z^dwdIZ_ edJ      Z`	 dx	 	 	 	 	 	 	 	 	 dydKZadzdLZbd{dMZcd|dNZd e(dO      Ze G dP dQe      Zfd}dRZgd~dSZhddTZiddUZj ej                  dV)      ddW       ZkdddXZlddYZmy)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y)LangSmithErrorz=An error occurred while communicating with the LangSmith API.N__name__
__module____qualname____doc__     \/var/www/html/eventheodds/airagagent/rag_env/lib/python3.12/site-packages/langsmith/utils.pyr   r   *   s    Gr   r   c                      e Zd ZdZy)LangSmithAPIErrorz9Internal server error while communicating with LangSmith.Nr   r   r   r    r"   r"   .   s    Cr   r"   c                      e Zd ZdZy)LangSmithRequestTimeoutz*Client took too long to send request body.Nr   r   r   r    r$   r$   2   s    4r   r$   c                      e Zd ZdZy)LangSmithUserErrorzAUser error caused an exception when communicating with LangSmith.Nr   r   r   r    r&   r&   6   s    Kr   r&   c                      e Zd ZdZy)LangSmithRateLimitErrorz7You have exceeded the rate limit for the LangSmith API.Nr   r   r   r    r(   r(   :   s    Ar   r(   c                      e Zd ZdZy)LangSmithAuthErrorz-Couldn't authenticate with the LangSmith API.Nr   r   r   r    r*   r*   >   s    7r   r*   c                      e Zd ZdZy)LangSmithNotFoundErrorz%Couldn't find the requested resource.Nr   r   r   r    r,   r,   B   s    /r   r,   c                      e Zd ZdZy)LangSmithConflictErrorzThe resource already exists.Nr   r   r   r    r.   r.   F       &r   r.   c                      e Zd ZdZy)LangSmithConnectionErrorz&Couldn't connect to the LangSmith API.Nr   r   r   r    r1   r1   J       0r   r1   c                  4     e Zd ZdZ	 	 	 	 	 	 	 	 d fdZ xZS )LangSmithExceptionGroupz%Port of ExceptionGroup for Py < 3.11.c               2    t        |   |i | || _        y)zInitialize.N)super__init__
exceptions)selfr8   argskwargs	__class__s       r    r7   z LangSmithExceptionGroup.__init__Q   s     	$)&)$r   )r:   r   r8   zSequence[Exception]r;   r   returnNone)r   r   r   r   r7   __classcell__r<   s   @r    r4   r4   N   s0    /%%&9%EH%	% %r   r4   c                      e Zd ZdZy)LangSmithWarningzBase class for warnings.Nr   r   r   r    rB   rB   \   s    "r   rB   c                      e Zd ZdZy)LangSmithMissingAPIKeyWarningzWarning for missing API key.Nr   r   r   r    rD   rD   `   r/   r   rD   c                    ddl mc m} ddlm}m} | xs  |       }|d   |d   S  |       ry|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_helpersrF   rG   _GLOBAL_TRACING_ENABLEDget_env_var)ctxrQ   rF   rG   tc
var_results         r    tracing_is_enabledrX   d   sq     43O		%#%B
 
)} )}''3///\;yRT3UVJr   c                 "    t        dd      dk(  S )z"Return True if testing is enabled.TEST_TRACKINGrK   rL   falserT   r   r   r    test_tracking_is_disabledr]   |   s    3w>>r   c                      d fd}|S )z7Validate specified keyword args are mutually exclusive.c                H     t        j                         d fd       }|S )Nc                 >   D cg c]  }t        fd|D               }}t        |      D cg c]  \  }}|dk7  s| }}}|r>|D cg c]  }dj                  |          }}t        ddj                  |              	| i S c c}w c c}}w c c}w )z3Validate exactly one arg in each group is not None.c              3  F   K   | ]  }j                  |      d  y w)N   )get).0argr;   s     r    	<genexpr>z?xor_args.<locals>.decorator.<locals>.wrapper.<locals>.<genexpr>   s     J#fjjo.IAJs   !!rb   z, zFExactly one argument in each of the following groups must be defined: )sum	enumeratejoin
ValueError)
r:   r;   	arg_groupcountsicountinvalid_groupsinvalid_group_names
arg_groupsfuncs
    `      r    wrapperz,xor_args.<locals>.decorator.<locals>.wrapper   s    
 ", JJJF  1:&0APHAuUaZaPNPIW&XAtyyA'?&X#&X 		"5679 
 ((( Q&Xs   BB BB)r:   r   r;   r   r=   r   )	functoolswraps)rr   rs   rq   s   ` r    	decoratorzxor_args.<locals>.decorator   s%    			) 
	)  r   )rr   r   r=   r   r   )rq   rv   s   ` r    xor_argsrw      s    ( r   c                R   	 | j                          y# t        j                  $ r/}t        j                  t        |      | j                        |d}~wt
        j                  $ r@}t        j                  t        |       d| j                   | j                  |       |d}~ww xY w)z&Raise an error with the response text.Nz: )requestresponse)raise_for_statusrequests	HTTPErrorstrtexthttpxHTTPStatusErrorry   )rz   es     r    raise_for_status_with_textr      s    	!!# ?  Q7Q>   ##1vhb($$
 		s     B&*AB&&;B!!B&c                R    t        | t        j                        r| j                  S | S )zGet the value of a string enum.)
isinstanceenumEnumvalue)enus    r    get_enum_valuer      s    #tyy!yyJr   rb   )maxsizec                0    t         j                  | |       y)z4Log a message at the specified level, but only once.N)_LOGGERlog)levelmessages     r    log_oncer      s     KKwr   c                    | st        d      d| v r9d| vrt        d|  d      | d   d   j                  dd      j                         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.MessagerK   type&Unexpected format for stored message: z Message does not have a type.)rj   replacelowerr   s    r    _get_message_typer      s    ,--ww<WI/0  t}R ((B7==?? 8	0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   r;   r   z Message does not have kwargs.datar   z Message does not have data.)rj   r   s    r    _get_message_fieldsr      sy    ,--w7"<WI01  x   8	./  vr   c                8    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7r   c                    d| v r| d   D cg c]  }t        |       c}S d| v rt        | d         gS t        d|  d      c c}w )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.
    messagesr   z-Could not find message(s) in run with inputs .)r   rj   )inputsr   s     r    get_messages_from_inputsr      s^     V9?
9KLg )LLF 	!2344
DVHAN
OO Ms   Ac                    d| vrt        d|  d      | d   }t        |      dk7  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   rb   z3Chat examples expect exactly one generation. Found z generations: r   r   z"Unexpected format for generation: z%. Generation does not have a message.)rj   lenr   outputsr   first_generations      r    #get_message_generation_from_outputsr      s     G#GyPQRSS-(K
;1+&'~k]!E
 	
 #1~((01A0B C3 3
 	
 ,Y788r   c                    d| v r| d   S d| v r'| 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promptsrb   r   z$Multiple prompts in run with inputs z!. Please create example manually.z)Could not find prompt in run with inputs r   )r   rj   )r   r   s     r    get_prompt_from_inputsr     st     6hF#w<11:26( ;/ /
 	
 @J
KKr   c                    d| vrt        d|  d      | d   }t        |      dk7  rt        d|       |d   }d|vrt        d|       |d   S )	z(Get the LLM generation from the outputs.r   r   r   rb   zMultiple generations in run: r   r   zNo text in generation: )rj   r   r   s      r    get_llm_generation_from_outputsr   .  s}    G#GyPQRSS-(K
;18FGG"1~%%23C2DEFFF##r   c                 z   	 t        j                  g dt         j                  t         j                         ddgS # t         j                  t        f$ re 	 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FileNotFoundErrorrj   r   r   r    get_docker_compose_commandr   ;  s    .%%%%	

 )$$))+<= 	!!!;/!))!))
 %%%--/@A 	E 	s!   9< B:8BB:%B66B:c                    | j                   d| j                  id}| j                  r,t        | j                        dkD  ri | j                  |d   d<   |S )z*Convert a LangChain message to an example.contentr   r   r   additional_kwargs)r   r   r   r   )r   	converteds     r    convert_langchain_messager   V  s\     GOO,!I
   S)B)B%Ca%G1NG4M4M1N	&-.r   c           
         t        t        t        | dd      t              t        t        | dd      t              t        | d      xr 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   getattrr~   dicthasattr)objs    r    is_base_message_liker   b  sZ     wsIt4c:ws$7>EC JZV0Dc%J	
 r   c                0    | yt        t        |             S )z2Check if the given environment variable is truish.F)	is_truishrT   )r   s    r    is_env_var_truishr   t  s    }['((r   )	LANGSMITH	LANGCHAIN)
namespacesc                    y Nr   namerM   r   s      r    rT   rT   {  s     r   c                    y r   r   r   s      r    rT   rT     s     r   d   c                   |D cg c]	  }| d|   }}|D ];  } t         j                  j                  |       }|%|j                         dk7  s9|c S  |S c c}w )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.
    _rK   )osenvironrc   strip)r   rM   r   	namespacenamesr   s         r    rT   rT     sh    & 5??y	{!D6"?E? 

t$"!4L N @s   Ac           
     v    t         j                  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SESSIONrM   NrL   )r   r   rc   rT   )return_default_values    r    get_tracer_projectr     s=     ::>>
 	(  0D9$		
 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.c                2    t         |   |       || _        y)zInitialize the `FilterPoolFullWarning` filter.

        Args:
            name: The name of the filter. Defaults to `""`.
            host: The host to filter. Defaults to `""`.
        N)r6   r7   _host)r9   r   hostr<   s      r    r7   zFilterPoolFullWarning.__init__  s     	
r   c                H    |j                         }d|vry| j                  |vS )zJurllib3.connectionpool:Connection pool is full, discarding connection: ...z.Connection pool is full, discarding connectionT)
getMessager   r9   recordmsgs      r    filterzFilterPoolFullWarning.filter  s*    !;3Fzz$$r   )rK   rK   )r   r~   r   r~   r=   r>   r=   bool)r   r   r   r   r7   r   r?   r@   s   @r    r   r     s    Q%r   r   c                      e Zd ZdZddZy)FilterLangSmithRetryz!Filter for retries from this lib.c                *    |j                         }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y)r   z&Wrapper to filter logs with this name.Nr   r   r   r    r   r     r2   r   r   c              #    K   t         5  |D ]  }| j                  |        	 ddd       	 d t         5  |D ]  }	 | j                  |        	 ddd       y# 1 sw Y   8xY w# t        $ r t        j                  d       Y Mw xY w# 1 sw Y   yxY w# t         5  |D ]8  }	 | j                  |       # t        $ r t        j                  d       Y 6w xY w 	 ddd       w # 1 sw Y   w xY wxY w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)loggerfiltersr   s      r    filter_logsr    s      
 % 	%FV$	%%? 	?! ??''/?	? 	?% % % ?OO$=>?		? 	?\ 	?! ??''/$ ?OO$=>??	? 	? 	?s   C4AC4B C4B
A&B
	C4A#C4&BB
BB

BC4C1C%$B65C%6CC%CC%	C1%C.*C11C4c                $    | | 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_CACHErL   r\   )caches    r    get_cache_dirr	    s     |T22r   ignore_hostsallow_hostsc                    |rt         fd|D              ry|rH	 t        j                   j                        }|j
                  xs dt         fd|D              }|syi  _         S # t        $ r Y yw xY w)zAFilter request headers based on `ignore_hosts` and `allow_hosts`.c              3  T   K   | ]  }j                   j                  |       ! y wr   )url
startswith)rd   r   ry   s     r    rf   z)filter_request_headers.<locals>.<genexpr>  s      RTGKK2248Rs   %(NrK   c              3     K   | ]K  }|j                  d       rj                  j                  |      n|k(  xs j                  d|        M yw))zhttp://zhttps://r   N)r  r  endswith)rd   r   ry   request_hosts     r    rf   z)filter_request_headers.<locals>.<genexpr>  s]      	
  ??#:; &&t,!T)N\-B-BQtf:-NO		
s   AA)anyurllib_parseurlparser  	Exceptionhostnameheaders)ry   r  r  
parsed_urlhost_matchesr  s   `    @r    filter_request_headersr    s     R\RR	%..w{{;J "**0b 	
 $	
 	
 GON'  		s   A- -	A98A9c           	   #    K   	 ddl }ddlm} |j	                          t
        j                  j                  |       \  }}|j                  |j                  d      s|j                  d      rdnd|d	g d
ddgfd      }|j                  |      5  d ddd       y# t        $ r t        d      w xY w# 1 sw Y   yxY ww)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methodpathbodyauthorizationz
Set-Cookiec                     t        |       S )Nr
  )r  )ry   r  r  s    r    <lambda>zwith_cache.<locals>.<lambda>P  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VCRr  use_cassette)r%  r  r  r0  r3  	cache_dir
cache_filels_vcrs    ``     r    
with_cacher:  /  s     
 <!GGMM$/IzWW ""7+z/B/B6/J & #2'6
  F  
		Z	(  9  
.
 	

8 s4   CB$ BCB<	C$B99C<CCc              #  f   K   | t        | ||      5  d ddd       yd y# 1 sw Y   yxY ww)r  N)r:  )r%  r  r  s      r    with_optional_cacher<  X  s;      lK8 		 	 		 	s   1%1.1c                     t        j                  t        j                          } | D cg c]	  }d|vs| }}dj	                  |      S c c}w )Nz
langsmith/rK   )	tracebackformat_exceptionsysexc_infori   )tb_lineslinefiltered_liness      r    _format_excrE  f  sG    ))3<<>:H'/Lt<t3KdLNL77>"" Ms
   	A
A
Tc                J   t        |       }t        |dd       }|		  |      S k\  r| S t        | t              rB| j                         D ci c]&  \  }}t        |dz         t        |dz         ( c}}S t        | t              r| D cg c]  }t        |dz          c}S t        | t              rt        fd| D              S t        | t              r| D ch c]  }t        |dz          c}S | S # t        $ r Y w xY wc c}}w c c}w c c}w )N__deepcopy__rb   c              3  @   K   | ]  }t        |d z           yw)rb   N)_middle_copy)rd   item_depth	max_depthmemos     r    rf   z_middle_copy.<locals>.<genexpr>  s      U\$i!DUs   )
r   r   r  r   r   itemsrJ  listtupleset)	valrN  rM  rL  clscopierkvrK  s	    ```     r    rJ  rJ  p  s6    s)CS.$/F	$< 
#t
 			
 1 D)VaZ8,4FQJ; 
 	
 #tLOPDT4FQJ?PP#uUQTUUU#sLOPDT4FQJ?PPJ%  		

 Q Qs#   D +DD)D 	DDc                    i }	 t        j                  | |      S # t        $ r5}t        j	                  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reprrJ  )rS  rN  r   s      r    deepish_copyr]    sQ     D'}}S$'' '
 	4d1g>C&&'s    	A*AAAc                \    ddl m} |j                  |       }|j                  |      }||k\  S )zGCheck if the current version is greater or equal to the target version.r   )version)	packagingr_  r   )current_versiontarget_versionr_  currenttargets        r    is_version_greater_or_equalre    s,    !mmO,G]]>*Ffr   c                p   | r6| j                  d      dkD  s"| j                  d      s| j                  d      rt        d|        | j	                  dd      }|d   }t        |      dkD  r|d   nd}d|v r,|j	                  dd      \  }}|r|st        d|        |||fS |st        d|        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.
    /rb   zInvalid identifier format: :r   latest-)rn   r  r  rj   r4  r   )
identifierparts
owner_namecommitownerr   s         r    parse_prompt_identifierrp    s     C 1$  %s#6zlCDDS!$EqJUaU1XXF
j &&sA.tD::,GHHdF""::,GHHJ&&r   Pc                  Z     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.c           
         t         |   t        t        dt        f   t        j                  t        j                         j                  |g|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.
        .)
r6   submitr   r   rF  rt   partialcontextvarscopy_contextrun)r9   rr   r:   r;   r<   s       r    ru  z ContextThreadPoolExecutor.submit  s\      w~a !!,,.22D;?CI
 	
r   Nrb   timeout	chunksizec                   t        t        |d               D cg c]  }t        j                          c}dfd}t	        |   |g|||dS c c}w )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.
        r   c                 F     j                         j                  g|  S r   )popry  )r:   contextsfns    r    _wrapped_fnz2ContextThreadPoolExecutor.map.<locals>._wrapped_fn  s!    %8<<>%%b0400r   rz  )r:   r   r=   rF  )ranger   rw  rx  r6   map)	r9   r  r{  r|  	iterablesr   r  r  r<   s	    `     @r    r  zContextThreadPoolExecutor.map  sb    < 9>c)A,>O8PQ1K,,.Q	1 w{

 	
 	
 Rs   A)rr   zCallable[P, T]r:   zP.argsr;   zP.kwargsr=   z	Future[T])
r  zCallable[..., T]r  zIterable[Any]r{  zOptional[float]r|  intr=   zIterator[T])r   r   r   r   ru  r  r?   r@   s   @r    rs  rs    ss    I

 
 	

 

: $((
(
 "(
 !	(

 (
 
(
 (
r   rs  c                    | xs t        t        t        dd            }|j                         st	        d      |j                         j                  d      j                  d      j                  d      S )zBGet the LangSmith API URL from the environment or the given value.ENDPOINTzhttps://api.smith.langchain.comrL   z!LangSmith API URL cannot be empty"'rg  )r   r~   rT   r   r&   rstrip)api_url_api_urls     r    get_api_urlr    sj     $5	
H >> !DEE>>!!#&,,S188==r   c                    | | nt        dd      }||j                         sy|j                         j                  d      j                  d      S )z8Get the API key from the environment or the given value.NAPI_KEYrL   r  r  rT   r   )api_keyapi_key_s     r    get_api_keyr  '  sK    !-w;yRV3WHx~~/>>!!#&,,S11r   c                    | | nt        dd      }||j                         sy|j                         j                  d      j                  d      S )zGet workspace ID.NWORKSPACE_IDrL   r  r  r  )workspace_idworkspace_id_s     r    get_workspace_idr  /  sY     # 	6 
 M$7$7$9 &&s+11#66r   c                   	 t        j                  |       j                  j                  d      d   }t	        j
                  |      }|dk(  xs$ |j                  d      xs |j                  d      S # t        j                  $ r Y y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.
    rh  r   z	127.0.0.1z0.0.0.0z::F)r  urlsplitnetlocr4  socketgethostbynamer  gaierror)r  r  ips      r    _is_localhostr  ;  sz    &&s+2288=a@!!&)[ SBMM)$<Sd@SS?? s   A0A3 3B	B	   c                   | r| S t        j                  |      }t        |      rd}|S t        |j                        j                  d      rOt        |j                        j                  dd      d   }t        j                  |j                  |            }|S t        |j                        j                  d      rOt        |j                        j                  dd      d   }t        j                  |j                  |            }|S t        |j                        j                  d      rd}|S t        |j                        j                  d	      rd
}|S t        |j                        j                  d      rd}|S d}|S )z1Get the host URL based on the web URL or API URL.zhttp://localhostz/apirb   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  r~   r%  r  rsplit
urlunparse_replacer  r  )web_urlr  r  linknew_paths        r    get_host_urlr  P  sm    &&w/JW! K 
Z__		&	&v	.z'..vq9!<&&z':':':'IJ K 
Z__		&	&y	1z'..y!<Q?&&z':':':'IJ K 
Z		*	*5	1/ K 
Z		*	*6	20
 K	 
Z		*	*7	31 K -Kr   c                   |dkD  st        |       st        |       S t        | d      r| j                  S t	        | t
        j                        rt        | j                  |dz         S t        | d      rQt        | d      r,t        | j                  d      r| j                  j                  S t        | j                  |dz         S t        |       S )Nr  r   rb   __call__r<   )callabler~   r   r   r   rt   rv  _get_function_namerr   r<   r  )r  depths     r    r  r  i  s    qy2wr:{{"i''(!"''51955r:2{#j(I<<(((!"++uqy99r7Nr   c                l    t        | t              r| j                         dk(  xs | 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.
    rN   1)r   r~   r   r   )rS  s    r    r   r   {  s2     #syy{f$2s
29r   r   )rU   zOptional[dict]r=   zUnion[bool, Literal['local']]r   )rq   ztuple[str, ...]r=   r   )rz   z(Union[requests.Response, httpx.Response]r=   r>   )r   zUnion[enum.Enum, str]r=   r~   )r   r  r   r~   r=   r>   )r   Mapping[str, Any]r=   r~   )r   r  r=   r  )r   r  r=   dict[str, Any])r   r  r=   zlist[dict[str, Any]])r   r  r=   r  )r   r  r=   r~   )r   r  r=   r~   )r=   z	list[str])r   zls_schemas.BaseMessageLiker=   r   )r   objectr=   r   )r   Optional[str]r=   r   )r   r~   rM   r~   r   rQ  r=   r~   )r   r~   rM   r>   r   rQ  r=   r  )r   r~   rM   r  r   rQ  r=   r  )T)r=   r  )r  zlogging.Loggerr  zSequence[logging.Filter]r=   Generator[None, None, None])r  r  r=   r  )ry   r   r  Optional[Sequence[str]]r  r  r=   r   )NN)r%  zUnion[str, pathlib.Path]r  r  r  r  r=   r  )r%  z"Optional[Union[str, pathlib.Path]]r  r  r  r  r=   r  )r=   r~   )   r   )
rS  rF  rN  zdict[int, Any]rM  r  rL  r  r=   rF  )rS  rF  r=   rF  )ra  r~   rb  r~   r=   r   )rk  r~   r=   ztuple[str, str, str])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~   )rS  r   r=   r   )nr   
__future__r   
contextlibrw  rY  r   rt   loggingr   pathlibr  r   r@  	threadingr>  collections.abcr   r   r   r   r   concurrent.futuresr	   r
   typingr   r   r   r   r   r   r   r   urllibr   r  r   r|   typing_extensionsr   urllib3.utilr   	langsmithr   
ls_schemas	getLoggerr   r   r  r   r"   r$   r&   r(   r*   r,   r.   r1   r4   UserWarningrB   rD   rX   r]   rw   r   r   	lru_cacher   r   r   r   r   r   r   r   r   r   r   r   rT   r   Filterr   r   r   RLockr   contextmanagerr  r	  r  r:  r<  rE  rF  rJ  r]  re  rp  rq  rs  r  r  r  r  r  r  r   r   r   r    <module>r     s     "       	    
   L L 9	 	 	 )   '  +
'

H
%HY HD D5n 5L LBn B8 80^ 0'^ '1~ 1%n %#{ #'$4 ' 0?
46	  Q    
&&8P&9:L2
$ Q  4	$) 

 3	
 	
 	 
 
  3	
 	
  
 S! " 3	
 	
  "4 Q  &%GNN %*+7>> +1U 1 y  ??%=? ? ?23$ -1+/	!! *! )	!
 	!H  -1+/%
"%)% )% !	% %P  -1+/

,
)
 )
 !	
 
# CL EF	
 -0>A<'* 'F cND
 2 D
N>2	7* Q  0$r   