
    ho                       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jZ                  e.      Z/ G d de0      Z1 G d de1      Z2 G d de1      Z3 G d de1      Z4 G d de1      Z5 G d de1      Z6 G d de1      Z7 G d de1      Z8 G d de1      Z9 G d de1      Z: G d d e;      Z< G d! d"e<      Z=dXdYd#Z>dZd$Z?d[d%Z@	 	 	 	 d\d&ZAd]d'ZB ej                  d()      d^d*       ZDd_d+ZEd`d,ZFdad-ZGdbd.ZHdcd/ZIddd0ZJded1ZK ej                  d()      dfd2       ZLdgd3ZMdhd4ZNdid5ZO ej                  d6)      	 dXd7d8	 	 	 	 	 	 	 djd9       ZP ej                  d()      dkdld:       ZQ G d; d<ej                        ZS G d= d>ej                        ZT G d? d@e)      ZU ej                         ZWej                  	 	 	 	 	 	 dmdA       ZYdndBZZdddC	 	 	 	 	 	 	 dodDZ[ej                  	 	 dp	 	 	 	 	 	 	 dqdE       Z\ej                  	 	 dp	 	 	 	 	 	 	 drdF       Z]dsdGZ^ edH      Z_	 dt	 	 	 	 	 	 	 	 	 dudIZ`dvdJZadwdKZbdxdLZc e'dM      Zd G dN dOe      ZedydPZfdzdQZgd{dRZhd|dSZi ej                  dT)      d}dU       Zjd~ddVZkddWZly)zGeneric utility functions.    )annotationsN)	GeneratorIterableIteratorMappingSequence)FutureThreadPoolExecutor)AnyCallableLiteralOptionalTypeVarUnioncast)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__     M/var/www/html/eduruby.in/venv/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#   1   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%   5   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'   9   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+   A   s    /r   r+   c                      e Zd ZdZy)LangSmithConflictErrorzThe resource already exists.Nr   r   r   r   r-   r-   E       &r   r-   c                      e Zd ZdZy)LangSmithConnectionErrorz&Couldn't connect to the LangSmith API.Nr   r   r   r   r0   r0   I       0r   r0   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)selfr7   argskwargs	__class__s       r   r6   z LangSmithExceptionGroup.__init__P   s     	$)&)$r   )r9   r   r7   zSequence[Exception]r:   r   returnNone)r   r   r   r   r6   __classcell__r;   s   @r   r3   r3   M   s0    /%%&9%EH%	% %r   r3   c                      e Zd ZdZy)LangSmithWarningzBase class for warnings.Nr   r   r   r   rA   rA   [   s    "r   rA   c                      e Zd ZdZy)LangSmithMissingAPIKeyWarningzWarning for missing API key.Nr   r   r   r   rC   rC   _   r.   r   rC   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_helpersrE   rF   _GLOBAL_TRACING_ENABLEDget_env_var)ctxrP   rE   rF   tc
var_results         r   tracing_is_enabledrW   c   sq     43O		%#%B
 
)} )}''3///\;yRT3UVJr   c                 "    t        dd      dk(  S )z"Return True if testing is enabled.TEST_TRACKINGrJ   rK   falserS   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   !!ra   z, zFExactly one argument in each of the following groups must be defined: )sum	enumeratejoin
ValueError)
r9   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)r9   r   r:   r   r<   r   )	functoolswraps)rq   rr   rp   s   ` r   	decoratorzxor_args.<locals>.decorator   s%    			) 
	)  r   )rq   r   r<   r   r   )rp   ru   s   ` r   xor_argsrv      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HTTPStatusErrorrx   )ry   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   ra   )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.MessagerJ   type&Unexpected format for stored message: z Message does not have a type.)ri   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.)ri   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 )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.
    messagesr   z-Could not find message(s) in run with inputs .)r   ri   )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 (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   ra   z3Chat examples expect exactly one generation. Found z generations: r   r   z"Unexpected format for generation: z%. Generation does not have a message.)ri   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 (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promptsra   r   z$Multiple prompts in run with inputs z!. Please create example manually.z)Could not find prompt in run with inputs r   )r   ri   )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   ra   zMultiple generations in run: r   r~   zNo text in generation: )ri   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FileNotFoundErrorri   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 (object): 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                *    t        t        |             S )z2Check if the given environment variable is truish.)	is_truishrS   )r   s    r   is_env_var_truishr   t  s    ['((r   d   )	LANGSMITH	LANGCHAIN)
namespacesc                   |D cg c]	  }| d|   }}|D ]'  } t         j                  j                  |       }|%|c S  |S c c}w )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.
    _)osenvironrb   )namerL   r   	namespacenamesr   s         r   rS   rS   y  s[    ( 5??y	{!D6"?E? 

t$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SESSIONrL   NrK   )r   r   rb   rS   )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 )FilterPoolFullWarningzFFilter urrllib3 warnings logged when the connection pool isn't reused.c                2    t         |   |       || _        y)zInitialize the FilterPoolFullWarning filter.

        Args:
            name (str, optional): The name of the filter. Defaults to "".
            host (str, optional): The host to filter. Defaults to "".
        N)r5   r6   _host)r8   r   hostr;   s      r   r6   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   r8   recordmsgs      r   filterzFilterPoolFullWarning.filter  s*    !;3Fzz$$r   )rJ   rJ   )r   r}   r   r}   r<   r=   r<   bool)r   r   r   r   r6   r   r>   r?   s   @r   r   r     s    P%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     r1   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 (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_CACHErK   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)z=Filter request headers based on ignore_hosts and allow_hosts.c              3  T   K   | ]  }j                   j                  |       ! y wN)url
