
    ier                    L   d Z ddlmZ ddlZddlmc 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/m0Z0 dd
l1m2Z3  ejh                  e5      Z6 G d de7      Z8 G d de8      Z9 G d de8      Z: G d de8      Z; G d de8      Z< G d de8      Z= G d de8      Z> G d de8      Z? G d de8      Z@ G d de8      ZAd[dZB G d  d!eC      ZD G d" d#eD      ZEd\d]d$ZFd^d%ZGd_d&ZH	 	 	 	 d`d'ZIdad(ZJ ej                  d)*      dbd+       ZLdcd,ZMddd-ZNded.ZOdfd/ZPdgd0ZQdhd1ZRdid2ZS ej                  d)*      djd3       ZTdkd4ZUdld5ZVdmd6ZWe'd7d8	 	 	 	 	 	 	 dnd9       ZXe'	 d\d7d8	 	 	 	 	 	 	 dod:       ZX ej                  d;*      	 d\d7d8	 	 	 	 	 	 	 dpd<       ZX ej                  d)*      dqdrd=       ZY G d> d?ej                        Z[ G d@ dAej                        Z\ G dB dCe0      Z] ej                         Z_e	j                  	 	 	 	 	 	 dsdD       ZadtdEZbdddF	 	 	 	 	 	 	 dudGZce	j                  	 	 dv	 	 	 	 	 	 	 dwdH       Zde	j                  	 	 dv	 	 	 	 	 	 	 dxdI       ZedydJZf e$dK      Zg	 dz	 	 	 	 	 	 	 	 	 d{dLZhd|dMZid}dNZjd~dOZk e.dP      Zl G dQ dRe      ZmddSZnddTZoddUZpddVZq ej                  dW*      ddX       ZrdddYZsddZZty)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__     W/home/jang/Projects/ai-researcher/.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$   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                    d|  dS )a%  Get the error message for an invalid prompt identifier.

    Used consistently across the codebase when parsing prompt identifiers fails.

    Args:
        identifier: The invalid identifier that was provided.

    Returns:
        A formatted error message explaining the valid formats.
    z#Invalid prompt identifier format: "z". Expected one of:
  - "prompt-name" (for private prompts)
  - "owner/prompt-name" (for prompts with explicit owner)
  - "prompt-name:commit-hash" (with commit reference)
  - "owner/prompt-name:commit-hash" (with owner and commit)r   )
identifiers    r    !get_invalid_prompt_identifier_msgrC   Y   s     .j\ :F 	Gr   c                      e Zd ZdZy)LangSmithWarningzBase class for warnings.Nr   r   r   r    rE   rE   q   s    "r   rE   c                      e Zd ZdZy)LangSmithMissingAPIKeyWarningzWarning for missing API key.Nr   r   r   r    rG   rG   u   r/   r   rG   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_helpersrI   rJ   _GLOBAL_TRACING_ENABLEDget_env_var)ctxrT   rI   rJ   tc
var_results         r    tracing_is_enabledr[   y   sq     43O		%#%B
 
)} )}''3///\;yRT3UVJr   c                 "    t        dd      dk(  S )z"Return True if testing is enabled.TEST_TRACKINGrN   rO   falserW   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   !!re   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)ru   rv   rt   s   ` r    	decoratorzxor_args.<locals>.decorator   s%    			) 
	)  r   )ru   r   r=   r   r   )rt   ry   s   ` r    xor_argsrz      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HTTPStatusErrorr|   )r}   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   re   )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.MessagerN   type&Unexpected format for stored message: z Message does not have a type.)rm   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.)rm   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   rm   )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   re   z3Chat examples expect exactly one generation. Found z generations: r   r   z"Unexpected format for generation: z%. Generation does not have a message.)rm   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promptsre   r   z$Multiple prompts in run with inputs z!. Please create example manually.z)Could not find prompt in run with inputs r   )r   rm   )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   re   zMultiple generations in run: r   r   zNo text in generation: )rm   r   r   s      r    get_llm_generation_from_outputsr   C  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FileNotFoundErrorrm   r   r   r    get_docker_compose_commandr   P  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   k  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   w  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_truishrW   )r   s    r    is_env_var_truishr     s    }['((r   )	LANGSMITH	LANGCHAIN)
namespacesc                    y Nr   namerP   r   s      r    rW   rW     s     r   c                    y r   r   r   s      r    rW   rW     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.
    _rN   )osenvironrf   strip)r   rP   r   	namespacenamesr   s         r    rW   rW     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SESSIONrP   NrO   )r   r   rf   rW   )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   )rN   rN   )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_CACHErO   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)rg   r   r|   s     r    ri   z)filter_request_headers.<locals>.<genexpr>(  s      RTGKK2248Rs   %(NrN   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)rg   r   r|   request_hosts     r    ri   z)filter_request_headers.<locals>.<genexpr>3  s]      	
  ??#:; &&t,!T)N\-B-BQtf:-NO		
s   AA)anyurllib_parseurlparser  	Exceptionhostnameheaders)r|   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  )r|   r  r  s    r    <lambda>zwith_cache.<locals>.<lambda>e  s    .D,K/
 r   )
serializercassette_library_dirrecord_modematch_onfilter_headersbefore_record_request)vcrImportErrorlangsmith._internalr"  patch_urllib3r   r(  splitVCRr  use_cassette)r(  r  r  r3  r6  	cache_dir
cache_filels_vcrs    ``     r    
with_cacher=  D  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?  m  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/rN   )	tracebackformat_exceptionsysexc_inforl   )tb_lineslinefiltered_liness      r    _format_excrH  {  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__re   c              3  @   K   | ]  }t        |d z           yw)re   N)_middle_copy)rg   item_depth	max_depthmemos     r    ri   z_middle_copy.<locals>.<genexpr>  s      U\$i!DUs   )
r   r   r  r   r   itemsrM  listtupleset)	valrQ  rP  rO  clscopierkvrN  s	    ```     r    rM  rM    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reprrM  )rV  rQ  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)	packagingrb  r   )current_versiontarget_versionrb  currenttargets        r    is_version_greater_or_equalrh    s,    !mmO,G]]>*Ffr   c                   | r6| j                  d      dkD  s"| j                  d      s| j                  d      rt        t	        |             | j                  dd      }|d   }t        |      dkD  r|d   nd}d|v r2|j                  dd      \  }}|r|st        t	        |             |||fS |st        t	        |             d||fS )a3  Parse a string in the format of `owner/name:hash`, `name:hash`, `owner/name`, or `name`.

    Args:
        identifier: The prompt identifier to parse.

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

    Raises:
        ValueError: If the identifier doesn't match the expected formats.
    /re   :r   latest-)rq   r  r  rm   rC   r7  r   )rB   parts