startswith)rc   r   rx   s     r   re   z)filter_request_headers.<locals>.<genexpr>   s      RTGKK2248Rs   %(NrJ   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)rc   r   rx   request_hosts     r   re   z)filter_request_headers.<locals>.<genexpr>  s]      	
  ??#:; &&t,!T)N\-B-BQtf:-NO		
s   AA)anyurllib_parseurlparser
  	Exceptionhostnameheaders)rx   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  )rx   r  r  s    r   <lambda>zwith_cache.<locals>.<lambda>=  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  r+  r.  	cache_dir
cache_filels_vcrs    ``     r   
with_cacher5    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)r5  )r   r  r  s      r   with_optional_cacher7  E  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/rJ   )	tracebackformat_exceptionsysexc_inforh   )tb_lineslinefiltered_liness      r   _format_excr@  S  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__ra   c              3  @   K   | ]  }t        |d z           yw)ra   N)_middle_copy)rc   item_depth	max_depthmemos     r   re   z_middle_copy.<locals>.<genexpr>t  s      U\$i!DUs   )
r   r   r   r   r   itemsrE  listtupleset)	valrI  rH  rG  clscopierkvrF  s	    ```     r   rE  rE  ]  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reprrE  )rN  rI  r   s      r   deepish_copyrX  {  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)	packagingrZ  r   )current_versiontarget_versionrZ  currenttargets        r   is_version_greater_or_equalr`    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 )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.
    /ra   zInvalid identifier format: :r   latest-)rm   r  r  ri   r/  r   )
identifierparts
owner_namecommitownerr   s         r   parse_prompt_identifierrk    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.
        .)
r5   submitr   r   rA  rs   partialcontextvarscopy_contextrun)r8   rq   r9   r:   r;   s       r   rp  z ContextThreadPoolExecutor.submit  s\      w~a !!,,.22D;?CI
 	
r   Nra   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	  )poprt  )r9   contextsfns    r   _wrapped_fnz2ContextThreadPoolExecutor.map.<locals>._wrapped_fn  s!    %8<<>%%b0400r   ru  )r9   r   r<   rA  )ranger   rr  rs  r5   map)	r8   r|  rv  rw  	iterablesr   r}  r{  r;   s	    `     @r   r  zContextThreadPoolExecutor.map  sb    < 9>c)A,>O8PQ1K,,.Q	1 w{

 	
 	
 Rs   A)rq   zCallable[P, T]r9   zP.argsr:   zP.kwargsr<   z	Future[T])
r|  zCallable[..., T]r  zIterable[Any]rv  zOptional[float]rw  intr<   zIterator[T])r   r   r   r   rp  r  r>   r?   s   @r   rn  rn    ss    I

 
 	

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

 (
 
(
 (
r   rn  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.comrK   z!LangSmith API URL cannot be empty"'rb  )r   r}   rS   stripr%   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_KEYrK   r  r  rS   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_IDrK   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.
    rc  r   z	127.0.0.1z0.0.0.0z::F)r  urlsplitnetlocr/  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/apira   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  =  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   ra   __call__r;   )callabler}   r   r   r   rs   rq  _get_function_namerq   r;   r  )r|  depths     r   r  r  V  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.
    rM   1)r   r}   r   r   )rN  s    r   r   r   h  s2     #syy{f$2s
29r   r	  )rT   zOptional[dict]r<   zUnion[bool, Literal['local']]r   )rp   ztuple[str, ...]r<   r   )ry   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}   rL   r  r   rL  r<   r  )T)r<   r  )r   zlogging.Loggerr   zSequence[logging.Filter]r<   Generator[None, None, None])r  r  r<   r  )rx   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   )
rN  rA  rI  zdict[int, Any]rH  r  rG  r  r<   rA  )rN  rA  r<   rA  )r\  r}   r]  r}   r<   r   )rf  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}   )rN  r   r<   r   )mr   
__future__r   
contextlibrr  rT  r   rs   loggingr   pathlibr  r   r;  	threadingr9  collections.abcr   r   r   r   r   concurrent.futuresr	   r
   typingr   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-   r0   r3   UserWarningrA   rC   rW   r\   rv   r   r   	lru_cacher   r   r   r   r   r   r   r   r   r   r   r   rS   r   Filterr   r   r   RLockr   contextmanagerr   r  r  r5  r7  r@  rA  rE  rX  r`  rk  rl  rn  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	$)
 S! " 3	
 	
  "6 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   