owner_namecommitownerr   s         r    parse_prompt_identifierrr    s     C 1$  %s#::FGGS!$EqJUaU1XXF
j &&sA.tD>zJKKdF"">zJKK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   rI  rw   partialcontextvarscopy_contextrun)r9   ru   r:   r;   r<   s       r    rw  z ContextThreadPoolExecutor.submit  s\      w~a !!,,.22D;?CI
 	
r   Nre   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   )popr{  )r:   contextsfns    r    _wrapped_fnz2ContextThreadPoolExecutor.map.<locals>._wrapped_fn#  s!    %8<<>%%b0400r   r|  )r:   r   r=   rI  )ranger   ry  rz  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)ru   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   rw  r  r?   r@   s   @r    ru  ru    ss    I

 
 	

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

 (
 
(
 (
r   ru  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.comrO   z!LangSmith API URL cannot be empty"'rj  )r   r   rW   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_KEYrO   r  r  rW   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_IDrO   r  r  r  )workspace_idworkspace_id_s     r    get_workspace_idr  D  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.
    rk  r   z	127.0.0.1z0.0.0.0z::F)r  urlsplitnetlocr7  socketgethostbynamer  gaierror)r  r  ips      r    _is_localhostr  P  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/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  r   r(  r  rsplit
urlunparse_replacer  r  )web_urlr  r  linknew_paths        r    get_host_urlr  e  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   re   __call__r<   )callabler   r   r   r   rw   rx  _get_function_nameru   r<   r  )r  depths     r    r  r  ~  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.
    rQ   1)r   r   r   r   )rV  s    r    r   r     s2     #syy{f$2s
29r   )rB   r   r=   r   r   )rX   zOptional[dict]r=   zUnion[bool, Literal['local']]r   )rt   ztuple[str, ...]r=   r   )r}   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   rP   r   r   rT  r=   r   )r   r   rP   r>   r   rT  r=   r  )r   r   rP   r  r   rT  r=   r  )T)r=   r  )r  zlogging.Loggerr  zSequence[logging.Filter]r=   Generator[None, None, None])r  r  r=   r  )r|   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   )
rV  rI  rQ  zdict[int, Any]rP  r  rO  r  r=   rI  )rV  rI  r=   rI  )rd  r   re  r   r=   r   )rB   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   )rV  r   r=   r   )ur   
__future__r   builtins@py_builtins_pytest.assertion.rewrite	assertionrewrite
@pytest_ar
contextlibry  r\  r   rw   loggingr   pathlibr  r   rC  	threadingrA  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   rC   UserWarningrE   rG   r[   r`   rz   r   r   	lru_cacher   r   r   r   r   r   r   r   r   r   r   r   rW   r   Filterr   r   r   RLockr  contextmanagerr  r  r  r=  r?  rH  rI  rM  r`  rh  rr  rs  ru  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 %0#{ #'$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   