
    Ngsa                   x   U d Z ddlmZ ddlZddl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ZddlZddlZddlZddlZddlmZ ddlmZ ddlmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- ddl.m/Z0 ddl1Z1ddl1m2Z3 dd	l4m5Z6 dd
l7m8Z8 ddl9m:Z: ddl;m<Z< ddl=Z=ddl=m>Z? ddl=m@ZA ddl=mBZC ddlDmEZE ddlFmGZG ddlFmHZI ddlJmKZK ddlLmMZMmNZNmOZO ddlPmQZQmRZR ddlSmTZTmUZUmVZVmWZWmXZXmYZYmZZZ ddl[m\Z] 	 ddl^m_Z_ n# e`$ r  G d d          Z_Y nw xY wer
ddlaZbddlcmdZe  ejf        eg          Zh ejf        d          ZidZjdakdZld emd!<    ejn                    jo        Zpd" ee:          jq        v Zr	 	 d]d^d.Zsd_d1Zte,eju        evf         Zwe&d2         Zxd`d4Zydad8Zzdbd;Z{dcd=Z|dddAZ}dedfdFZ~ej        dgdH            Zej        dIdJdhdM            ZddJdidNZ e
j        dOP          dQ             Z G dR dSe3j                  Z G dT dU          Z	 dedjd[Z	 dedjd\ZdS )ka  Client for interacting with the LangSmith API.

Use the client to customize API keys / workspace ocnnections, SSl certs,
etc. for tracing.

Also used to create, read, update, and delete LangSmith resources
such as runs (~trace spans), datasets, examples (~records),
feedback (~metrics), projects (tracer sessions/groups), etc.

For detailed API documentation, visit: https://docs.smith.langchain.com/.
    )annotationsN)	signature)PriorityQueue)TYPE_CHECKINGAnyCallableDefaultDictDictIterableIteratorListLiteralMappingOptionalSequenceTupleTypeUnioncast)parse)adapters)	multipart)	TypeGuard)PoolKey)Retry)env)schemas)utils)_orjson)TracingQueueItem)tracing_control_thread_func)	warn_beta)_AUTO_SCALE_UP_NTHREADS_LIMIT_BLOCKSIZE_BYTES_SIZE_LIMIT_BYTES)MultipartPartsAndContext join_multipart_parts_and_context)SerializedFeedbackOperationSerializedRunOperation#combine_serialized_queue_operationsserialize_feedback_dictserialize_run_dict<serialized_feedback_operation_to_multipart_parts_and_context7serialized_run_operation_to_multipart_parts_and_context)
dumps_json)ZoneInfoc                      e Zd ZdZdS )r0   zIntroduced in python 3.9.N)__name__
__module____qualname____doc__     L/var/www/html/ai-engine/env/lib/python3.11/site-packages/langsmith/client.pyr0   r0   g   s        ''''r7   r0   	evaluatorzurllib3.connectionpool	x-api-keyFr6   ztuple[Dict, ...]	EMPTY_SEQkey_blocksize   dataseturl_or_tokenUnion[str, uuid.UUID]api_urlstr	num_partsintkindreturnTuple[str, str]c                   	 t          | t          j                  st          j        |           r|t          |           fS n# t          $ r Y nw xY wt          j        t          |                     }|j                            d          }t          |          |k    r||          }t          |d           nt          j        d| d|            |j        dk    rd}n|j        dk    rd	}||fS )
z*Parse a public dataset URL or share token./ztoken parts)varzInvalid public z URL: zsmith.langchain.comhttps://api.smith.langchain.comzbeta.smith.langchain.comz$https://beta.api.smith.langchain.com)
isinstanceuuidUUIDrC   
ValueErrorurllib_parseurlparsepathsplitlen_as_uuidls_utilsLangSmithUserErrornetloc)r@   rB   rD   rF   
parsed_url
path_parts
token_uuids          r8   _parse_token_or_urlr]   {   s   lDI.. 	.$)L2I2I 	.C----	.    &s<'8'899J&&s++J
:)##
+
/////)*VD*V*V*V*VWWW1113		8	8	88Js   >A 
AAurlboolc                    	 t          j        |           j                            d          d         }|                    d          S # t
          $ r Y dS w xY w)zCheck if the URL is langchain hosted.

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

    Returns:
    -------
    bool
        True if the URL is langchain hosted, False otherwise.
    :r   zlangchain.comF)rQ   urlsplitrY   rT   endswith	Exception)r^   rY   s     r8   _is_langchain_hostedre      sa    &s++288==a@///   uus   AA	 	
AA)toolchainllm	retriever	embeddingpromptparserr   c                    t          dg ddddd          } t          j                            d          }t	          t          t          |                    d                              d	k    }|rd
| d<   t          j	        di | S )zGet the default retry configuration.

    If urllib3 version is 1.26 or greater, retry on all methods.

    Returns:
    -------
    Retry
        The default retry configuration.
       )i  i  i    i        ?FT)totalstatus_forcelistbackoff_factorraise_on_redirectraise_on_statusrespect_retry_after_headerurllib3.)      Nallowed_methodsr6   )
dict	importlibmetadataversiontuplemaprE   rT   rW   LangSmithRetry)retry_paramsurllib3_versionuse_allowed_methodss      r8   _default_retry_configr      s     222#'  L  (00;;OC)>)>s)C)C D DEEP /*.&'"22\222r7   sessionrequests.SessionNonec                b    t                               d           |                                  dS )zjClose the session.

    Parameters
    ----------
    session : Session
        The session to close.
    zClosing Client.sessionN)loggerdebugclose)r   s    r8   close_sessionr      s(     LL)***MMOOOOOr7   api_keyOptional[str]c                n    |s0t          |           r#t          j        dt          j                   dS dS dS )a  Verify API key is provided if url not localhost.

    Parameters
    ----------
    api_url : str
        The API URL.
    api_key : str or None
        The API key.

    Raises:
    ------
    LangSmithUserError
        If the API key is not provided when using the hosted service.
    z8API key must be provided when using hosted LangSmith APIN)re   warningswarnrW   LangSmithMissingAPIKeyWarningrB   r   s     r8   _validate_api_key_if_hostedr      sW       (( 	MJ6     	 	r7   float | Nonec                     t          j        d          } | dS t          |           }|dk     s|dk    rt          j        d|           |S )zjGet the tracing sampling rate.

    Returns:
    -------
    float
        The tracing sampling rate.
    TRACING_SAMPLING_RATENr   ry   zELANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: )rW   get_env_varfloatrX   )sampling_rate_strsampling_rates     r8   _get_tracing_sampling_rater      ss     !,-DEE t+,,MqMA--)%"% %
 
 	
 r7   _write_api_urlsOptional[Dict[str, str]]Dict[str, str]c                   | p&t          j        t          j        dd                    } i }|                                 D ]\  }}|                                }|st          j        d          |                                                    d                              d                              d          }|                                                    d                              d          }t          ||           |||<   |S )NLANGSMITH_RUNS_ENDPOINTSz{}zFLangSmith runs API URL within LANGSMITH_RUNS_ENDPOINTS cannot be empty"'rJ   )
jsonloadsosgetenvitemsstriprW   rX   rstripr   )r   processed_write_api_urlsr^   r   processed_urlprocessed_api_keys         r8   _get_write_api_urlsr     s   % 
	,d33* *O  "'--// 	D 	DW		 	-X   &++--33C88>>sCCJJ3OO#MMOO11#66<<SAA#M3DEEE2C //##r7   valueID_TYPErK   	uuid.UUIDc                    	 t          | t          j                  st          j        |           n| S # t          $ r#}|pd}t	          j        | d|            |d }~ww xY w)Nr   z* must be a valid UUID or UUID string. Got )rM   rN   rO   rP   rW   rX   )r   rK   es      r8   rV   rV     s~    '1%'C'CNtyN   nW)EEeEE
 
	s   /2 
AAAOptional[Union[str, uuid.UUID]]c                    d S Nr6   )r   s    r8   _ensure_uuidr   (  s    GJsr7   Taccept_nullr   Optional[uuid.UUID]c                   d S r   r6   r   r   s     r8   r   r   ,  s	     #r7   c               R    | |rd S t          j                    S t          |           S r   )rN   uuid4rV   r   s     r8   r   r   2  s,    } 	4z||E??r7   ry   maxsizec                n    t          j        |           }|j                            d          d         }|S )Nra   r   )rQ   rR   rY   rT   )r^   rZ   hosts      r8   
_parse_urlr   :  s2    &s++J""3''*DKr7   c                  h     e Zd Zg dZej        ej        ej        ej        dfd fdZd fd	Z	 xZ
S )_LangSmithHttpAdapter)max_retriesconfig_pool_connections_pool_maxsize_pool_block
_blocksizei @  pool_connectionsrE   pool_maxsizer   Union[Retry, int, None]
pool_blockr_   	blocksizerG   r   c                ^    || _         t                                          ||||           d S r   )r   super__init__)selfr   r   r   r   r   	__class__s         r8   r   z_LangSmithHttpAdapter.__init__K  s1     $)<jQQQQQr7   Fc                ^    t           r
| j        |d<    t                      j        |||fi |S )Nr   )URLLIB3_SUPPORTS_BLOCKSIZEr   r   init_poolmanager)r   connectionsr   blockpool_kwargsr   s        r8   r   z&_LangSmithHttpAdapter.init_poolmanagerV  s:    % 	7'+K$'uww'WeSS{SSSr7   )r   rE   r   rE   r   r   r   r_   r   rE   rG   r   F)r2   r3   r4   	__attrs__requests_adaptersDEFAULT_POOLSIZEDEFAULT_RETRIESDEFAULT_POOLBLOCKr   r   __classcell__)r   s   @r8   r   r   A  s          I !2 B->/@/P,>	R 	R 	R 	R 	R 	R 	RT T T T T T T T T Tr7   r   c                     e Zd ZdZg dZ	 dddddddddddddddZddZdd Zedd!            Z	edd"            Z
edd$            Zedd&            Zd d(Zdd+Zdd,dddd-d.dd?Zdd@ddEZddFdGdHddMZdej        j        dNddYZddej        j        dZdd]Z	 	 ddddZed	df            Zd^dgd
dkZdddlddsZdduZddvZddxZdd{Z	 	 dd^d|ddZ ddZ!ddZ"	 	 dd^d|ddZ#ddddZ$dddddddddd	ddZ%ddZ&ddZ'	 dddZ(dddddddddddddddddddZ)dddddddddddddddddddZ*dddddÄZ+ddĜddƄZ,ddǄZ-ddȄZ.d dɄZ/	 dd!d̄Z0	 dd"d̈́Z1	 dddΜd#d҄Z2	 dddΜd#dӄZ3d$dԄZ4d%dՄZ5dd֜d&dلZ6dddddڜd'dބZ7ddd^dddߜd(dZ8ddddddd)dZ9d*dZ:d+dZ; e<j=        d          ddd^dd,d            Z>ddd-dZ?dddd.dZ@	 	 	 	 	 	 	 	 d/d0dZA e<j=        d          dddd1d            ZBdej        j        ddddd2dZCdddd3d ZD e<j=        d          dddd4d            ZE	 dddΜd5dZF	 dddΜd6dZGddddddd	d7dZH e<j=        d          dddd8d            ZIdddd9dZJdddddd:dZKdddddd;dZLdddd<dZMd=dZN e<j=        d          	 	 	 	 d>d?d$            ZO e<j=        d          	 	 	 	 d>d@d)            ZP	 	 	 dAdBd*ZQdddddddd+dCd3ZR e<j=        d          	 	 	 	 	 	 	 	 d/dDd:            ZSdd;dEd<ZT	 	 	 	 	 	 dFd=dddd>dGdCZUeVdDdEdHdF            ZWeVddGdIdI            ZXddddddJdJdKZYddddddLdKdPZZdLdQZ[ddddRdMdUZ\ddd^dVdNdZZ]dOd\Z^dPd`Z_ddadQdfZ`ddd^dgdRdnZa	 	 	 dAddodSdtZbddd^dgdTdvZcdddddejd        je        ddddwddddddxdUdZfddddddVdZgdWdZhddddddXdZidYdZj	 dddddddZdZkddddd[dZldddd\dZmddd]dZndddddd^dZodddd_dZpd`dZqdddadZrdbdZsdcdZtdddZudedZvdddddddfdZwdddddd^ddddgdǄZxdddddd^ddddgdȄZydhdʄZzdid̈́Z{	 djdkdτZ|dldӄZ}dmdԄZ~dndՄZdodքZdodׄZdؐd=dd^ej        j        dddڜdpdZdqdZdddd^ddrdZdddsdZdddddddtdZdudZd^ddvdZdd=d^ddwdZd^ddxdZddDddddddydZdzdZdS ({  Clientz.Client for interacting with the LangSmith API.)__weakref__rB   r   retry_config
timeout_msr   _get_data_type_cached_web_url
_tenant_idtracing_sample_rate_filtered_post_uuidstracing_queue_anonymizer_hide_inputs_hide_outputs_infor   	_settings_manual_cleanup_pyo3_clientNT)r   r   r   web_urlr   auto_batch_tracing
anonymizerhide_inputshide_outputsinfoapi_urlsrB   r   r   r   Optional[Retry]r   %Optional[Union[int, Tuple[int, int]]]r   r   Optional[requests.Session]r   r_   r    Optional[Callable[[dict], dict]]r   -Optional[Union[Callable[[dict], dict], bool]]r   r   /Optional[Union[dict, ls_schemas.LangSmithInfo]]r   r   rG   r   c               L   |r|rt          j        d          t          j        d          st          j        d          r(t          j        d          rt          j        d          t	                      | _        t                      | _        t          |          | _	        | j	        r>t          t          | j	                            | _        | j	        | j                 | _        n_t          j        |          | _        t          j        |          | _        t!          | j        | j                   | j        | j        i| _	        |pt#                      | _        t'          |t(                    r||fn|pd| _        || _        d| _        |r|nt1          j                    }|| _        |t'          |t6          j                  r|nt7          j        di || _        t=          j        | t@          | j                   tC          j"        t@          |           |rTtG                      | _$        tK          j&        tN          t=          j(        |           f          )                                 nd| _$        tU          | j        tV          tX          d	z   
          }| j        -                    d|           | j        -                    d|            t]          j/        d          | j0                  | _1        || _2        |	|	nt          j3        d          dk    | _4        |
|
nt          j3        d          dk    | _5        d| _6        t          j3        d          d}	 ddl7}n?# tp          $ r2}tr          :                    dtw          |                     Y d}~nd}~ww xY w|rrd}d}d}d	}	 |<                    | j        | j        ||||          | _6        n?# tz          $ r2}tr          :                    dtw          |                     Y d}~nd}~ww xY wd| _>        d| _?        dS )a_	  Initialize a Client instance.

        Parameters
        ----------
        api_url : str or None, default=None
            URL for the LangSmith API. Defaults to the LANGCHAIN_ENDPOINT
            environment variable or https://api.smith.langchain.com if not set.
        api_key : str or None, default=None
            API key for the LangSmith API. Defaults to the LANGCHAIN_API_KEY
            environment variable.
        retry_config : Retry or None, default=None
            Retry configuration for the HTTPAdapter.
        timeout_ms : int, tuple[int, int], or None, default=None
            Timeout for the HTTPAdapter. Can also be a 2-tuple of
            (connect timeout, read timeout) to set them separately.
        web_url : str or None, default=None
            URL for the LangSmith web app. Default is auto-inferred from
            the ENDPOINT.
        session: requests.Session or None, default=None
            The session to use for requests. If None, a new session will be
            created.
        anonymizer : Optional[Callable[[dict], dict]]
            A function applied for masking serialized run inputs and outputs,
            before sending to the API.
        hide_inputs: Whether to hide run inputs when tracing with this client.
            If True, hides the entire inputs. If a function, applied to
            all run inputs when creating runs.
        hide_outputs: Whether to hide run outputs when tracing with this client.
            If True, hides the entire outputs. If a function, applied to
            all run outputs when creating runs.
        info: Optional[ls_schemas.LangSmithInfo]
            The information about the LangSmith API. If not provided, it will
            be fetched from the API.
        api_urls: Optional[Dict[str, str]]
            A dictionary of write API URLs and their corresponding API keys.
            Useful for multi-tenant setups. Data is only read from the first
            URL in the dictionary. However, ONLY Runs are written (POST and PATCH)
            to all URLs in the dictionary. Feedback, sessions, datasets, examples,
            annotation queues and evaluation results are only written to the first.

        Raises:
        ------
        LangSmithUserError
            If the API key is not provided when using the hosted service.
            If both api_url and api_urls are provided.
        z-You cannot provide both api_url and api_urls.LANGSMITH_ENDPOINTLANGCHAIN_ENDPOINTr   z]You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS.)i'  i_ N)targetargsry   )r   r   r   zhttp://zhttps://
   r   HIDE_INPUTStrueHIDE_OUTPUTSUSE_PYO3_CLIENTr   zaFailed to import `langsmith_pyo3` when PyO3 client was requested, falling back to Python impl: %si@B d     z|Failed to instantiate `langsmith_pyo3.BlockingTracingClient` when PyO3 client was requested, falling back to Python impl: %sFr6   )@rW   rX   r   r   r   r   setr   r   r   nextiterrB   r   get_api_urlget_api_keyr   r   r   rM   rE   r   r   r   requestsSessionr   
ls_schemasLangSmithInfor   weakreffinalizer   atexitregisterr   r   	threadingThread_tracing_control_thread_funcrefstartr   r$   r#   mount	functools	lru_cache_get_data_typer   r   r   r   r   r   langsmith_pyo3ImportErrorr   warningreprBlockingTracingClientrd   r   r   )r   rB   r   r   r   r   r   r   r   r   r   r   r   session_adapterr&  r   queue_capacity
batch_sizebatch_timeout_millisworker_threadss                        r8   r   zClient.__init__w  s   |  	x 	-?  
 I*++	/1y9M/N/N	i233	 -0  
 $>#?#? 47EE!<O=
 =
  	@T%9 : :;;DL*.*>t|*LDLL#/88DL#/88DL'dlCCC$(L$,#?D (C,A,C,C *c**2Z$$0 0 	
  /3%=778+;+=+= |z$
0HII| D)11D11 	

 	}dl;;;x000 
	&:G//D3 k$'')	  
 egggg!%D ()& 7:
 
 
 	9g...:w///%DY%8%D%D%D&
 &
" & & K%m44> 	 ' L%n55? 	 ! 122>!N%%%%%   6GG         !* 
'+$!"(6(L(L&",&) )D%% !   NNZQ        EI$s0   M# #
N-(NN-)O 
P!(PPrC   c                    | j         }d| dS )zReturn an HTML representation of the instance with a link to the URL.

        Returns:
        -------
        str
            The HTML representation of the instance.
        z	<a href="z6", target="_blank" rel="noopener">LangSmith Client</a>)	_host_url)r   links     r8   _repr_html_zClient._repr_html_0  s     ~W4WWWWr7   c                    d| j          dS )zReturn a string representation of the instance with a link to the URL.

        Returns:
        -------
        str
            The string representation of the instance.
        zClient (API URL: ))rB   r   s    r8   __repr__zClient.__repr__;  s     34<2222r7   c                *    t          | j                  S r   )r   rB   r7  s    r8   _hostzClient._hostE  s    $,'''r7   c                @    t          j        | j        | j                  S )zThe web host url.)rW   get_host_urlr   rB   r7  s    r8   r2  zClient._host_urlI  s     $T]DLAAAr7   r   c                V    dt           j         dd}| j        r| j        |t          <   |S )zGet the headers for the API request.

        Returns:
        -------
        Dict[str, str]
            The headers for the API request.
        zlangsmith-py/application/json)z
User-AgentAccept)	langsmith__version__r   	X_API_KEY)r   headerss     r8   _headerszClient._headersN  s?     B)*?AA(
 
 < 	.!%GIr7   ls_schemas.LangSmithInfoc           	        | j         	 |                     ddddi| j        d         dz  | j        d         dz  f	          }t          j        |           t          j        di |                                | _         na# t          $ rT}t          
                    d
| j         dt          |                      t          j                    | _         Y d}~nd}~ww xY w| j         S )zGet the information about the LangSmith API.

        Returns:
        -------
        Optional[ls_schemas.LangSmithInfo]
            The information about the LangSmith API, or None if the API is
                not available.
        NGETz/infor?  r>  r   r  ry   )rC  timeoutzFailed to get info from : r6   )r   request_with_retriesr   rW   raise_for_status_with_textr  r  r   BaseExceptionr   r(  rB   r)  )r   responser   s      r8   r   zClient.info_  s    :844%'9:!_Q/$68JT8QR	 5   3H==='5HHHH

  8 8 8Ht|HHtAwwHH   (577





	8
 zs   A5A? ?
C	A
CCls_schemas.LangSmithSettingsc                    | j         R|                     dd          }t          j        |           t	          j        di |                                | _         | j         S )zzGet the settings for the current tenant.

        Returns:
            dict: The settings for the current tenant.
        NrG  z	/settingsr6   )r   rJ  rW   rK  r  LangSmithSettingsr   )r   rM  s     r8   _get_settingszClient._get_settingsz  sZ     >!00DDH/999'9LLHMMOOLLDN~r7   content_lengthOptional[int]c                    || j         d S t          t          j        | j                   }|j        }|sd S |                    d          }|d S ||k    r	d| d| dS d S )Nsize_limit_byteszThe content length of z) bytes exceeds the maximum size limit of z bytes.)r   r   r  r  batch_ingest_configget)r   rR  r   bic
size_limits        r8   _content_above_sizezClient._content_above_size  s    !TZ%74J,dj99& 	4WW/00
4J&&= = =)3= = = tr7   ry    )request_kwargsstop_after_attemptretry_on	to_ignorehandle_response_contextmethod0Literal['GET', 'POST', 'PUT', 'PATCH', 'DELETE']pathnamer\  Optional[Mapping]r]  rE   r^  'Optional[Sequence[Type[BaseException]]]r_  r`  1Optional[Callable[[requests.Response, int], Any]]ra  kwargsr   requests.Responsec              &   |pi }d| j         d         dz  | j         d         dz  fi||	di | j        |                    di           |	                    di           i}|dk    r.d|v r*d|vr&|d                             d	          sd
|d         d	<   t          j                    t          j        t          | j                            g}
g |pdt          j        t          j	        t          j
        fR }g |pdR }d}t          |          D ]}	 	 t          j        t          |
          5   | j        j        ||                    d          s
| j        |z   n|fddi|}ddd           n# 1 swxY w Y   t          j        |           |c S # t&          j        j        $ r_}t,                              d|           |dz   |k    r d|z  t1          j                    dz  z   }t3          j        |           Y d}~d}~wt&          j        $ r}|z| |dz   |k     r |||dz             }|rY d}~*|j        dk    r,t          j
        d| d| dt;          |           |           |j        dk    rt          j	        d| | d|           |j        dk    r)t          j        d| dt;          |           |           |j        dk    r)t          j        d| dt;          |           |           |j        dk    r)t          j         d | dt;          |           |           |j        d!k    r)t          j!        d"| dt;          |           |           t          j"        d#| d| dt;          |                     t          j#        d#| d| dt;          |                     d}~wt&          j$        $ r"}| j        d$k    rd%nd&}	 tK          |j        r,t          |j        j&                            d'                    nd(          }| '                    |          }|r|}n# tP          $ r d}Y nw xY w|j        r!|j        j&                            d)          pd(nd(}|dd*         |d+d         }}d,tS          dtU          |          d-z
            z  }| | | }t          j        d.| d| d| dt;          |           d/| d0| |           |d}~wtV          $ r}tY          |j-                  }tU          |          dk    r|d         nd(}|.                    d1d2          }|rXd3/                    t          |d                   g|gz   d4 tU          |          dk    r
|dd         ng D             z             }n|}t          j"        d#| d| d| |           |d}~ww xY w# |$ r1}|$t,                              d|           |cY d}~c S Y d}~d}~wt          j        $ r |dz   |k    r |k	 ta          |j&                            d5d6                    }nA# tV          $ r4}t,          1                    d7t;          |                     d8}Y d}~nd}~ww xY w|d|z  z  t1          j                    z   }t3          j        |           Y |$ r> |dz   |k    r d|z  t1          j                    dz  z   }t3          j        |           Y w xY wt          j"        d#| d| d9          ):aQ  Send a request with retries.

        Parameters
        ----------
        request_method : str
            The HTTP request method.
        pathname : str
            The pathname of the request URL. Will be appended to the API URL.
        request_kwargs : Mapping
            Additional request parameters.
        stop_after_attempt : int, default=1
            The number of attempts to make.
        retry_on : Sequence[Type[BaseException]] or None, default=None
            The exceptions to retry on. In addition to:
            [LangSmithConnectionError, LangSmithAPIError].
        to_ignore : Sequence[Type[BaseException]] or None, default=None
            The exceptions to ignore / pass on.
        handle_response : Callable[[requests.Response, int], Any] or None, default=None
            A function to handle the response and return whether to continue
            retrying.
        **kwargs : Any
            Additional keyword arguments to pass to the request.

        Returns:
        -------
        Response
            The response object.

        Raises:
        ------
        LangSmithAPIError
            If a server error occurs.
        LangSmithUserError
            If the request fails.
        LangSmithConnectionError
            If a connection error occurs.
        LangSmithError
            If the request fails.
        rH  r   r  ry   rC  rG  datafilesContent-Typer>  )r   r6   NhttpstreamFzPassing on exception %sr>   rp   i  zServer error caused failure to  z in LangSmith API. ro   z(Client took too long to send request to i  zRate limit exceeded for z. i  zAuthentication failed for i  zResource not found for i  zConflict for z
Failed to rL   z'Please confirm your LANGCHAIN_ENDPOINT.z(Please confirm your internet connection.zContent-Lengthr[  r;      *   z#Connection error caused failure to z
Content-Length: z

API Key: r   zsession (project)
c                ,    g | ]}t          |          S r6   rC   ).0args     r8   
<listcomp>z/Client.request_with_retries.<locals>.<listcomp>_  s    WWWCs3xxWWWr7   zretry-after30zInvalid retry-after header: %s   z in LangSmith API.)2r   rD  rW  rW   FilterLangSmithRetryFilterPoolFullWarningrC   r:  LangSmithConnectionErrorLangSmithRequestTimeoutLangSmithAPIErrorrangefilter_logs_urllib3_loggerr   request
startswithrB   rK  r  
exceptionsReadTimeoutr   r   randomtimesleep	HTTPErrorstatus_coder)  LangSmithRateLimitErrorLangSmithAuthErrorLangSmithNotFoundErrorLangSmithConflictErrorLangSmithErrorrX   ConnectionErrorrE   rC  rZ  rP   maxrU   rd   listr  replacejoinr   r(  )r   rb  rd  r\  r]  r^  r_  r`  ra  rh  logging_filters	retry_on_
to_ignore_rM  idxr   
sleep_timeshould_continuerecommendationrR  size_recr   prefixsuffixfillermasked_api_keyr  msgemsgretry_afters                                 r8   rJ  zClient.request_with_retries  s8
   j (-2*T14?13E3LM	
	
 	
  - $$Y33 **Y++		
 	
 eOO.((~--"9-11.AA . 9KN9%n5)++*DJ@@@
6
n"6
 10*6
 6
	 7Lb6K6K
+,, S	 S	CRw!-oOO 
 
#74<#7" (0':':6'B'B!.x 7 7%-	$ 	$ $)	$ -	$ 	$
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 7AAA#OOO*6   LL!:A>>>Qw"444!"C6=??S+@!AJJz***HHHH) 0 0 0+*6"Qw);;;2A/(CRSG2T2T#2 !-$,HHHH#/366"*"<!.& !. !.$,!. !.3777!. $,!. !.# #  &1S88"*"B!96 !9#+!9 !9.6!9 !9# #  &1S88"*"B!.8 !. !.tAww !.#+!. !.# #  &1S88"*"=!.X !. !.a !.#+!. !.# #  &1S88"*"A!.( !. !.d1gg !.#+!. !.# #  &1S88"*"A S S SDGG S S S# #  #+"9!3V !3 !3h !3 !3)-a!3 !3# #  '9* * *( * * $Q* *    /        <+LLL BAG #

.), y$C	 1 5 56F G GHHH!#* *
 $(#;#;N#K#K# 6-5N% . . .)-. EFIU	)--k::@bSU  &-RaR['"##,FF C3w<<!+;$<$<=F(.%@%@%@%@N";&f & &x & &.<& & GG& & .<& & '5	&
 $& &   !   <<D%(YY]]$q''C++i1DEEC ##yy a\\N"e$WWD		ADHHSUWWWX     #"1&V & &h & &4 &#& &     $ $ $'LL!:A>>>#OOOOOOOO ('''' 3 ( ( (7000')&+H,<,@,@PT,U,U&V&V$ ) ) )< GG   ')) *AsF2V]__D
;'''''   7000Vv}'<=

:&&& %>>>(>>>
 
 	
s   F16E3'F3E7	7F:E7	;FW*AH?WWN>6W<FN>>WS.!AP=<S.=Q	S.QB"S..W;CV>>WW[5W7)[57[5(X?>[5?
Y=	*Y83[58Y==3[53>[54[5paramsrS   r  Optional[dict]Iterator[dict]c             #  l  K   |r|                                 ni }|                    dd          }|                    dd          |d<   	 ||d<   |                     d||          }|                                }|sdS |E d{V  t	          |          |d         k     rdS |t	          |          z  }k)	a2  Get a paginated list of items.

        Parameters
        ----------
        path : str
            The path of the request URL.
        params : dict or None, default=None
            The query parameters.

        Yields:
        ------
        dict
            The items in the paginated list.
        offsetr   limitr  TrG  r  N)copyrW  rJ  r   rU   )r   rS   r  params_r  rM  r   s          r8   _get_paginated_listzClient._get_paginated_list  s      " $*1&++---rXq))";;w44	! &GH00 1  H
 MMOOE 5zzGG,,, c%jj F!	!r7   POSTruns)bodyrequest_methoddata_keyr  r  Literal['GET', 'POST']r  c             #  x  K   |r|                                 ni }	 |                     ||dt          |          i          }|                                }|sdS |                    |          sdS ||         E d{V  |                    d          }|sdS |                    d          sdS |d         |d<   )a  Get a cursor paginated list of items.

        Parameters
        ----------
        path : str
            The path of the request URL.
        body : dict or None, default=None
            The query body.
        request_method : str, default="post"
            The HTTP request method.
        data_key : str, default="runs"

        Yields:
        ------
        dict
            The items in the paginated list.
        Trk  r\  Ncursorsr  cursor)r  rJ  _dumps_jsonr   rW  )	r   rS   r  r  r  r  rM  response_bodyr  s	            r8   _get_cursor_paginated_listz!Client._get_cursor_paginated_list  s      2 "&-$))+++2	000K00  1  H %MMOOM   $$X.. $X........#''	22G ;;v&&  'GH'	0r7   )description	data_typedfpd.DataFramename
input_keysSequence[str]output_keysr  r  Optional[ls_schemas.DataType]ls_schemas.Datasetc                   t          j                    }|                    |d           |                    d           |                     d|f|||||          S )a  Upload a dataframe as individual examples to the LangSmith API.

        Parameters
        ----------
        df : pd.DataFrame
            The dataframe to upload.
        name : str
            The name of the dataset.
        input_keys : Sequence[str]
            The input keys.
        output_keys : Sequence[str]
            The output keys.
        description : str or None, default=None
            The description of the dataset.
        data_type : DataType or None, default=DataType.kv
            The data type of the dataset.

        Returns:
        -------
        Dataset
            The uploaded dataset.

        Raises:
        ------
        ValueError
            If the csv_file is not a string or tuple.
        F)indexr   zdata.csv)r  r  r  r  r  )ioBytesIOto_csvseek
upload_csv)r   r  r  r  r  r  r  csv_files           r8   upload_dataframezClient.upload_dataframe  sj    J :<<
		(%	(((a"!##  
 
 	
r7   )r  r  r  r  "Union[str, Tuple[str, io.BytesIO]]c               6   ||d}|r||d<   |r||d<   |rt          j        |          |d<   t          t          j                              |d<   t          |t                    rFt          |d          5 }d|i}	|                     dd	||	
          }
ddd           n# 1 swxY w Y   n@t          |t                    r|                     dd	|d|i
          }
nt          d          t          j
        |
           |
                                }d|v rWd|d         v rMt          |t                    r|n|d         }|                    d          d         }t          d| d          t          j        di || j        |                                 dS )a~  Upload a CSV file to the LangSmith API.

        Parameters
        ----------
        csv_file : str or Tuple[str, BytesIO]
            The CSV file to upload. If a string, it should be the path
            If a tuple, it should be a tuple containing the filename
            and a BytesIO object.
        input_keys : Sequence[str]
            The input keys.
        output_keys : Sequence[str]
            The output keys.
        name : str or None, default=None
            The name of the dataset.
        description : str or None, default=None
            The description of the dataset.
        data_type : DataType or None, default=DataType.kv
            The data type of the dataset.

        Returns:
        -------
        Dataset
            The uploaded dataset.

        Raises:
        ------
        ValueError
            If the csv_file is not a string or tuple.
        )r  r  r  r  r  idrbfiler  z/datasets/upload)rk  rl  Nz"csv_file must be a string or tupledetailzalready existsr   rJ   Dataset z already existsr2  r   r6   )rW   get_enum_valuerC   rN   r   rM   openrJ  r   rP   rK  r   rT   r  Datasetr2  _get_optional_tenant_id)r   r  r  r  r  r  r  rk  ffile_rM  result	file_names                r8   r  zClient.upload_csv  s3   P %&
 
  	 DL 	."-D 	C ( 7	 B BD&&T
h$$ 	Ch%% 44&	 5                 %(( 	C00"x(	 1  HH ABBB+H555v"2fX6F"F"F$.x$=$=N8A;I!,,R0IB	BBBCCC! 
 

n3355
 
 
 
 	
s   5BB#&B#Frun3Union[ls_schemas.Run, dict, ls_schemas.RunLikeDict]updater  r|   c                   t          |d          r2t          t          |d                    r|                                }nt	          t          |          }d|vrt          j                    |d<   n8t          |d         t                    rt          j	        |d                   |d<   d|v rE|d         =|rt          j        |d                   |d<   |                     |d                   |d<   d|v rE|d         =|rt          j        |d                   |d<   |                     |d                   |d<   |sF|                    d          s1t          j                            t          j        j                  |d<   d|v rJ|                    d          d	vr|                    dd           n|d                             d
d           |S )a  Transform the given run object into a dictionary representation.

        Args:
            run (Union[ls_schemas.Run, dict]): The run object to transform.
            update (bool, optional): Whether the payload is for an "update" event.
            copy (bool, optional): Whether to deepcopy run inputs/outputs.

        Returns:
            dict: The transformed run object as a dictionary.
        r|   r  inputsNoutputs
start_time
serializedrun_type)rh   rk   graph)hasattrcallablegetattrr|   r   rN   r   rM   rC   rO   rW   deepish_copy_hide_run_inputs_hide_run_outputsrW  datetimenowtimezoneutcpop)r   r  r  r  
run_creates        r8   _run_transformzClient._run_transform^  s   $ 3 	)HWS&-A-A$B$B 	)"xxzzJJdCJz!!#z||Jt
4(#.. 	;#yD)9::Jtz!!j&:&F S'/'<Z=Q'R'R
8$#'#8#8H9M#N#NJx 
""z)'<'H U(0(=j>S(T(T
9%$($:$::i;P$Q$QJy! 	Tjnn\:: 	T'/'8'<'<X=N=R'S'SJ|$ :%%~~j)) 2  
 |T2222 <(,,Wd;;;r7   Sequence[dict]c                   t          j                    }| D ]}t          t          |                    di                     }|                    di           }i |||d<   |                    di           t          j                    }                    fd|                                D                        d S )Nextraruntimer~   c                $    i | ]\  }}|v	||S r6   r6   )rx  kvr~   s      r8   
<dictcomp>z.Client._insert_runtime_env.<locals>.<dictcomp>  s)    RRR$!Q@Q@QA@Q@Q@Qr7   )ls_envget_runtime_environmentr   r|   
setdefaultget_langchain_env_var_metadatar  r   )r  runtime_envr  	run_extrar  langchain_metadatar~   s         @r8   _insert_runtime_envzClient._insert_runtime_env  s    466 
	 
	JT:#8#8"#E#EFFI%00B??G#=k#=W#=Ii &11*bAAH!'!F!H!HOORRRR"4":":"<"<RRR   
	 
	r7   patchIterable[dict]r
  
list[dict]c               &   | j         t          |          S |rWg }|D ]P}t          |d                   }|| j        vr|                    |           6| j                            |           Q|S g }|D ]}|d         |                    d          k    r|                    d          | j        vst          j                    | j         k     r|                    |           o| j                            t          |d                              |S )Nr  trace_id)	r   r  rV   r   appendremoverW  r  add)r   r  r
  sampledr  run_ids         r8   _filter_for_samplingzClient._filter_for_sampling  s)    #+:: 	G = =!#d),,!:::NN3''''-44V<<<<NG 
G 
G I!4!444
++43LLL]__t'???NN3''''-11(3t92E2EFFFFNr7   )project_namerevision_idr  Dict[str, Any]r  
RUN_TYPE_Tr  r  c                  |p&|                     dt          j                              }i |||||d}|                     |g          sdS |||d         d         d<   |                     |d          }|                     |g           |                    d	          |                    d
          | j        4t          |d                   |d<   | j        	                    |           dS | j
        @t          d|          }| j
                            t          |d
         |                     dS |                     |           dS |                     |           dS )az  Persist a run to the LangSmith API.

        Parameters
        ----------
        name : str
            The name of the run.
        inputs : Dict[str, Any]
            The input values for the run.
        run_type : str
            The type of the run, such as tool, chain, llm, retriever,
            embedding, prompt, or parser.
        revision_id : ID_TYPE or None, default=None
            The revision ID of the run.
        **kwargs : Any
            Additional keyword arguments.

        Raises:
        ------
        LangSmithUserError
            If the API key is not provided when using the hosted service.
        session_name)r  r  r  r  Nr  r~   r  Fr  r  dotted_orderr  post)r  rW   get_tracer_projectr  r  r  rW  r   rC   
create_runr   r,   putr    _create_run)	r   r  r  r  r  r  rh  r  serialized_ops	            r8   r  zClient.create_run  s   > $ 
vzz'))(
 (



( 
 
 

 ((*66 	F"=HJw
+M:(( ) 
 

 	  *... NN:&&2~..: , $'z$'7#8#8
4 !,,Z88888#/ 26: F F"&&$Z%?OO       ,,,,,Z(((((r7   r  c                    | j                                         D ]N\  }}i | j        t          |i}|                     d| dt          |          |dt          j        f           Od S )Nr  /runsrk  rC  )r\  r_  )r   r   rD  rB  rJ  r  rW   r  )r   r  rB   r   rC  s        r8   r!  zClient._create_run	  s     $ 4 : : < < 
	 
	GW;;	7;;G%%!!!'
33&    $:< &    
	 
	r7   c                    | j         du ri S | j        r6t          j        t	          |                    }|                     |          S | j         du r|S |                      |          S NTF)r   r   r   r   r  )r   r  json_inputss      r8   r  zClient._hide_run_inputs  sr    $$I 	1!-F(;(;<<K##K000%%M  (((r7   r  c                    | j         du ri S | j        r6t          j        t	          |                    }|                     |          S | j         du r|S |                      |          S r'  )r   r   r   r   r  )r   r  json_outputss      r8   r  zClient._hide_run_outputs   sr    %%I 	2"=W)=)=>>L##L111&&N!!'***r7   opsList[SerializedRunOperation]c                   g g d}|D ]Z}t          |t                    rt          j        |j                  }|j        rt          j        |j                  |d<   |j        rt          j        |j                  |d<   |j        rt          j        |j                  |d<   |j	        rt                              d           ||j                                     d|j         d|j         t          j        |          f           t          |t"                    rt                              d           2t                              d	t'          |                     \| j        }|j        pi                     d
          pt.          }t1          j        t4                    }t1          j        t4                    }d}	t7          t8          t:          d                  ddg          D ].}
t1          j        ||
                   }|r|	dk    r|	t?          |d         d                   z   |k    rr|                      t          j        |          d|
 dd!                    ||
                               d}	|"                                 |"                                 |#                                \  }}|	t?          |          z  }	||
                             t          j        |                     ||
                             |           |0|	r_d!                    d |$                                D                       }|                      t          j        |          d|z              d S d S )N)r  r
  r  r  eventszBAttachments are not supported when use_multipart_endpoint is Falseztrace=z,id=z;Feedback operations are not supported in non-multipart modez&Unknown item type in tracing queue: %srU  r   r  r
  ry   ru  rI  ; )ra  c              3  P   K   | ]!\  }}| d d                     |           V  "dS )rI  r/  N)r  rx  r  r  s      r8   	<genexpr>z/Client._batch_ingest_run_ops.<locals>.<genexpr>j  s>      WW41a1 6 6		! 6 6WWWWWWr7   )%rM   r)   r   r   _noner  Fragmentr  r.  attachmentsr   r(  	operationr  r  r  dumpsr(   errortyper   rV  rW  r%   collectionsdefaultdictr  r   r   r   dequerU   _post_batch_ingest_runsr  clearpopleftr   )r   r+  ids_and_partial_bodyop	curr_dictr   rU  body_chunkscontext_ids	body_sizekey
body_dequecurr_id	curr_bodycontexts                  r8   _batch_ingest_run_opszClient._batch_ingest_run_ops*  s    
 
 	  	Q 	QB"455 Q#M"(33	9 F*1*:29*E*EIh': H+2+;BJ+G+GIi(9 F*1*:29*E*EIh'> NN#   %R\2996bk66ru66i8P8PQ    B ;<< QQ    EtBxxPPPP y 4:??
 
  	 /:.Ed.K.K.9.Ed.K.K	W_568IJJ 	1 	1C$*+?+DEEJ 1MM!C
1a(8$9$99<LLL00k22!Jc!J!JTYY{37G-H-H!J!J 1    !"I%%'''%%'''%/%7%7%9%9"S^^+	C ''(8(C(CDDDC ''000  1   	iiWW;CTCTCVCVWWWWWG((k**TG^ )     	 	r7   )pre_sampledcreateGOptional[Sequence[Union[ls_schemas.Run, ls_schemas.RunLikeDict, Dict]]]rL  c                   |s|sdS  fd|pt           D             } fd|pt           D             }|D ]@}|                    d          r|                    d          st          j        d          A|D ]@}|                    d          r|                    d          st          j        d          A|s,                     |          }                     |d          }|s|sdS                      ||z              t          t          t                   t          t          t          j        d	 |D             d
 |D                                                     }                     |           dS )  Batch ingest/upsert multiple runs in the Langsmith system.

        Args:
            create (Optional[Sequence[Union[ls_schemas.Run, RunLikeDict]]]):
                A sequence of `Run` objects or equivalent dictionaries representing
                runs to be created / posted.
            update (Optional[Sequence[Union[ls_schemas.Run, RunLikeDict]]]):
                A sequence of `Run` objects or equivalent dictionaries representing
                runs that have already been created and should be updated / patched.
            pre_sampled (bool, optional): Whether the runs have already been subject
                to sampling, and therefore should not be sampled again.
                Defaults to False.

        Returns:
            None

        Raises:
            LangsmithAPIError: If there is an error in the API request.

        Note:
            - The run objects MUST contain the dotted_order and trace_id fields
                to be accepted by the API.
        Nc                >    g | ]}                     |d           S )Fr  r  rx  r  r   s     r8   rz  z,Client.batch_ingest_runs.<locals>.<listcomp>  s9     
 
 
58D%00
 
 
r7   c                @    g | ]}                     |d d          S )TF)r  r  rR  rS  s     r8   rz  z,Client.batch_ingest_runs.<locals>.<listcomp>  s>     
 
 
 Du==
 
 
r7   r  r  z:Batch ingest requires trace_id and dotted_order to be set.Tr	  c              3  6   K   | ]}t          d |          V  dS r  Nr,   rx  r  s     r8   r2  z+Client.batch_ingest_runs.<locals>.<genexpr>  s-      QQS+FC88QQQQQQr7   c              3  6   K   | ]}t          d |          V  dS r
  NrW  rX  s     r8   r2  z+Client.batch_ingest_runs.<locals>.<genexpr>  s-      RRc+GS99RRRRRRr7   )r<   rW  rW   rX   r  r  r   r   r)   r*   r  	itertoolsrg   rK  )r   rM  r  rL  create_dictsupdate_dictsr  serialized_opss   `       r8   batch_ingest_runszClient.batch_ingest_runso  s   D  	f 	F
 
 
 
<B<Oi
 
 

 
 
 
*
 
 
   	 	C77:&& cggn.E.E 1P     	 	C77:&& cggn.E.E 1P  
  	O44\BBL44\4NNL 	L 	F  !<=== '(/OQQLQQQRR\RRR   

 

 	"">22222r7   bytesc          	     0   | j                                         D ]\  }}	 |                     d| d|i | j        t          |idt
          j        fd|           C# t          $ r}	 t          j	        t          |          |          }d                    |                                          }t                              d|            n:# t          $ r- t                              dt          |                      Y nw xY wY d }~d }~ww xY wd S )Nr  z/runs/batchr%  rn   )r\  r_  r]  ra  r[  zFailed to batch ingest runs: )r   r   rJ  rD  rB  rW   r  rd   	tracebackformat_exception_onlyr9  r  r   r   r(  r)  )r   r  ra  rB   r   r   exc_desc_linesexc_descs           r8   r=  zClient._post_batch_ingest_runs  so    $ 4 : : < < 	N 	NGWN))+++ $$"m$%w$ $$ $  (>@'(% *      N N NN%.%DT!WWa%P%PN!ww~66==??HNN#M8#M#MNNNN  N N NNN#L477#L#LMMMMMNN!	N 	Ns6   <A
D(A&CD4DDDDD@list[Union[SerializedRunOperation, SerializedFeedbackOperation]]c                   g }|D ]}t          |t                    r#|                    t          |                     :t          |t                    r#|                    t          |                     rt                              dt          |                     t          |          }|r| 
                    |           d S d S )Nz+Unknown operation type in tracing queue: %s)rM   r)   r  r.   r(   r-   r   r8  r9  r'   _send_multipart_req)r   r+  partsrA  acc_multiparts        r8   _multipart_ingest_opszClient._multipart_ingest_ops  s     13 
	V 
	VB"455 	VKBOO    B ;<< VPQSTT    JDQSHHUUUU8?? 	4$$]33333	4 	4r7   c          	         |s|sdS  fd|pt           D             } fd|pt           D             }|rD|D ]@}|                    d          r|                    d          st          j        d          A~|rD|D ]@}|                    d          r|                    d          st          j        d          A~|re|rcd |D             }g }|D ]O}|d	         |v r.|                                D ]\  }	}
|
|
||d	                  |	<   :|                    |           P~|}|s,                     |          }                     |d
          }|s|sdS                      |                                |           t          t          t          j        d |D             d |D                                           }                     |           dS )rP  Nc                :    g | ]}                     |          S r6   rR  rS  s     r8   rz  z+Client.multipart_ingest.<locals>.<listcomp>  s'    PPPS++C00PPPr7   c                >    g | ]}                     |d           S )T)r  rR  rS  s     r8   rz  z+Client.multipart_ingest.<locals>.<listcomp>  s9     
 
 
69DD11
 
 
r7   r  r  zNMultipart ingest requires trace_id and dotted_order to be set in create dicts.zNMultipart ingest requires trace_id and dotted_order to be set in update dicts.c                     i | ]}|d          |S r  r6   rX  s     r8   r   z+Client.multipart_ingest.<locals>.<dictcomp>(  s    CCCsCIsCCCr7   r  Tr	  c              3  6   K   | ]}t          d |          V  dS rV  rW  rX  s     r8   r2  z*Client.multipart_ingest.<locals>.<genexpr>B  s-      MM'44MMMMMMr7   c              3  6   K   | ]}t          d |          V  dS rZ  rW  rX  s     r8   r2  z*Client.multipart_ingest.<locals>.<genexpr>C  s-      NN#'55NNNNNNr7   )r<   rW  rW   rX   r   r  r  r  r*   r  r[  rg   rk  )r   rM  r  rL  r\  r]  r  create_by_idstandalone_updatesr  r  r^  s   `           r8   multipart_ingestzClient.multipart_ingest  s   D  	& 	FPPPPF<OiPPP
 
 
 
=C=Py
 
 
  	#  wwz** #''.2I2I "56    	#  wwz** #''.2I2I "56    	.L 	.CClCCCL-/#  t9,, #		 ; ;1=9:LT3A6; '--c2222-L 	O44\BBL44\4NNL 	L 	F  ...  ... =MMMMMNNNNN  
 
 	"">22222r7   rn   )attemptsaccr&   rv  c                  |j         }|j        }| j                                        D ]\  }}t	          d|dz             D ]}	 t          j        |t                    }|j        dk    r|	                                }	n|}	| 
                    d| d|	i | j        t          |d|j        idd|            n%# t          j        $ r Y  nt          j        t          j        t          j        f$ r3}
||k    rt&                              d	|
            nY d }
~
Y d }
~
d }
~
wt*          $ r}	 t-          j        t1          |          |          }d
                    |                                          }t&                              d	|            n:# t*          $ r- t&                              d	t7          |                      Y nw xY wY d }~  d S d }~ww xY wd S )Nry   )boundaryi -1r  z/runs/multipartrm  r%  )r\  r]  ra  z!Failed to multipart ingest runs: r[  )ri  rJ  r   r   r  rqtb_multipartMultipartEncoderBOUNDARYrU   	to_stringrJ  rD  rB  content_typerW   r  r  r  r  r   r(  rd   rb  rc  r9  r  r   r)  )r   rw  rv  ri  ra  rB   r   r  encoderrk  excr   rd  re  s                 r8   rh  zClient._send_multipart_reqK  sj   	; $ 4 : : < < *	 *	GWQ1-- ) )(,=ehWWWG{j00&0022&--"333$(("&-( )7 .0D( (( ( ,-!) .    E6   EE54. ! ! !
 h'P3'P'PQQQQ  RQQQQ !   V)2)HaRS)T)T#%77>#:#:#A#A#C#C'U8'U'UVVVV$ V V V'T4PQ77'T'TUUUUUV FFFFFFFE*	 *	sJ   A4B<<G%G4$D""G0A&FG4G	GG	GG)	r  end_timer8  r  r  r.  r  tagsr5  r  r   r  Optional[datetime.datetime]r8  Optional[Dict]r.  Optional[Sequence[dict]]r  r  Optional[List[str]]r5  >Optional[Dict[str, tuple[str, bytes] | ls_schemas.Attachment]]c       	           t          |d          ||                    dd          |                    dd          |                    dd          |	||                    dd          |                    dd          d	}|
r|
|d	<   | j        duo|d         duo	|d         du}|                     |gd
          sdS ||                                |d<   nCt
          j                            t
          j        j                                                  |d<   |||d<   || 	                    |          |d<   |.|st          j        |          }|                     |          |d<   |||d<   |d         r|                     |g           |rH| j        At          d|          }| j                            t!          |d         |                     dS |                     |           dS )ah  Update a run in the LangSmith API.

        Parameters
        ----------
        run_id : str or UUID
            The ID of the run to update.
        name : str or None, default=None
            The name of the run.
        end_time : datetime or None
            The end time of the run.
        error : str or None, default=None
            The error message of the run.
        inputs : Dict or None, default=None
            The input values for the run.
        outputs : Dict or None, default=None
            The output values for the run.
        events : Sequence[dict] or None, default=None
            The events for the run.
        extra : Dict or None, default=None
            The extra information for the run.
        tags : List[str] or None, default=None
            The tags for the run.
        attachments: dict[str, ls_schemas.Attachment] or None, default=None
            A dictionary of attachments to add to the run. The keys are the attachment names,
            and the values are Attachment objects containing the data and mime type.
        **kwargs : Any
            Kwargs are ignored.
        r  r  Nparent_run_idr  
session_idr  )	r  r  r  r  r  r  r  r  r  r5  Tr	  r  r8  r  r  r.  r  r
  )r6  payload)rV   r  r   r  	isoformatr  r  r  r  r  rW   r  r  r  r,   r   r    _update_run)r   r  r  r  r8  r  r  r.  r  r  r5  rh  rk  use_multipartr"  s                  r8   
update_runzClient.update_runz  s=   \ 68,,

:t44#ZZ>>"JJ~t<< **\488"JJ~t<<
 
 
 
  	."-Dd* 1Z ,1 ^$D0	 	 (($t(<< 	F'1133D'044X5F5JKKUUWWD!DM!226::DN  9"/88"44W==DO#DN= 	-$$dV,,, 	#T/;.$OOOM"" n!5}EE     T"""""r7   
run_updatec                    | j                                         D ]J\  }}i | j        t          |i}|                     d| d|d          t          |          |d           Kd S )NPATCH/runs/r  r%  r  )r   r   rD  rB  rJ  r  )r   r  rB   r   rC  s        r8   r  zClient._update_run  s     $ 4 : : < < 	 	GW-7 G
 %%44*T"244'
33&    &    	 	r7   ls_schemas.Runc                   |                      |j                  }t          j        t                    }i }t          |d           D ]P}|j        t          j        d|j	         d          ||j                 
                    |           |||j	        <   Q|                    |j	        g           |_        |                                D ]\  }}|||         _        |S )aI  Load child runs for a given run.

        Parameters
        ----------
        run : Run
            The run to load child runs for.

        Returns:
        -------
        Run
            The run with loaded child runs.

        Raises:
        ------
        LangSmithError
            If a child run has no parent.
        rp  c                    | j         S r   )r  )rs    r8   <lambda>z)Client._load_child_runs.<locals>.<lambda>  s    !. r7   )rF  Nz
Child run z has no parent)	list_runschild_run_idsr:  r;  r  sortedr  rW   r  r  r  r  
child_runsr   )r   r  r  treemapr  	child_runr  childrens           r8   _load_child_runszClient._load_child_runs  s    $ ^^s'8^99
@K@WA
 A
 13((
 
 
 	+ 	+I &.-.W9<.W.W.WXXXI+,33I>>>!*D SVR00 ' 	/ 	/FH&.DL##
r7   load_child_runsc                    |                      ddt          |d                     }t          j        di |                                d| j        i}|r|j        r|                     |          }|S )a6  Read a run from the LangSmith API.

        Parameters
        ----------
        run_id : str or UUID
            The ID of the run to read.
        load_child_runs : bool, default=False
            Whether to load nested child runs.

        Returns:
        -------
        Run
            The run.
        rG  r  r  r2  r6   )rJ  rV   r  Runr   r2  r  r  )r   r  r  rM  r  s        r8   read_runzClient.read_run	  s    " ,,8HVX6688
 
 nIIx}}II$.III 	-s0 	-'',,C
r7   )
project_idr  r  r  reference_example_idqueryfiltertrace_filtertree_filteris_rootr  r  r8  run_idsselectr  r  +Optional[Union[ID_TYPE, Sequence[ID_TYPE]]]#Optional[Union[str, Sequence[str]]]r  Optional[ID_TYPE]r  r  r  r  r  r  Optional[bool]r  r  r  Optional[Sequence[ID_TYPE]]r  Optional[Sequence[str]]r  Iterator[ls_schemas.Run]c             +     K   g }t          |t          j        t          f          r|                    |           n*t          |t
                    r|                    |           |9t          |t                    r|g}|                     fd|D                        g d}|p|}|r|nd||r|gnd||||	|
||r|                                nd||||d|}d |                                D             }t           
                    d|                    D ]/\  }}t          j        d
i |d j        iV  ||d	z   |k    r dS 0dS )a/  List runs from the LangSmith API.

        Parameters
        ----------
        project_id : UUID or None, default=None
            The ID(s) of the project to filter by.
        project_name : str or None, default=None
            The name(s) of the project to filter by.
        run_type : str or None, default=None
            The type of the runs to filter by.
        trace_id : UUID or None, default=None
            The ID of the trace to filter by.
        reference_example_id : UUID or None, default=None
            The ID of the reference example to filter by.
        query : str or None, default=None
            The query string to filter by.
        filter : str or None, default=None
            The filter string to filter by.
        trace_filter : str or None, default=None
            Filter to apply to the ROOT run in the trace tree. This is meant to
            be used in conjunction with the regular `filter` parameter to let you
            filter runs by attributes of the root run within a trace.
        tree_filter : str or None, default=None
            Filter to apply to OTHER runs in the trace tree, including
            sibling and child runs. This is meant to be used in conjunction with
            the regular `filter` parameter to let you filter runs by attributes
            of any run within a trace.
        is_root : bool or None, default=None
            Whether to filter by root runs.
        parent_run_id : UUID or None, default=None
            The ID of the parent run to filter by.
        start_time : datetime or None, default=None
            The start time to filter by.
        error : bool or None, default=None
            Whether to filter by error status.
        run_ids : List[str or UUID] or None, default=None
            The IDs of the runs to filter by.
        limit : int or None, default=None
            The maximum number of runs to return.
        **kwargs : Any
            Additional keyword arguments.

        Yields:
        ------
        Run
            The runs.

        Examples:
        --------
        .. code-block:: python

            # List all runs in a project
            project_runs = client.list_runs(project_name="<your_project>")

            # List LLM and Chat runs in the last 24 hours
            todays_llm_runs = client.list_runs(
                project_name="<your_project>",
                start_time=datetime.now() - timedelta(days=1),
                run_type="llm",
            )

            # List root traces in a project
            root_runs = client.list_runs(project_name="<your_project>", is_root=1)

            # List runs without errors
            correct_runs = client.list_runs(project_name="<your_project>", error=False)

            # List runs and only return their inputs/outputs (to speed up the query)
            input_output_runs = client.list_runs(
                project_name="<your_project>", select=["inputs", "outputs"]
            )

            # List runs by run ID
            run_ids = [
                "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836",
                "9398e6be-964f-4aa4-8ae9-ad78cd4b7074",
            ]
            selected_runs = client.list_runs(id=run_ids)

            # List all "chain" type runs that took more than 10 seconds and had
            # `total_tokens` greater than 5000
            chain_runs = client.list_runs(
                project_name="<your_project>",
                filter='and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))',
            )

            # List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1
            good_extractor_runs = client.list_runs(
                project_name="<your_project>",
                filter='eq(name, "extractor")',
                trace_filter='and(eq(feedback_key, "user_score"), eq(feedback_score, 1))',
            )

            # List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0
            complex_runs = client.list_runs(
                project_name="<your_project>",
                filter='and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))',
            )

            # List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds
            tagged_runs = client.list_runs(
                project_name="<your_project>",
                filter='and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))',
            )
        Nc                F    g | ]}                     |           j        S r  )read_projectr  )rx  r  r   s     r8   rz  z$Client.list_runs.<locals>.<listcomp>  s-    RRRT"""558RRRr7   )app_pathr  completion_costcompletion_tokensr  r  r8  r.  r  feedback_statsfirst_token_timer  r  r  r  r  parent_run_idsprompt_costprompt_tokensr  r  r  r  statusr  
total_costtotal_tokensr  )r   r  reference_exampler  r  r  r  r  
parent_runr  r8  r  tracer  c                    i | ]
\  }}|||S r   r6   r1  s      r8   r   z$Client.list_runs.<locals>.<dictcomp>  s    KKKtq!Q]a]]]r7   /runs/queryr  r2  ry   r6   )rM   rN   rO   rC   r  r  extendr  r   	enumerater  r  r  r2  )r   r  r  r  r  r  r  r  r  r  r  r  r  r8  r  r  r  rh  project_idsdefault_select
body_queryir  s   `                      r8   r  zClient.list_runs"  s     | j49c"233 	+z****
D)) 	+z***#,,, . ,~RRRR\RRR  
 
 
< )>&1;{{t *>H%&&D(&'4>H*..000D!&
 &
" #&

& LKz'7'7'9'9KKK
++M
+KK
 
 	 	FAs .AA3AA$.AAAAAA QUe^^	 	r7   )r  r  r  r  project_namesr  reference_example_idsr  r  r8  r  r  r  r  r  data_source_typer  Optional[List[ID_TYPE]]r  r  r  r  r  r  c                   ddl m}m} |pg }|rl |            5  fd|D             } ||          D ].}|                    |                                j                   /	 ddd           n# 1 swxY w Y   ||||||||	|
||||||d}d |                                D             }                     ddd	t          |          i
          }t          j
        |           |                                S )a0  Get aggregate statistics over queried runs.

        Takes in similar query parameters to `list_runs` and returns statistics
        based on the runs that match the query.

        Args:
            id (Optional[List[ID_TYPE]]): List of run IDs to filter by.
            trace (Optional[ID_TYPE]): Trace ID to filter by.
            parent_run (Optional[ID_TYPE]): Parent run ID to filter by.
            run_type (Optional[str]): Run type to filter by.
            projects (Optional[List[ID_TYPE]]): List of session IDs to filter by.
            reference_example (Optional[List[ID_TYPE]]): List of reference example IDs to filter by.
            start_time (Optional[str]): Start time to filter by.
            end_time (Optional[str]): End time to filter by.
            error (Optional[bool]): Filter by error status.
            query (Optional[str]): Query string to filter by.
            filter (Optional[str]): Filter string to apply.
            trace_filter (Optional[str]): Trace filter string to apply.
            tree_filter (Optional[str]): Tree filter string to apply.
            is_root (Optional[bool]): Filter by root run status.
            data_source_type (Optional[str]): Data source type to filter by.

        Returns:
            Dict[str, Any]: A dictionary containing the run statistics.
        r   ThreadPoolExecutoras_completedc                H    g | ]}                     j        |           S r  )submitr  )rx  r  executorr   s     r8   rz  z(Client.get_run_stats.<locals>.<listcomp>  s<        OOD$5DOII  r7   N)r  r  r  r  r   r  r  r  r8  r  r  r  r  r  r  c                    i | ]
\  }}|||S r   r6   r1  s      r8   r   z(Client.get_run_stats.<locals>.<dictcomp>0  s    EEEDAqq}1a}}}r7   r  z/runs/statsrk  r  )concurrent.futuresr  r  r  r  r  r   rJ  r  rW   rK  r   )r   r  r  r  r  r  r  r  r  r  r8  r  r  r  r  r  r  r  r  futuresfuturer  rM  r  s   `                      @r8   get_run_statszClient.get_run_stats  s   Z 	HGGGGGGG!'R 	;##%% ;     -   +l733 ; ;F&&v}}'9::::;; ; ; ; ; ; ; ; ; ; ; ; ; ; ; $ "!6$ (& 0
 
& FEGMMOOEEE,,G,, - 
 
 	+H555}}s   A
A22A69A6)r  r  ls_schemas.RunBasec                  t          |dd          x}rnt          |dd          x}r|                     |          j        }nQ||}nL||                     |          j        }n.t          j                    }|                     |          j        }t          |d          }| j         d|                                  d| d|j         dS )	a  Get the URL for a run.

        Not recommended for use within your agent runtime.
        More for use interacting with runs after the fact
        for data analysis or ETL workloads.

        Parameters
        ----------
        run : Run
            The run.
        project_name : str or None, default=None
            The name of the project.
        project_id : UUID or None, default=None
            The ID of the project.

        Returns:
        -------
        str
            The URL for the run.
        r  Nr  r  z/o/z/projects/p/z/r/z
?poll=true)r  r  r  rW   r  rV   r2  _get_tenant_id)r   r  r  r  r  r  session_id_s          r8   get_run_urlzClient.get_run_url<  s   6 !lD999: 
	I$S.$???\ 	I***EEHJJ##JJ%***EEHJJ#688L***EEHJz<88~ $ $$"5"5"7"7 $ $[ $ $$ $ $	
r7   )share_idr  c               @   t          |d          }t          |          |pt          t          j                              d}|                     dd| d| j        |          }t          j        |           |                                d         }| j	         d| d	S )
zGet a share link for a run.r  )r  share_tokenPUTr  /sharerC  r   r  /public//r)
rV   rC   rN   r   rJ  rD  rW   rK  r   r2  )r   r  r  run_id_rk  rM  r  s          r8   	share_runzClient.share_runh  s    68,,'ll#8s4:<<'8'8
 
 ,,$W$$$M	 - 
 
 	+H555mmoom4.99+9999r7   c                    |                      ddt          |d           d| j                  }t          j        |           dS )zDelete share link for a run.DELETEr  r  r  rC  NrJ  rV   rD  rW   rK  )r   r  rM  s      r8   unshare_runzClient.unshare_runy  sU    ,,7Xfh//777M - 
 

 	+H55555r7   c                    |                      ddt          |d           d| j                  }t          j        |           |                                }|d|vrdS | j         d|d          d	S )
zRetrieve the shared link for a specific run.

        Args:
            run_id (ID_TYPE): The ID of the run.

        Returns:
            Optional[str]: The shared link for the run, or None if the link is not
            available.
        rG  r  r  r  r  Nr  r  r  )rJ  rV   rD  rW   rK  r   r2  )r   r  rM  r  s       r8   read_run_shared_linkzClient.read_run_shared_link  s     ,,7Xfh//777M - 
 

 	+H555>]&884.CC&*?CCCCr7   c                P    |                      t          |d                    }|duS )zGet share state for a run.r  N)r  rV   )r   r  r3  s      r8   run_is_sharedzClient.run_is_shared  s*    ((&()C)CDD4r7   r  Union[ID_TYPE, str]c                "   t          |dd          \  }}d| d}||dt          |d           z  }|                     d	|| j        
          }t	          j        |           t          j        di |                                d| j	        iS )Get shared runs.r[  r  rF   r  /runNrJ   r  rG  r  r2  r6   )
r]   rV   rJ  rD  rW   rK  r  r  r   r2  )r   r  r  _r\   rS   rM  s          r8   read_shared_runzClient.read_shared_run  s     ,K%HHH:*****422444D,,M - 
 

 	+H555~JJJJ4>JJJJr7   c              #     K   |rd|ini }t          |dd          \  }}|                     d| d|          D ]}t          j        d
i |d| j        iV  d	S )r  r  r[  r  r  r  r  r  r2  Nr6   )r]   r  r  r  r2  )r   r  r  r  r  r\   r  s          r8   list_shared_runszClient.list_shared_runs  s       #*1gr+K%HHH:22.z...T 3 
 
 	B 	BC .AA3AA$.AAAAAAA	B 	Br7   dataset_name
dataset_idr  ls_schemas.DatasetShareSchemac                  ||t          d          ||                     |          j        }|                     ddt	          |d           d| j                  }t          j        |           |                                }t          t          j        i |d	| j         d
t	          |d         d           di          S )a  Retrieve the shared schema of a dataset.

        Args:
            dataset_id (Optional[ID_TYPE]): The ID of the dataset.
                Either `dataset_id` or `dataset_name` must be given.
            dataset_name (Optional[str]): The name of the dataset.
                Either `dataset_id` or `dataset_name` must be given.

        Returns:
            ls_schemas.DatasetShareSchema: The shared schema of the dataset.

        Raises:
            ValueError: If neither `dataset_id` nor `dataset_name` is given.
        N/Either dataset_id or dataset_name must be givenr  rG  
/datasets/r  r  r  r^   r  r  zresponse.share_token/d)rP   read_datasetr  rJ  rV   rD  rW   rK  r   r   r  DatasetShareSchemar2  )r   r  r  rM  ds        r8   read_dataset_shared_schemaz!Client.read_dataset_shared_schema  s    ( ,"6NOOO***EEHJ,,C*l;;CCCM - 
 

 	+H555MMOO)$. J JAm,.DEEJ J J 
 
 	
r7   c          	        ||t          d          ||                     |          j        }dt          |          i}|                     ddt          |d           d| j        |          }t          j        |           |	                                }t          t          j        i |d	| j         d
|d          di          S )zGet a share link for a dataset.Nr  r  r  r  r  r  r  r^   r  r  r	  )rP   r
  r  rC   rJ  rV   rD  rW   rK  r   r   r  r  r2  )r   r  r  rk  rM  r  s         r8   share_datasetzClient.share_dataset  s     ,"6NOOO***EEHJ#j//
 ,,C*l;;CCCM	 - 
 
 	+H555--//)IqI%DNHHAm4DHHHII
 
 	
r7   c                    |                      ddt          |d           d| j                  }t          j        |           dS )z Delete share link for a dataset.r  r  r  r  r  Nr  )r   r  rM  s      r8   unshare_datasetzClient.unshare_dataset  sU    ,,C*l;;CCCM - 
 

 	+H55555r7   c                    |                      ddt          |d           d| j                  }t          j        |           t          j        di |                                | j        d| ddS )	zGet shared datasets.rG  r  r  	/datasetsr  r	  )r2  _public_pathr6   )	rJ  rV   rD  rW   rK  r  r  r   r2  )r   r  rM  s      r8   read_shared_datasetzClient.read_shared_dataset	  s    
 ,,Fx];;FFFM - 
 

 	+H555! 
 
mmoo
n3K333
 
 
 
 	
r7   example_idsr  List[ls_schemas.Example]c                    i }|d |D             |d<                         ddt          |d           d j        |          }t          j        |            fd	|                                D             S )
zGet shared examples.Nc                ,    g | ]}t          |          S r6   rw  )rx  r  s     r8   rz  z/Client.list_shared_examples.<locals>.<listcomp>	  s    :::CGG:::r7   r  rG  r  r  	/examplesrC  r  c                D    g | ]}t          j        di |d j        iS )r2  r6   )r  Exampler2  )rx  r?   r   s     r8   rz  z/Client.list_shared_examples.<locals>.<listcomp>"	  sG     
 
 
 CCCCDNCCC
 
 
r7   )rJ  rV   rD  rW   rK  r   )r   r  r  r  rM  s   `    r8   list_shared_exampleszClient.list_shared_examples	  s     "::k:::F4L,,Fx];;FFFM	 - 
 
 	+H555
 
 
 
#==??
 
 
 	
r7   )r  r  name_containsr  dataset_share_tokenr   (Iterator[ls_schemas.TracerSessionResult]c             #     K   |||d}t          |d          }t          |                     d| d|                    D ]/\  }}	t          j        d	i |	d| j        iV  ||dz   |k    r dS 0dS )
aL  List shared projects.

        Args:
            dataset_share_token : str
                The share token of the dataset.
            project_ids : List[ID_TYPE], optional
                List of project IDs to filter the results, by default None.
            name : str, optional
                Name of the project to filter the results, by default None.
            name_contains : str, optional
                Substring to search for in project names, by default None.
            limit : int, optional

        Yields:
            TracerSessionResult: The shared projects.
        )r  r  r   r!  r  z/datasets/sessionsr  r2  Nry   r6   )rV   r  r  r  TracerSessionResultr2  )
r   r!  r  r  r   r  r  r  r  projects
             r8   list_shared_projectszClient.list_shared_projects'	  s      2 $TMRR24IJJ#$$:;::: %  
 
 	 	JAw 0UU7UUdnUUUUUU QUe^^	 	r7   )r  r~   upsertproject_extrareference_dataset_idr~   r'  r(  r)  ls_schemas.TracerSessionc               ~   | j          d}|}|r
i |pi d|i}|||t          t          j                              d}	i }
|rd|
d<   |||	d<   |                     d|i | j        d	d
it          |	                    }t          j        |           t          j
        di |                                d| j        iS )a  Create a project on the LangSmith API.

        Parameters
        ----------
        project_name : str
            The name of the project.
        project_extra : dict or None, default=None
            Additional project information.
        metadata: dict or None, default=None
            Additional metadata to associate with the project.
        description : str or None, default=None
            The description of the project.
        upsert : bool, default=False
            Whether to update the project if it already exists.
        reference_dataset_id: UUID or None, default=None
            The ID of the reference dataset to associate with the project.

        Returns:
        -------
        TracerSession
            The created project.
        	/sessionsr~   )r  r  r  r  Tr'  Nr)  r  rm  r>  rC  rk  r2  r6   )rB   rC   rN   r   rJ  rD  r  rW   rK  r  TracerSessionr   r2  )r   r  r  r~   r'  r(  r)  endpointr  r  r  rM  s               r8   create_projectzClient.create_projectL	  s	   @ l--- 	<;;j(;;E &djll##	 
  
  	$#F8++?D'(,,It}In6HIIT""	 - 
 
 	+H555'TT(--//TTT^TTTTr7   )r  r  r~   r(  r  c               n   | j          dt          |d           }|}|r
i |pi d|i}||||r|                                ndd}	|                     d|i | j        ddit          |	          	          }
t          j        |
           t          j	        di |

                                d
| j        iS )a  Update a LangSmith project.

        Parameters
        ----------
        project_id : UUID
            The ID of the project to update.
        name : str or None, default=None
            The new name to give the project. This is only valid if the project
            has been assigned an end_time, meaning it has been completed/closed.
        description : str or None, default=None
            The new description to give the project.
        metadata: dict or None, default=None

        project_extra : dict or None, default=None
            Additional project information.

        Returns:
        -------
        TracerSession
            The updated project.
        
/sessions/r  r~   N)r  r  r  r  r  rm  r>  r-  r2  r6   )rB   rV   r  rJ  rD  r  rW   rK  r  r.  r   r2  )r   r  r  r  r~   r(  r  r/  r  r  rM  s              r8   update_projectzClient.update_project	  s    > lRRhz<.P.PRR 	<;;j(;;E&08B**,,,d	 
  
 ,,It}In6HIIT""	 - 
 
 	+H555'TT(--//TTT^TTTTr7   r   c                   | j         | j         S 	 |                     ddddi          }|                                }t          |t                    rFt          |          dk    r3t          j        di |d         d| j        i}|j	        | _         | j         S nA# t          $ r4}t                              dt          |          d	
           Y d }~nd }~ww xY wd S )NrG  r,  r  ry   r  r   r2  z*Failed to get tenant ID from LangSmith: %sTexc_infor6   )r   rJ  r   rM   r  rU   r  r$  r2  	tenant_idrd   r   r   r)  )r   rM  r  tracer_sessionr   s        r8   r  zClient._get_optional_tenant_id	  s   ?&?"	00{GQ< 1  H ]]__F&$'' 'CKK!OO!+!? " "Qi" "+/>" " " #1":& 	 	 	LL<d1ggPT         	 ts   BB 
C$*CCr   c                Z    |                                  }|t          j        d          |S )NzNo tenant ID found)r  rW   r  )r   r7  s     r8   r  zClient._get_tenant_id	  s1    0022	)*>???r7   )r  r  )r  r  include_statsr:  ls_schemas.TracerSessionResultc                  d}ddi}||dt          |d           z  }n|||d<   nt          d          ||d	<   |                     d
||          }|                                }t	          |t
                    rKt          |          dk    rt          j        d| d          t          j
        di |d         d| j        iS t          j
        di |                                d| j        iS )a-  Read a project from the LangSmith API.

        Parameters
        ----------
        project_id : str or None, default=None
            The ID of the project to read.
        project_name : str or None, default=None
            The name of the project to read.
                Note: Only one of project_id or project_name may be given.
        include_stats : bool, default=False
            Whether to include a project's aggregate statistics in the response.

        Returns:
        -------
        TracerSessionResult
            The project.
        r,  r  ry   NrJ   r  r  'Must provide project_name or project_idr:  rG  r  r   zProject 
 not foundr2  r6   )rV   rP   rJ  r   rM   r  rU   rW   r  r  r$  r2  )r   r  r  r:  rS   r  rM  r  s           r8   r  zClient.read_project	  s7   2 ")1!<\::<<<DD%)F6NNFGGG"/,,UD,HHfd## 	Y6{{a57|777   1XXF1IXXXXXX- 
 
mmoo
 
)-
 
 
 	
r7   r  c               b    	 |                      |           n# t          j        $ r Y dS w xY wdS )aM  Check if a project exists.

        Parameters
        ----------
        project_name : str
            The name of the project to check for.
        project_id : str or None, default=None
            The ID of the project to check for.

        Returns:
        -------
        bool
            Whether the project exists.
        r  FT)r  rW   r  )r   r  r  s      r8   has_projectzClient.has_project	  sK    "	<8888. 	 	 	55	ts    ,,c          	         t          j        dt          d           ddlm}m} ddl}                     ||dg d	          }g }g } fd
}	d}
d} |            5 }g }|D ]v}d|j        id |j	        
                                D             d |j        pi 
                                D             |j        r!|j        |j        z
                                  nd|j        |j        d}|j        r6|                    d |j        
                                D                        |j        r|                    |j                   n#t(                              d|j         d           t-          |          |
z  dk    r=||||
z            x}r.|                    |                    |	|                     ||
z  }|                    |           x||d         r1|                    |                    |	||d                              ddd           n# 1 swxY w Y    |j        |                              d          }d  ||          D             }|r; |j        |                              d          }|                    |dd          } |j        |                    d                    S )aS  Read the record-level information from an experiment into a Pandas DF.

        Note: this will fetch whatever data exists in the DB. Results are not
        immediately available in the DB upon evaluation run completion.

        Returns:
        --------
        pd.DataFrame
            A dataframe containing the test results.
        z%Function get_test_results is in beta.r>   )
stacklevelr   r  NT)r  r  r  r  r8  r  r  r  )r  r  r  r  c                H                         |           }d |D             S )Nr  c                j    g | ]0}d |j         id |j        pi                                 D             1S )
example_idc                     i | ]\  }}d | |S )z
reference.r6   r1  s      r8   r   zNClient.get_test_results.<locals>.fetch_examples.<locals>.<listcomp>.<dictcomp>C
  s'    WWWtq!'A''WWWr7   )r  r  r   rx  examples     r8   rz  zCClient.get_test_results.<locals>.fetch_examples.<locals>.<listcomp>@
  s\       
  !'*WW8M27T7T7V7VWWW  r7   )list_examples)batchexamplesr   s     r8   fetch_examplesz/Client.get_test_results.<locals>.fetch_examples>
  s<    ))e)<<H 
  (   r7   2   rF  c                     i | ]\  }}d | |S )zinput.r6   r1  s      r8   r   z+Client.get_test_results.<locals>.<dictcomp>O
  s$    DDD41a|||QDDDr7   c                     i | ]\  }}d | |S )zoutputs.r6   r1  s      r8   r   z+Client.get_test_results.<locals>.<dictcomp>P
  s$    OOOTQ~!~~qOOOr7   )execution_timer8  r  c                F    i | ]\  }}d | |                     d          S )z	feedback.avg)rW  r1  s      r8   r   z+Client.get_test_results.<locals>.<dictcomp>[
  s>        $1 ,OOQUU5\\  r7   zRun z has no reference example ID.c                @    g | ]}|                                 D ]}|S r6   )r  )rx  r  outputs      r8   rz  z+Client.get_test_results.<locals>.<listcomp>o
  sA     
 
 
V]]__
 
;AF
 
 
 
r7   )
left_indexright_indexrecords)orient)r   r   UserWarningr  r  r  pandasr  r  r  r   r  r  r  total_secondsr8  r  r  r  r  r   r(  rU   r  	DataFrame	set_indexmergejson_normalizeto_dict)r   r  r  r  r  pdr  resultsr  rM  r.  r  r  r  r  rowrK  	result_dfexample_outputs
example_dfs   `                   r8   get_test_resultszClient.get_test_results
  s     	3[Q	
 	
 	
 	
 	HGGGGGGG~~!%	 	 		  
 
 !	 	 	 	 	 
!! #	VXG $ $ !"8DD18>>3C3CDDD POaio25L5L5N5NOOO :"al2AACCC!W$   # JJ ()(8(>(>(@(@     ) O&&q'=>>>>NN#M!$#M#M#MNNN{##j0A55 +FVj5H,H IIu -x~u'M'MNNN*,s#### 677# Vx~{677?STTUUUG#	V #	V #	V #	V #	V #	V #	V #	V #	V #	V #	V #	V #	V #	V #	VH !BL))33LAA	
 
!-g!6!6
 
 
  	W%o66@@NNJ"((tQU(VVI !r !2!2)!2!D!DEEEs   F8H  H$'H$reference_dataset_namereference_freeOptional[Dict[str, Any]]"Iterator[ls_schemas.TracerSession]c	              #    K   d|t          |d          ndi}	|||	d<   |||	d<   |||	d<   ||t          d          ||	d<   n"| |                     |	          j        }||	d<   |||	d
<   |t	          j        |          |	d<   t          |                     d|	                    D ]/\  }
}t          j	        di |d| j
        iV  ||
dz   |k    r dS 0dS )aB  List projects from the LangSmith API.

        Parameters
        ----------
        project_ids : Optional[List[ID_TYPE]], optional
            A list of project IDs to filter by, by default None
        name : Optional[str], optional
            The name of the project to filter by, by default None
        name_contains : Optional[str], optional
            A string to search for in the project name, by default None
        reference_dataset_id : Optional[List[ID_TYPE]], optional
            A dataset ID to filter by, by default None
        reference_dataset_name : Optional[str], optional
            The name of the reference dataset to filter by, by default None
        reference_free : Optional[bool], optional
            Whether to filter for only projects not associated with a dataset.
        limit : Optional[int], optional
            The maximum number of projects to return, by default None
        metadata: Optional[Dict[str, Any]], optional
            Metadata to filter by.

        Yields:
        ------
        TracerSession
            The projects.
        r  Nr  r  r  r   zGOnly one of reference_dataset_id or reference_dataset_name may be givenreference_datasetr  rj  r~   r,  r  r2  ry   r6   )minrP   r
  r  r   r7  r  r  r  r.  r2  )r   r  r  r   r)  ri  rj  r  r~   r  r  r%  s               r8   list_projectszClient.list_projectsy
  sm     L (9S___s"
 "&F4L!F6N$&3F?#+%1 ;   +?F&''#/#'#4#43 $5 $ $ ! +?F&'%'5F#$!%H!5!5F:#$$[$@@
 
 	 	JAw *OOWOOOOOOOO QUe^^	 	r7   c                  |)t          |                     |          j                  }n|t          d          |                     ddt          |d           | j                  }t          j        |           dS )a  Delete a project from LangSmith.

        Parameters
        ----------
        project_name : str or None, default=None
            The name of the project to delete.
        project_id : str or None, default=None
            The ID of the project to delete.
        Nr  r=  r  r2  r  r  )	rC   r  r  rP   rJ  rV   rD  rW   rK  )r   r  r  rM  s       r8   delete_projectzClient.delete_project
  s     #T..L.IILMMJJFGGG,,=*l;;==M - 
 

 	+H55555r7   )r  r  inputs_schemaoutputs_schemar~   ls_schemas.DataTypers  rt  c                  ||j         t          j                                                                        |rd|indd}|||d<   |||d<   |||d<   |                     ddi | j        d	d
it          j        |                    }t          j	        |           t          j        di |                                | j        |                                 dS )a  Create a dataset in the LangSmith API.

        Parameters
        ----------
        dataset_name : str
            The name of the dataset.
        description : str or None, default=None
            The description of the dataset.
        data_type : DataType or None, default=DataType.kv
            The data type of the dataset.
        metadata: dict or None, default=None
            Additional metadata to associate with the dataset.

        Returns:
        -------
        Dataset
            The created dataset.
        r~   N)r  r  
created_atr  r  inputs_schema_definitionoutputs_schema_definitionr  r  rm  r>  r-  r  r6   )r   r  r  r  rJ  rD  r   r7  rW   rK  r  r  r   r2  r  )	r   r  r  r  rs  rt  r~   r?   rM  s	            r8   create_datasetzClient.create_dataset
  s   : !""+//11;;==/7Aj(++T	#
 #
 "%0GM"$2?G./%3AG/0,,It}In6HIIw''	 - 
 
 	+H555! 
 
mmoo
n3355
 
 
 
 	
r7   r  r  c               b    	 |                      ||           dS # t          j        $ r Y dS w xY w)ao  Check whether a dataset exists in your tenant.

        Parameters
        ----------
        dataset_name : str or None, default=None
            The name of the dataset to check.
        dataset_id : str or None, default=None
            The ID of the dataset to check.

        Returns:
        -------
        bool
            Whether the dataset exists.
        r{  TF)r
  rW   r  )r   r  r  s      r8   has_datasetzClient.has_dataset  sJ    "	<JOOO4. 	 	 	55	s    ..c                  d}ddi}||dt          |d           z  }n|||d<   nt          d          |                     d	||
          }|                                }t	          |t
                    r^t          |          dk    rt          j        d| d          t          j
        di |d         | j        |                                 dS t          j
        di || j        |                                 dS )aZ  Read a dataset from the LangSmith API.

        Parameters
        ----------
        dataset_name : str or None, default=None
            The name of the dataset to read.
        dataset_id : UUID or None, default=None
            The ID of the dataset to read.

        Returns:
        -------
        Dataset
            The dataset.
        r  r  ry   NrJ   r  r  'Must provide dataset_name or dataset_idrG  r  r   r  r>  r  r6   )rV   rP   rJ  r   rM   r  rU   rW   r  r  r  r2  r  )r   r  r  rS   r  rM  r  s          r8   r
  zClient.read_dataset&  sa   * ")1!<\::<<<DD%)F6NNFGGG,, - 
 

 fd## 		6{{a57|777   %  ).7799    
 ! 
 

n3355
 
 
 
 	
r7   from_versionUnion[str, datetime.datetime]
to_versionls_schemas.DatasetDiffInfoc          
        |,|t          d          |                     |          j        }t          |d          }|                     dd| d| j        t          |t          j                  r|                                n|t          |t          j                  r|                                n|d	          }t          j
        |           t          j        d
i |                                S )a|  Get the difference between two versions of a dataset.

        Parameters
        ----------
        dataset_id : str or None, default=None
            The ID of the dataset.
        dataset_name : str or None, default=None
            The name of the dataset.
        from_version : str or datetime.datetime
            The starting version for the diff.
        to_version : str or datetime.datetime
            The ending version for the diff.

        Returns:
        -------
        DatasetDiffInfo
            The difference between the two versions of the dataset.

        Examples:
        --------
        .. code-block:: python

            # Get the difference between two tagged versions of a dataset
            from_version = "prod"
            to_version = "dev"
            diff = client.diff_dataset_versions(
                dataset_name="my-dataset",
                from_version=from_version,
                to_version=to_version,
            )
            print(diff)

            # Get the difference between two timestamped versions of a dataset
            from_version = datetime.datetime(2024, 1, 1)
            to_version = datetime.datetime(2024, 2, 1)
            diff = client.diff_dataset_versions(
                dataset_name="my-dataset",
                from_version=from_version,
                to_version=to_version,
            )
            print(diff)
        N&Must provide either dataset name or IDr  r  rG  r  z/versions/diff)r  r  r  r6   )rP   r
  r  rV   rJ  rD  rM   r  r  rW   rK  r  DatasetDiffInfor   )r   r  r  r  r  dsidrM  s          r8   diff_dataset_versionszClient.diff_dataset_versionsY  s
   d # !IJJJ***EEHJ
L11,,----M ",0ABB&L**,,,% "*h.?@@$J((***# 	 - 
 
" 	+H555)<<HMMOO<<<r7   r  c          	     *   d}|n-||                      |          j        }nt          d          |                     d| dt	          |d           d          }d	 |j                                                            d
          D             }|S )ao  Download a dataset in OpenAI Jsonl format and load it as a list of dicts.

        Parameters
        ----------
        dataset_id : str
            The ID of the dataset to download.
        dataset_name : str
            The name of the dataset to download.

        Returns:
        -------
        list
            The dataset loaded as a list of dicts.
        r  Nr  r  rG  rJ   r  z
/openai_ftc                6    g | ]}t          j        |          S r6   )r   r   )rx  lines     r8   rz  z9Client.read_dataset_openai_finetuning.<locals>.<listcomp>  s"    RRR4:d##RRRr7   ru  )r
  r  rP   rJ  rV   textr   rT   )r   r  r  rS   rM  r?   s         r8   read_dataset_openai_finetuningz%Client.read_dataset_openai_finetuning  s    " !%***EEHJJFGGG,,DDhz<88DDD
 
 SR0C0C0E0E0K0KD0Q0QRRRr7   )dataset_idsr  r  dataset_name_containsr~   r  r  r  Iterator[ls_schemas.Dataset]c             #  n  K   d|t          |d          ndi}|||d<   |||d<   |||d<   |||d<   |t          j        |          |d<   t          |                     d	|
                    D ]B\  }}	t          j        di |	| j        |                                 dV  ||dz   |k    r dS CdS )z{List the datasets on the LangSmith API.

        Yields:
        -------
        Dataset
            The datasets.
        r  Nr  r  r  r  r   r~   r  r  r  ry   r6   )	ro  r   r7  r  r  r  r  r2  r  )
r   r  r  r  r  r~   r  r  r  r?   s
             r8   list_datasetszClient.list_datasets  s)     $ (9S___s"
 "&F4L "+F;#)F6N ,&;F?#!%H!5!5F:#$$[$@@
 
 		 		JAw $  .7799      
  QUe^^		 		r7   )r  r  c                   ||                      |          j        }|t          d          |                     ddt	          |d           | j                  }t          j        |           dS )a  Delete a dataset from the LangSmith API.

        Parameters
        ----------
        dataset_id : UUID or None, default=None
            The ID of the dataset to delete.
        dataset_name : str or None, default=None
            The name of the dataset to delete.
        Nr  r  r  r  r  r  )r
  r  rP   rJ  rV   rD  rW   rK  )r   r  r  rM  s       r8   delete_datasetzClient.delete_dataset  s      #***EEHJEFFF,,=*l;;==M - 
 

 	+H55555r7   as_ofdatetime.datetimetagc                  ||                      |          j        }|t          d          |                     ddt	          |d           d| j        |                                |d	          }t          j        |           dS )
a  Update the tags of a dataset.

        If the tag is already assigned to a different version of this dataset,
        the tag will be moved to the new version. The as_of parameter is used to
        determine which version of the dataset to apply the new tags to.
        It must be an exact version of the dataset to succeed. You can
        use the read_dataset_version method to find the exact version
        to apply the tags to.

        Parameters
        ----------
        dataset_id : UUID
            The ID of the dataset to update.
        as_of : datetime.datetime
            The timestamp of the dataset to apply the new tags to.
        tag : str
            The new tag to apply to the dataset.

        Examples:
        --------
        .. code-block:: python

            dataset_name = "my-dataset"
            # Get the version of a dataset <= a given timestamp
            dataset_version = client.read_dataset_version(
                dataset_name=dataset_name, as_of=datetime.datetime(2024, 1, 1)
            )
            # Assign that version a new tag
            client.update_dataset_tags(
                dataset_name="my-dataset",
                as_of=dataset_version.as_of,
                tag="prod",
            )
        Nr  r  r  r  r  z/tagsr  r  r  )	r
  r  rP   rJ  rV   rD  r  rW   rK  r   r  r  r  r  rM  s         r8   update_dataset_tagzClient.update_dataset_tag  s    T #***EEHJEFFF,,B*l;;BBBM** 	 - 
 
 	+H55555r7   )r  r  searchr  r  #Iterator[ls_schemas.DatasetVersion]c          	   #  ,  K   ||                      |          j        }||t          |d          ndd}t          |                     dt          |d           d|                    D ]&\  }}t          j        d
i |V  ||d	z   |k    r dS 'dS )a  List dataset versions.

        Args:
            dataset_id (Optional[ID_TYPE]): The ID of the dataset.
            dataset_name (Optional[str]): The name of the dataset.
            search (Optional[str]): The search query.
            limit (Optional[int]): The maximum number of versions to return.

        Returns:
            Iterator[ls_schemas.DatasetVersion]: An iterator of dataset versions.
        Nr  r  )r  r  r  r  z	/versionsr  ry   r6   )r
  r  ro  r  r  rV   r  DatasetVersion)r   r  r  r  r  r  r  r   s           r8   list_dataset_versionszClient.list_dataset_versions@  s      & ***EEHJ(-(9S___s
 
 $$$JXj,??JJJ %  
 
 	 	JAw +66g66666 QUe^^	 	r7   )r  r  r  r  ls_schemas.DatasetVersionc               
   ||                      |          j        }|r|s||t          d          |                     ddt	          |d           d||d	          }t          j        d
i |                                S )aQ  Get dataset version by as_of or exact tag.

        Ues this to resolve the nearest version to a given timestamp or for a given tag.

        Args:
            dataset_id (Optional[ID_TYPE]): The ID of the dataset.
            dataset_name (Optional[str]): The name of the dataset.
            as_of (Optional[datetime.datetime]): The timestamp of the dataset
                to retrieve.
            tag (Optional[str]): The tag of the dataset to retrieve.

        Returns:
            ls_schemas.DatasetVersion: The dataset version.


        Examples:
        ---------
        .. code-block:: python

            # Get the latest version of a dataset
            client.read_dataset_version(dataset_name="my-dataset", tag="latest")

            # Get the version of a dataset <= a given timestamp
            client.read_dataset_version(
                dataset_name="my-dataset",
                as_of=datetime.datetime(2024, 1, 1),
            )


            # Get the version of a dataset with a specific tag
            client.read_dataset_version(dataset_name="my-dataset", tag="prod")
        Nr  z/Exactly one of as_of and tag must be specified.rG  r  r  z/versionr  r  r6   )r
  r  rP   rJ  rV   r  r  r   r  s         r8   read_dataset_versionzClient.read_dataset_versionc  s    P ***EEHJ 	Pc 	Pu}NOOO,,E*l;;EEE"3// - 
 

 (;;8==??;;;r7   )source_api_urlr  token_or_urlr  c                  |p| j         }t          ||          \  }}t          |d          }|                    |          }|p|j        }	 |                     |          }t                              d| d           |S # t          j	        $ r Y nw xY w	 t          |                    |                    }|                     ||j        |j        pt          j        j                  }	 |                     d |D             d |D             |j        	           n2# t(          $ r%}	t                              d
| d           |	d}	~	ww xY w	 ~n# ~w xY w|S )a;  Clone a public dataset to your own langsmith tenant.

        This operation is idempotent. If you already have a dataset with the given name,
        this function will do nothing.

        Args:
            token_or_url (str): The token of the public dataset to clone.
            source_api_url: The URL of the langsmith server where the data is hosted.
                Defaults to the API URL of your current client.
            dataset_name (str): The name of the dataset to create in your tenant.
                Defaults to the name of the public dataset.
        placeholderr   r  r  z) already exists in your tenant. Skipping.)r  r  r  c                    g | ]	}|j         
S r6   )r  rx  r   s     r8   rz  z/Client.clone_public_dataset.<locals>.<listcomp>  s    777AH777r7   c                    g | ]	}|j         
S r6   )r  r  s     r8   rz  z/Client.clone_public_dataset.<locals>.<listcomp>  s    9991QY999r7   )r  r  r  z)An error occurred while creating dataset z . You should delete it manually.N)rB   r]   r   r  r  r
  r   r   rW   r  r  r  rz  r  r  r  DataTypekvcreate_examplesr  rL  r8  )
r   r  r  r  r\   source_clientdsrL  r?   r   s
             r8   clone_public_datasetzClient.clone_public_dataset  s   & (74<%8~%V%V"
 #!
 
 
 ..z::#.rw	"""==BKKR<RRR   I. 	 	 	D		M>>zJJKKH)))N,@**=*@ *  G
$$77h77799999&z %    
 ! 
 
 
 5 5 5 5   
" sC   5B BBAE /1D!  E !
E+ EEE Ec                <    |                      |          }|j        S )N)r  )r
  r  )r   r  r?   s      r8   r%  zClient._get_data_type  s!    ##z#::  r7   rk   
generationrw  ls_schemas.Examplec                >    |                      d|id|i|||          S )z,Add an example (row) to an LLM-type dataset.inputrU  r  r  r  r  rw  )create_example)r   rk   r  r  r  rw  s         r8   create_llm_examplezClient.create_llm_example  s:     ""V$z*!%! # 
 
 	
r7   messages:List[Union[Mapping[str, Any], ls_schemas.BaseMessageLike]]generations>Optional[Union[Mapping[str, Any], ls_schemas.BaseMessageLike]]c           	         g }|D ]~}t          j        |          r@|                    t          j        t	          t
          j        |                               V|                    t	          t          |                     d}|Vt          j        |          r-t          j        t	          t
          j        |                    }nt	          t          |          }|                     d|i|d|ind|||          S )z,Add an example (row) to a Chat-type dataset.Nr  rU  r  )	rW   is_base_message_liker  convert_langchain_messager   r  BaseMessageLiker|   r  )	r   r  r  r  r  rw  final_inputmessagefinal_generationss	            r8   create_chat_examplezClient.create_chat_example  s$     	8 	8G,W55 8""6Z7AA     ""4g#6#67777 ",[99 <$,$F3[AA% %!! %){$;$;!""[)1B1N,--TX!%! # 
 
 	
r7   c                r   ||                      |          j        }d}|                     |          }|t          j        j        k    r|j        dk    rt          d|j         d          	 t          j	        |j
                  }n-# t          $ r  t          d|j         d|j
                   w xY wd|i}|j        sd}n[	 t          j        |j                  }	n-# t          $ r  t          d	|j         d
|j                   w xY wd|	i}n|t          j        j        k    r|j        dk    rt          d|j         d          	 dt          j        |j
                  i}n-# t          $ r  t          d|j         d|j
                   w xY w|j        sd}n	 dt          j        |j                  i}nd# t          $ r  t          d|j         d
|j                   w xY w|t          j        j        k    r|j
        }|j        }nt          d| d          |                     |||||          S )z-Add an example (row) to a dataset from a run.Nr  rh   z	Run type z+ is not supported for dataset of type 'LLM'z2Error converting LLM run inputs to prompt for run z with inputs r  z7Error converting LLM run outputs to generation for run z with outputs rU  z, is not supported for dataset of type 'chat'z9Error converting LLM run inputs to chat messages for run z=Error converting LLM run outputs to chat generations for run zDataset type z not recognized.r  )r
  r  r   r  r  rh   r  rP   rW   get_prompt_from_inputsr  r  get_llm_generation_from_outputschatget_messages_from_inputs#get_message_generation_from_outputsr  r  )
r   r  r  r  rw  dataset_typerk   r  r  r  s
             r8   create_example_from_runzClient.create_example_from_run  s5    ***EEHJL11*==:.222|u$$ 1 1 1 1  !8DD    :: :-0Z: :  
 '.v%6F; 
148!)!I#+!V!VJJ!   $@F@ @25+@ @  
 $Z0Z0555|u$$ 2 2 2 2  !8#DSZ#P#PQ    :: :-0Z: :  
 ; 
 ("NK# #GG
 "   $H$'FH H:=+H H  
 Z0333ZFkGG K\KKKLLL""!%! # 
 
 	
s0   .B *B2C *D	E' '*FF; ;*G%)r  r~   splitssource_run_idsidsr  r  Sequence[Mapping[str, Any]]/Optional[Sequence[Optional[Mapping[str, Any]]]]r  -Optional[Sequence[Optional[str | List[str]]]]r  %Optional[Sequence[Optional[ID_TYPE]]]r  c                  |t          d          |                     |          j        |||||d}
t          |          }|
                                D ]@\  }}|9t          |          |k    r&t          d| dt          |           d| d          Afd	t          ||pdgt          |          z  |pdgt          |          z  |pdgt          |          z  |pdgt          |          z  |pdgt          |          z            D             }|                     d
di | j        ddit          |                    }t          j
        |           dS )aM  Create examples in a dataset.

        Parameters
        ----------
        inputs : Sequence[Mapping[str, Any]]
            The input values for the examples.
        outputs : Optional[Sequence[Optional[Mapping[str, Any]]]], default=None
            The output values for the examples.
        metadata : Optional[Sequence[Optional[Mapping[str, Any]]]], default=None
            The metadata for the examples.
        splits :  Optional[Sequence[Optional[str | List[str]]]], default=None
            The splits for the examples, which are divisions
            of your dataset such as 'train', 'test', or 'validation'.
        source_run_ids : Optional[Sequence[Optional[ID_TYPE]]], default=None
                The IDs of the source runs associated with the examples.
        ids : Optional[Sequence[ID_TYPE]], default=None
            The IDs of the examples.
        dataset_id : Optional[ID_TYPE], default=None
            The ID of the dataset to create the examples in.
        dataset_name : Optional[str], default=None
            The name of the dataset to create the examples in.
        Nz3Either dataset_id or dataset_name must be provided.r  )r  r~   r  r  r  
Length of  (z#) does not match length of inputs (r6  c                r    g | ]3\  }}}}}}|||||pt          t          j                              |d 4S ))r  r  r  r~   rT   r  source_run_id)rC   rN   r   )rx  in_out_	metadata_split_id_source_run_id_r  s          r8   rz  z*Client.create_examples.<locals>.<listcomp>  sg     
 
 
 BT9fc> (%.S..!/ 
 
 
r7   r  /examples/bulkrm  r>  r-  )rP   r
  r  rU   r   ziprJ  rD  r  rW   rK  )r   r  r  r~   r  r  r  r  r  rh  sequence_args	input_lenarg_name	arg_valuerL  rM  s          `        r8   r  zClient.create_examplesg  s   F ,"6RSSS***EEHJ  ,
 
 KK	#0#6#6#8#8 	 	Hi$Y9)D)D 7 7 7S^^ 7 7*37 7 7  
 
 
 
 FI/D6CKK/0TFS[[0.4&3v;;.+vF+64&3v;;"6F F
 
 
( ,,It}In6HIIX&&	 - 
 
 	+H55555r7   Mapping[str, Any]Optional[Mapping[str, Any]]rT   Optional[str | List[str]]rF  r  c
           
        ||                      |          j        }||||||	d}
|r|                                |
d<   |pt          t	          j                              |
d<   |                     ddi | j        dd	it          d
 |
	                                D                                 }t          j        |           |                                }t          j        di || j        |                                 dS )a  Create a dataset example in the LangSmith API.

        Examples are rows in a dataset, containing the inputs
        and expected outputs (or other reference information)
        for a model or chain.

        Args:
            inputs : Mapping[str, Any]
                The input values for the example.
            dataset_id : UUID or None, default=None
                The ID of the dataset to create the example in.
            dataset_name : str or None, default=None
                The name of the dataset to create the example in.
            created_at : datetime or None, default=None
                The creation timestamp of the example.
            outputs : Mapping[str, Any] or None, default=None
                The output values for the example.
            metadata : Mapping[str, Any] or None, default=None
                The metadata for the example.
            split : str or List[str] or None, default=None
                The splits for the example, which are divisions
                of your dataset such as 'train', 'test', or 'validation'.
            example_id : UUID or None, default=None
                The ID of the example to create. If not provided, a new
                example will be created.
            source_run_id : UUID or None, default=None
                The ID of the source run associated with this example.

        Returns:
            Example: The created example.
        Nr  )r  r  r  r~   rT   r  rw  r  r  r  rm  r>  c                    i | ]
\  }}|||S r   r6   r1  s      r8   r   z)Client.create_example.<locals>.<dictcomp>  s    MMMtq!q}a}}}r7   r-  r  r6   )r
  r  r  rC   rN   r   rJ  rD  r  r   rW   rK  r   r  r  r2  r  )r   r  r  r  rw  r  r~   rT   rF  r  rk  rM  r  s                r8   r  zClient.create_example  s<   X ***EEHJ $ *
 
  	8!+!5!5!7!7D43tz||#4#4T
,,It}In6HIIMMtzz||MMMNN	 - 
 
 	+H555! 
 

n3355
 
 
 
 	
r7   )r  c                  |                      ddt          |d           d|r|                                ndi          }t          j        di |                                | j        |                                 dS )	zRead an example from the LangSmith API.

        Args:
            example_id (UUID): The ID of the example to read.

        Returns:
            Example: The example.
        rG  
/examples/rF  r  Nr  r  r6   )rJ  rV   r  r  r  r   r2  r  )r   rF  r  rM  s       r8   read_examplezClient.read_example  s     ,,=*l;;==e=*** - 
 
 ! 
 
mmoo
n3355
 
 
 
 	
r7   r   )r  r  r~   r  'Optional[Union[datetime.datetime, str]]inline_s3_urlsr  Iterator[ls_schemas.Example]c          
   +    K   i |||t          |t          j                  r|                                n||||t          |d          nd|
d}|	t	          |	          |d<   |||d<   n$|!|                     |          j        }||d<   n	 t          |                     d|                    D ]B\  }}t          j
        di || j        |                                 d	V  ||d
z   |k    r dS CdS )a/  Retrieve the example rows of the specified dataset.

        Args:
            dataset_id (UUID, optional): The ID of the dataset to filter by.
                Defaults to None.
            dataset_name (str, optional): The name of the dataset to filter by.
                Defaults to None.
            example_ids (List[UUID], optional): The IDs of the examples to filter by.
                Defaults to None.
            as_of (datetime, str, or optional): The dataset version tag OR
                timestamp to retrieve the examples as of.
                Response examples will only be those that were present at the time
                of the tagged (or timestamped) version.
            splits (List[str], optional): A list of dataset splits, which are
                divisions of your dataset such as 'train', 'test', or 'validation'.
                Returns examples only from the specified splits.
            inline_s3_urls (bool, optional): Whether to inline S3 URLs.
                Defaults to True.
            offset (int): The offset to start from. Defaults to 0.
            limit (int, optional): The maximum number of examples to return.
            filter (str, optional): A structured fileter string to apply to
                the examples.

        Yields:
            Example: The examples.
        Nr  )r  r  r  r  r  r  r  r~   r?   r  r  r  r  ry   r6   )rM   r  r  ro  r  r
  r  r  r  r  r  r2  r  )r   r  r  r  r  r  r  r  r  r~   r  rh  r  r  rI  s                  r8   rJ  zClient.list_examples  sr     R"
"
%/x7H%I%IT!!!u,(-(9S___s"
 "
 "
 !,X!6!6F:! *F9%***EEHJ *F9#$$[$@@
 
 		 		JAw $  .7799      
  QUe^^		 		r7   latest)r  c          	         t          |d          }|                     dd| d| j        t          j        d|i|                    }t          j        |           dS )a1  Enable dataset indexing. Examples are indexed by their inputs.

        This enables searching for similar examples by inputs with
        ``client.similar_examples()``.

        Args:
            dataset_id (UUID): The ID of the dataset to index.
            tag (str, optional): The version of the dataset to index. If 'latest'
                then any updates to the dataset (additions, updates, deletions of
                examples) will be reflected in the index.

        Returns:
            None

        Raises:
            requests.HTTPError
        r  r  r  z/indexr  r-  N)rV   rJ  rD  r   r7  rW   rK  )r   r  r  rh  resps        r8   index_datasetzClient.index_datasetd  ss    2 j,77
((++++MUC26233	 ) 
 
 	+D11111r7   )r  List[ls_schemas.ExampleSearch]c         	     `   t          |d          }||d|}|||d<   |                     dd| d| j        t          j        |                    }t          j        |           g }|                                d	         D ]*}	|                    t          j	        d
i |	d|i           +|S )ae  Retrieve the dataset examples whose inputs best match the current inputs.

        **Note**: Must have few-shot indexing enabled for the dataset. See
        `client.index_dataset()`.

        Args:
            inputs (dict): The inputs to use as a search query. Must match the dataset
                input schema. Must be JSON serializable.
            limit (int): The maximum number of examples to return.
            dataset_id (str or UUID): The ID of the dataset to search over.
            filter (str, optional): A filter string to apply to the search results. Uses
                the same syntax as the `filter` parameter in `list_runs()`. Only a subset
                of operations are supported. Defaults to None.

                For example, you can use ``and(eq(metadata.some_tag, 'some_value'), neq(metadata.env, 'dev'))``
                to filter only examples where some_tag has some_value, and the environment is not dev.
                kwargs (Any): Additional keyword args to pass as part of request body.

        Examples:
            .. code-block:: python

                from langsmith import Client

                client = Client()
                client.similar_examples(
                    {"question": "When would i use the runnable generator"},
                    limit=3,
                    dataset_id="...",
                )

            .. code-block:: pycon

                [
                    ExampleSearch(
                        inputs={'question': 'How do I cache a Chat model? What caches can I use?'},
                        outputs={'answer': 'You can use LangChain\'s caching layer for Chat Models. This can save you money by reducing the number of API calls you make to the LLM provider, if you\'re often requesting the same completion multiple times, and speed up your application.\n\nfrom langchain.cache import InMemoryCache\nlangchain.llm_cache = InMemoryCache()\n\n# The first time, it is not yet in cache, so it should take longer\nllm.predict(\'Tell me a joke\')\n\nYou can also use SQLite Cache which uses a SQLite database:\n\nrm .langchain.db\n\nfrom langchain.cache import SQLiteCache\nlangchain.llm_cache = SQLiteCache(database_path=".langchain.db")\n\n# The first time, it is not yet in cache, so it should take longer\nllm.predict(\'Tell me a joke\') \n'},
                        metadata=None,
                        id=UUID('b2ddd1c4-dff6-49ae-8544-f48e39053398'),
                        dataset_id=UUID('01b6ce0f-bfb6-4f48-bbb8-f19272135d40')
                    ),
                    ExampleSearch(
                        inputs={'question': "What's a runnable lambda?"},
                        outputs={'answer': "A runnable lambda is an object that implements LangChain's `Runnable` interface and runs a callbale (i.e., a function). Note the function must accept a single argument."},
                        metadata=None,
                        id=UUID('f94104a7-2434-4ba7-8293-6a283f4860b4'),
                        dataset_id=UUID('01b6ce0f-bfb6-4f48-bbb8-f19272135d40')
                    ),
                    ExampleSearch(
                        inputs={'question': 'Show me how to use RecursiveURLLoader'},
                        outputs={'answer': 'The RecursiveURLLoader comes from the langchain.document_loaders.recursive_url_loader module. Here\'s an example of how to use it:\n\nfrom langchain.document_loaders.recursive_url_loader import RecursiveUrlLoader\n\n# Create an instance of RecursiveUrlLoader with the URL you want to load\nloader = RecursiveUrlLoader(url="https://example.com")\n\n# Load all child links from the URL page\nchild_links = loader.load()\n\n# Print the child links\nfor link in child_links:\n    print(link)\n\nMake sure to replace "https://example.com" with the actual URL you want to load. The load() method returns a list of child links found on the URL page. You can iterate over this list to access each child link.'},
                        metadata=None,
                        id=UUID('0308ea70-a803-4181-a37d-39e95f138f8c'),
                        dataset_id=UUID('01b6ce0f-bfb6-4f48-bbb8-f19272135d40')
                    ),
                ]

        r  )r  r  Nr  r  r  z/searchr-  rL  r6   )
rV   rJ  rD  r   r7  rW   rK  r  r  ExampleSearch)
r   r  r  r  r  rh  reqr  rL  exs
             r8   similar_exampleszClient.similar_examples  s    H j,77

 
 

 "CM((,,,,MC	 ) 
 
 	+D111))++j) 	S 	SBOOJ4QQrQQjQQQRRRRr7   )r  r  r~   rT   r  c          
     6   t          |||||          }|                     ddt          |d           i | j        ddit	          d |                                D                                 }t          j        |           |                                S )	a  Update a specific example.

        Parameters
        ----------
        example_id : str or UUID
            The ID of the example to update.
        inputs : Dict[str, Any] or None, default=None
            The input values to update.
        outputs : Mapping[str, Any] or None, default=None
            The output values to update.
        metadata : Dict or None, default=None
            The metadata to update.
        split : str or List[str] or None, default=None
            The dataset split to update, such as
            'train', 'test', or 'validation'.
        dataset_id : UUID or None, default=None
            The ID of the dataset to update.

        Returns:
        -------
        Dict[str, Any]
            The updated example.
        )r  r  r  r~   rT   r  r  rF  rm  r>  c                    i | ]
\  }}|||S r   r6   r1  s      r8   r   z)Client.update_example.<locals>.<dictcomp>  s    PPPtq!!-a---r7   r-  )	r|   rJ  rV   rD  r  r   rW   rK  r   )	r   rF  r  r  r~   rT   r  rI  rM  s	            r8   update_examplezClient.update_example  s    B !
 
 
 ,,=*l;;==It}In6HIIPPw}}PPPQQ	 - 
 
 	+H555}}r7   r  r  r~   r  r  Sequence[ID_TYPE],Optional[Sequence[Optional[Dict[str, Any]]]]"Optional[Sequence[Optional[Dict]]]c                  |||||d}t          |          }|                                D ]@\  }	}
|
9t          |
          |k    r&t          d|	 dt          |
           d| d          Ad t          ||pdgt          |          z  |pdgt          |          z  |pdgt          |          z  |pdgt          |          z  |pdgt          |          z            D             }|                     dd	i | j        d
dit          d |D                                 }t          j        |           |	                                S )a  Update multiple examples.

        Parameters
        ----------
        example_ids : Sequence[ID_TYPE]
            The IDs of the examples to update.
        inputs : Optional[Sequence[Optional[Dict[str, Any]]], default=None
            The input values for the examples.
        outputs : Optional[Sequence[Optional[Mapping[str, Any]]]], default=None
            The output values for the examples.
        metadata : Optional[Sequence[Optional[Mapping[str, Any]]]], default=None
            The metadata for the examples.
        split :  Optional[Sequence[Optional[str | List[str]]]], default=None
            The splits for the examples, which are divisions
            of your dataset such as 'train', 'test', or 'validation'.
        dataset_ids : Optional[Sequence[Optional[ID_TYPE]]], default=None
            The IDs of the datasets to move the examples to.

        Returns:
        -------
        Dict[str, Any]
            The response from the server (specifies the number of examples updated).
        r  Nr  r  z%) does not match length of examples (r6  c           	     .    g | ]\  }}}}}}||||||d S ))r  r  r  r  r~   rT   r6   )rx  r  r  r  r  r  dataset_id_s          r8   rz  z*Client.update_examples.<locals>.<listcomp>A  sO     
 
 
 ?S$	6; )% 
 
 
r7   r  r  rm  r>  c                J    g | ] }d  |                                 D             !S )c                    i | ]
\  }}|||S r   r6   r1  s      r8   r   z5Client.update_examples.<locals>.<listcomp>.<dictcomp>Z  s    KKK$!QQ]A]]]r7   )r   rH  s     r8   rz  z*Client.update_examples.<locals>.<listcomp>Y  s?       # LK'--//KKK  r7   r-  )
rU   r   rP   r  rJ  rD  r  rW   rK  r   )r   r  r  r  r~   r  r  r  examples_lenr  r  rL  rM  s                r8   update_exampleszClient.update_examples  s   D  &
 
 ;''#0#6#6#8#8 	 	Hi$Y<)G)G < < <S^^ < <,8< < <  
 
 CF34&3{#3#334D6C$4$445TFS%5%5534&3{#3#338vK(8(88C C
 
 
$ ,,It}In6HII '/    - 
 
 	+H555}}r7   c                    |                      ddt          |d           | j                  }t          j        |           dS )zDelete an example by ID.

        Parameters
        ----------
        example_id : str or UUID
            The ID of the example to delete.
        r  r  rF  r  Nr  )r   rF  rM  s      r8   delete_examplezClient.delete_examplec  sT     ,,=*l;;==M - 
 

 	+H55555r7   )r  r  r  'Optional[Union[str, datetime.datetime]]	List[str]c               p   |,|t          d          |                     |          j        }i }|3t          |t          j                  r|                                n||d<   |                     ddt          |d           d|	          }t          j	        |           |
                                S )
a  Get the splits for a dataset.

        Args:
            dataset_id (ID_TYPE): The ID of the dataset.
            as_of (Optional[Union[str, datetime.datetime]], optional): The version
                of the dataset to retrieve splits for. Can be a timestamp or a
                string tag. Defaults to "latest".

        Returns:
            List[str]: The names of this dataset's.
        NMust provide dataset name or IDr  r  rG  r  r  /splitsr  )rP   r
  r  rM   r  r  rJ  rV   rW   rK  r   )r   r  r  r  r  rM  s         r8   list_dataset_splitszClient.list_dataset_splitsr  s    $ # !BCCC***EEHJ%/x7H%I%IT!!!u 7O ,,D*l;;DDD - 
 

 	+H555}}r7   )r  r  r  
split_nameList[ID_TYPE]r  c                  |,|t          d          |                     |          j        }|d t          |          D             |d}|                     ddt          |d           d	|
          }t          j        |           dS )a  Update the splits for a dataset.

        Args:
            dataset_id (ID_TYPE): The ID of the dataset to update.
            split_name (str): The name of the split to update.
            example_ids (List[ID_TYPE]): The IDs of the examples to add to or
                remove from the split.
            remove (bool, optional): If True, remove the examples from the split.
                If False, add the examples to the split. Defaults to False.

        Returns:
            None
        Nr  r  c           
     V    g | ]&\  }}t          t          |d | d                    'S )zexample_ids[]rC   rV   rx  r  r  s      r8   rz  z0Client.update_dataset_splits.<locals>.<listcomp>  sJ       As HS"5"5"5"56677  r7   )r  rL  r  r  r  r  r  r   )rP   r
  r  r  rJ  rV   rW   rK  )r   r  r  r  r  r  rk  rM  s           r8   update_dataset_splitszClient.update_dataset_splits  s    , # !BCCC***EEHJ$ '44   
 
 ,,K\ B BKKKRV - 
 
 	+H55555r7   9Union[ls_schemas.Run, ls_schemas.RunBase, str, uuid.UUID]c                    t          |t          t          j        f          r|                     ||          }nt          t          j        |          }|S )a|  Resolve the run ID.

        Parameters
        ----------
        run : Run or RunBase or str or UUID
            The run to resolve.
        load_child_runs : bool
            Whether to load child runs.

        Returns:
        -------
        Run
            The resolved run.

        Raises:
        ------
        TypeError
            If the run type is invalid.
        r  )rM   rC   rN   rO   r  r   r  r  )r   r  r  run_s       r8   _resolve_run_idzClient._resolve_run_id  sJ    0 cC+,, 	-==o=FFDD
,,Dr7   rI  5Union[ls_schemas.Example, str, uuid.UUID, dict, None]Optional[ls_schemas.Example]c                |   t          |t          t          j        f          r|                     |          }nt          |t
          j                  r|}ngt          |t                    r.t          j        di || j        | 	                                d}n$|j
        |                     |j
                  }nd}|S )aC  Resolve the example ID.

        Parameters
        ----------
        example : Example or str or UUID or dict or None
            The example to resolve.
        run : Run
            The run associated with the example.

        Returns:
        -------
        Example or None
            The resolved example.
        r  Nr6   )rM   rC   rN   rO   r  r  r  r|   r2  r  r  )r   rI  r  reference_example_s       r8   _resolve_example_idzClient._resolve_example_id  s    & gTY/00 	&!%!2!27!;!;!344 	&!(&& 		&!+!3 " "".7799" " " "
 %1!%!2!233K!L!L!%!!r7   )fn_namerc  JUnion[ls_evaluator.EvaluationResult, ls_evaluator.EvaluationResults, dict]r$  #List[ls_evaluator.EvaluationResult]c               J   ddl m dfddd}t          |j                  r|g}nu ||          rfd|d         D             }nUt          |t                    r  t          t          |                    g}n t          dt          |           d          |S )Nr   r9   single_result*Union[ls_evaluator.EvaluationResult, dict]rG   ls_evaluator.EvaluationResultc                |    t          | t                    r% j        di |                     d          d| S | S )N	reasoning)rF  commentr6   )rM   r|   EvaluationResultrW  )r(  r$  ls_evaluators    r8   _cast_resultz1Client._select_eval_results.<locals>._cast_result	  sh     -.. 4|4  &#0#4#4[#A#A  (   ! r7   rc  r   )TypeGuard[ls_evaluator.EvaluationResults]c                4    t          | t                    od| v S )Nrc  )rM   r|   )rc  s    r8   _is_eval_resultsz5Client._select_eval_results.<locals>._is_eval_results  s    gt,,Eg1EEr7   c                &    g | ]} |          S r6   r6   )rx  r  r0  s     r8   rz  z/Client._select_eval_results.<locals>.<listcomp>  s!    DDDAQDDDr7   z!Invalid evaluation results type: z.. Must be EvaluationResult, EvaluationResults.)r(  r)  rG   r*  )rc  r   rG   r1  )langsmith.evaluationr:   rM   r.  r|   r   rP   r9  )r   rc  r$  r3  results_r0  r/  s     `  @@r8   _select_eval_resultszClient._select_eval_results  s    	CBBBBB	! 	! 	! 	! 	! 	! 	!	F 	F 	F 	F g|<== 
	yHHg&& 	DDDD1CDDDHH&& 	$T$%8%899:HH@DMM @ @ @   r7   )source_infor  r  r:   ls_evaluator.RunEvaluatorr8  r  9Optional[Union[ls_schemas.Example, str, dict, uuid.UUID]]r*  c                   |                      ||          }|                     ||          }|                    ||          }|                     |||          }	|	d         S )a1  Evaluate a run.

        Parameters
        ----------
        run : Run or RunBase or str or UUID
            The run to evaluate.
        evaluator : RunEvaluator
            The evaluator to use.
        source_info : Dict[str, Any] or None, default=None
            Additional information about the source of the evaluation to log
            as feedback metadata.
        reference_example : Example or str or dict or UUID or None, default=None
            The example to use as a reference for the evaluation.
            If not provided, the run's reference example will be used.
        load_child_runs : bool, default=False
            Whether to load child runs when resolving the run ID.

        Returns:
        -------
        Feedback
            The feedback object created by the evaluation.
        r  rI  r8  r   )r  r#  evaluate_run_log_evaluation_feedback
r   r  r:   r8  r  r  r  r"  evaluator_responserc  s
             r8   r>  zClient.evaluate_run&  s    B ##C#II!556GNN&33& 4 
 
 //# 0 
 
 qzr7   )	_executorrA  Optional[ls_schemas.Run]rB  Optional[cf.ThreadPoolExecutor]c                                         |          } fd}|D ]}|pi }	|j        ri |j        |	}	d }
|j        r|j        }
n	||j        }
 ||
|j        |j        |j        |j        |j        |	|j	        t          t          t          j                 |j                  t          j        j        ||j        |r|j        nd            |S )Nc                 P    r j         j        fi |  d S  j        di |  d S )Nr6   )r  create_feedback)rh  rB  r   s    r8   _submit_feedbackz9Client._log_evaluation_feedback.<locals>._submit_feedbackb  sN     / 	 !5@@@@@@@$$..v.....r7   )r  rF  scorer   r-  
correctionr8  r  feedback_configfeedback_source_typer  r  r  )r7  evaluator_infotarget_run_idr  rF  rI  r   r-  rJ  r  r   r   r  FeedbackConfigrK  FeedbackSourceTypeMODELr  r  )r   rA  r  r8  r  rB  rc  rH  ressource_info_r  s   `    `     r8   r?  zClient._log_evaluation_feedbackU  s     ++,>??	/ 	/ 	/ 	/ 	/ 	/  	 	C&,"L! FE#"4EEG  !+&Gii>(!/ $Z679L! ! &0%B%H%i),6$    " r7   %Union[ls_schemas.Run, str, uuid.UUID]c                  K   |                      ||          }|                     ||          }|                    ||           d{V }|                     |||          }	|	d         S )a8  Evaluate a run asynchronously.

        Parameters
        ----------
        run : Run or str or UUID
            The run to evaluate.
        evaluator : RunEvaluator
            The evaluator to use.
        source_info : Dict[str, Any] or None, default=None
            Additional information about the source of the evaluation to log
            as feedback metadata.
        reference_example : Optional Example or UUID, default=None
            The example to use as a reference for the evaluation.
            If not provided, the run's reference example will be used.
        load_child_runs : bool, default=False
            Whether to load child runs when resolving the run ID.

        Returns:
        -------
        EvaluationResult
            The evaluation result object created by the evaluation.
        r  r<  Nr=  r   )r  r#  aevaluate_runr?  r@  s
             r8   rV  zClient.aevaluate_run  s      B ##C#II!556GNN#,#:#:& $; $
 $
 
 
 
 
 
 

 //# 0 
 

 qzr7   r	  )rI  r   rJ  r-  r8  rL  r  feedback_idrK  r]  r  comparative_experiment_idfeedback_group_idr  r  rF  rI  Union[float, int, bool, None]r   Union[str, dict, None]rJ  Union[dict, None]r-  Union[str, None]rL  )Union[ls_schemas.FeedbackSourceType, str]rW  rK  #Optional[ls_schemas.FeedbackConfig]rX  rY  ls_schemas.Feedbackc          	        ||t          d          ||t          d          |r*t          j        dt          |           t                     	 t          |t          j                  st          j        |          }|t          j        j        k    rt          j	        |          }n=|t          j        j
        k    rt          j        |          }nt          d|           |j        |j        ni |_        |	"d|j        vrdt          |	          i|j        d<   |j        rd|j        v r|j        d         }t          |d	          r#t          |          r|                                }d|v r1t          t#          |j        d         d         d
                    |d<   ||j        d<   t          j        d&i dt'          |
          dt'          |d          dt'          |d          d|d|d|d|d|d|dt(          j                            t(          j        j                  dt(          j                            t(          j        j                  d|dt'          |d          dt'          |d          dt'          |d          d|}| j        j        pi                     dd          }|r| j        j        rwt9          j        | j        j        d          rX| j        Q|j        JtA          |          }| j        !                    tE          t          |j#                  |                     nJtI          |                    d                    }| %                    d d!d"|i|t8          j&        f#           t          j'        d&i |                                S # tP          $ r#}tR          *                    d$d%           |d}~ww xY w)'a
  Create a feedback in the LangSmith API.

        Parameters
        ----------
        run_id : str or UUID
            The ID of the run to provide feedback for. Either the run_id OR
            the project_id must be provided.
        trace_id : str or UUID
            The trace ID of the run to provide feedback for. This is optional.
        key : str
            The name of the metric or 'aspect' this feedback is about.
        score : float or int or bool or None, default=None
            The score to rate this run on the metric or aspect.
        value : float or int or bool or str or dict or None, default=None
            The display value or non-numeric value for this feedback.
        correction : dict or None, default=None
            The proper ground truth for this run.
        comment : str or None, default=None
            A comment about this feedback, such as a justification for the score or
            chain-of-thought trajectory for an LLM judge.
        source_info : Dict[str, Any] or None, default=None
            Information about the source of this feedback.
        feedback_source_type : FeedbackSourceType or str, default=FeedbackSourceType.API
            The type of feedback source, such as model (for model-generated feedback)
                or API.
        source_run_id : str or UUID or None, default=None,
            The ID of the run that generated this feedback, if a "model" type.
        feedback_id : str or UUID or None, default=None
            The ID of the feedback to create. If not provided, a random UUID will be
            generated.
        feedback_config: langsmith.schemas.FeedbackConfig or None, default=None,
            The configuration specifying how to interpret feedback with this key.
            Examples include continuous (with min/max bounds), categorical,
            or freeform.
        stop_after_attempt : int, default=10
            The number of times to retry the request before giving up.
        project_id : str or UUID
            The ID of the project_id to provide feedback on. One - and only one - of
            this and run_id must be provided.
        comparative_experiment_id : str or UUID
            If this feedback was logged as a part of a comparative experiment, this
            associates the feedback with that experiment.
        feedback_group_id : str or UUID
            When logging preferences, ranking runs, or other comparative feedback,
            this is used to group feedback together.
        extra : dict
            Metadata for the feedback.
        trace_id: Optional[ID_TYPE] = The trace ID of the run to provide feedback for. Enables batch ingestion.
        Nz-One of run_id and project_id must be providedz2Only one of run_id and project_id must be providedzLThe following arguments are no longer used in the create_feedback endpoint: )r~   zUnknown feedback source type __runr  r|   z+feedback_source.metadata['__run']['run_id']r  Tr   r  rF  rI  r   rJ  r-  feedback_sourcerw  modified_atrK  r  rX  rY  r  use_multipart_endpointFz0.8.10)exclude_noner  	/feedbackrk  )r\  r]  r^  zError creating feedbackr5  r6   )+rP   r   r   r  DeprecationWarningrM   r  rP  APIAPIFeedbackSourcerQ  ModelFeedbackSourcer~   rC   r  r  r|   rV   FeedbackCreater   r  r  r  r  r   rV  rW  r   rW   is_version_greater_or_equalr   r  r+   r   r    r  r  rJ  r  Feedbackrd   r   r8  )r   r  rF  rI  r   rJ  r-  r8  rL  r  rW  rK  r]  r  rX  rY  r  r  rh  rc  	_run_metafeedbackr  r"  feedback_blockr   s                             r8   rG  zClient.create_feedback  s   R >j0LMMM*"8QRRR 	M/$Vnn/ /"  
T	2J4QRR '1'D(( ($ $z'D'HHH0+FFF   &)F)LLL","@+"V"V"V !WAU!W!WXXX,;,D,P((VX $ (WO<T-T-T5=s=?Q?Q4R(1' >G7O,O,O />.Fw.O	9f-- 1(92E2E 1 ) 0 0Iy((*- +4W=hGI + +Ih' 5>(1!0   ,,, $F====	
 &hDAAAA C e e &:   !0 $,001B1FGGG %-11(2C2GHHH !0 (
EEEE  +7-4+ + + +!& #//@d"S"S"S"S'( e)H. "Y:@bEE(% M
 I% 89JHUU &2%1 7 A A"&&$S%5%5}EE    "-X]]]-M-M!N!N))$ (:&=? *    &99999 	 	 	LL2TLBBBG	s   M N5 5
O"?OO")rI  r   rJ  r-  (Union[float, int, bool, str, dict, None]c                   i }|||d<   |||d<   |||d<   |||d<   |                      ddt          |d           i | j        d	d
it          |                    }t	          j        |           dS )a[  Update a feedback in the LangSmith API.

        Parameters
        ----------
        feedback_id : str or UUID
            The ID of the feedback to update.
        score : float or int or bool or None, default=None
            The score to update the feedback with.
        value : float or int or bool or str or dict or None, default=None
            The value to update the feedback with.
        correction : dict or None, default=None
            The correction to update the feedback with.
        comment : str or None, default=None
            The comment to update the feedback with.
        NrI  r   rJ  r-  r  
/feedback/rW  rm  r>  r-  )rJ  rV   rD  r  rW   rK  )r   rW  rI  r   rJ  r-  feedback_updaterM  s           r8   update_feedbackzClient.update_feedback]  s    0 +-',OG$',OG$!,6OL))0OI&,,?+}==??It}In6HII_--	 - 
 
 	+H55555r7   c                    |                      ddt          |d                     }t          j        di |                                S )zRead a feedback from the LangSmith API.

        Parameters
        ----------
        feedback_id : str or UUID
            The ID of the feedback to read.

        Returns:
        -------
        Feedback
            The feedback.
        rG  rt  rW  r6   )rJ  rV   r  rn  r   r   rW  rM  s      r8   read_feedbackzClient.read_feedback  sR     ,,?+}==??
 
 "55X]]__555r7   )r  feedback_keyrL  r  rz  1Optional[Sequence[ls_schemas.FeedbackSourceType]]Iterator[ls_schemas.Feedback]c             +     K   ||t          |d          ndd|}|||d<   |||d<   t          |                     d|                    D ]&\  }}t          j        d	i |V  ||dz   |k    r dS 'dS )
a  List the feedback objects on the LangSmith API.

        Parameters
        ----------
        run_ids : List[str or UUID] or None, default=None
            The IDs of the runs to filter by.
        feedback_key: List[str] or None, default=None
            The feedback key(s) to filter by. Example: 'correctness'
            The query performs a union of all feedback keys.
        feedback_source_type: List[FeedbackSourceType] or None, default=None
            The type of feedback source, such as model
            (for model-generated feedback) or API.
        limit : int or None, default=None
        **kwargs : Any
            Additional keyword arguments.

        Yields:
        ------
        Feedback
            The feedback objects.
        Nr  )r  r  rF  sourcerg  r  ry   r6   )ro  r  r  r  rn  )	r   r  rz  rL  r  rh  r  r  rp  s	            r8   list_feedbackzClient.list_feedback  s      > (-(9S___s
 
 

 #(F5M+3F8$$$[$@@
 
 	 	KAx %1111111 QUe^^	 	r7   c                    |                      ddt          |d           | j                  }t          j        |           dS )zDelete a feedback by ID.

        Parameters
        ----------
        feedback_id : str or UUID
            The ID of the feedback to delete.
        r  rt  rW  r  Nr  rx  s      r8   delete_feedbackzClient.delete_feedback  sT     ,,?+}==??M - 
 

 	+H55555r7   )r   rJ  r-  r~   rA   c                  t          || j        d          \  }}|| j        k    rt          d|           |                     ddt	          |           t          |||||d          | j                  }	t          j        |	           dS )	a  Create feedback from a presigned token or URL.

        Args:
            token_or_url (Union[str, uuid.UUID]): The token or URL from which to create
                 feedback.
            score (Union[float, int, bool, None], optional): The score of the feedback.
                Defaults to None.
            value (Union[float, int, bool, str, dict, None], optional): The value of the
                feedback. Defaults to None.
            correction (Union[dict, None], optional): The correction of the feedback.
                Defaults to None.
            comment (Union[str, None], optional): The comment of the feedback. Defaults
                to None.
            metadata (Optional[dict], optional): Additional metadata for the feedback.
                Defaults to None.

        Raises:
            ValueError: If the source API URL is invalid.

        Returns:
            None: This method does not return anything.
        ry   )rD   zInvalid source API URL. r  z/feedback/tokens/)rI  r   rJ  r-  r~   r%  N)	r]   rB   rP   rJ  rV   r  rD  rW   rK  )
r   r  rI  r   rJ  r-  r~   r  r\   rM  s
             r8   create_feedback_from_tokenz!Client.create_feedback_from_token  s    @ &9$,!&
 &
 &
"
 T\))HHHIII,,6 4 466""",& ( 	 	 M - 
 
 	+H55555r7   )
expirationrK  rW  r  0Optional[datetime.datetime | datetime.timedelta]ls_schemas.FeedbackIngestTokenc               ~   ||||pt          t          j                              d}|t          j        ddd          |d<   nt          |t          j                  r|                                |d<   nlt          |t          j                  r3t          j        |j	        |j
        dz  |j
        d	z  d	z            |d<   nt          d
t          |                     |                     ddt          |                    }t          j        |           t          j        di |                                S )a  Create a pre-signed URL to send feedback data to.

        This is useful for giving browser-based clients a way to upload
        feedback data directly to LangSmith without accessing the
        API key.

        Args:
            run_id:
            feedback_key:
            expiration: The expiration time of the pre-signed URL.
                Either a datetime or a timedelta offset from now.
                Default to 3 hours.
            feedback_config: FeedbackConfig or None.
                If creating a feedback_key for the first time,
                this defines how the metric should be interpreted,
                such as a continuous score (w/ optional bounds),
                or distribution over categorical values.
            feedback_id: The ID of the feedback to create. If not provided, a new
                feedback will be created.

        Returns:
            The pre-signed URL for uploading feedback data.
        )r  rz  rK  r  Nr   rn   dayshoursminutes
expires_in
expires_at  <   Unknown expiration type: r  /feedback/tokens)rk  r6   )rC   rN   r   r  TimeDeltaInputrM   r  r  	timedeltar  secondsrP   r9  rJ  r  rW   rK  FeedbackIngestTokenr   )r   r  rz  r  rK  rW  r  rM  s           r8   create_presigned_feedback_tokenz&Client.create_presigned_feedback_token  sd   B (.2TZ\\!2!2	 
  
 !+!:" " "D
 
H$566 		M!+!5!5!7!7D
H$677 	M!+!:_ (D0#+r1R7" " "D Kj9I9IKKLLL,,T"" - 
 

 	+H555-@@@@@r7   )r  feedback_configsfeedback_keysr  7Optional[Sequence[Optional[ls_schemas.FeedbackConfig]]](Sequence[ls_schemas.FeedbackIngestToken]c                  	
 |/t          |          t          |          k    rt          d          |sdgt          |          z  }d\  |t          j        ddd          nt	          |t
          j                  r|                                nit	          |t
          j                  r0t          j        |j        |j	        dz  |j	        dz  dz            nt          d	t          |                     t          fd
t          ||          D                       	d	 fdg }t          j        t           j                            5 

fd j                                        D             }t          j        |          D ]5}|                                }|                    d |D                        6	 ddd           n# 1 swxY w Y   |S )a;  Create a pre-signed URL to send feedback data to.

        This is useful for giving browser-based clients a way to upload
        feedback data directly to LangSmith without accessing the
        API key.

        Args:
            run_id:
            feedback_key:
            expiration: The expiration time of the pre-signed URL.
                Either a datetime or a timedelta offset from now.
                Default to 3 hours.
            feedback_config: FeedbackConfig or None.
                If creating a feedback_key for the first time,
                this defines how the metric should be interpreted,
                such as a continuous score (w/ optional bounds),
                or distribution over categorical values.

        Returns:
            The pre-signed URL for uploading feedback data.
        NzBThe length of feedback_keys and feedback_configs must be the same.NNr   rn   r  r  r  r  c                &    g | ]\  }}||d S ))r  rz  rK  r  r  r6   )rx  rz  rK  r  r  r  s      r8   rz  z;Client.create_presigned_feedback_tokens.<locals>.<listcomp>  sE        2L/ %$0'6",",   r7   rB   rC   r   r   rG   r  c                                         d|  di j        t          |pj        id          }t	          j        |           |                                S )Nr  r  r%  r  )rJ  rD  rB  r   rW   rK  r   )rB   r   rM  r  r   s      r8   r  z4Client.create_presigned_feedback_tokens.<locals>.req  s    00,,,  - !7#:dl       1 
 
H /999==??"r7   )max_workersc                D    g | ]\  }}                     ||          S r6   )r  )rx  rB   r   r  r  s      r8   rz  z;Client.create_presigned_feedback_tokens.<locals>.<listcomp>  s=       $GW Wg66  r7   c                0    g | ]}t          j        d i |S )r6   )r  r  )rx  parts     r8   rz  z;Client.create_presigned_feedback_tokens.<locals>.<listcomp>  s)    QQQZ3;;d;;QQQr7   )rB   rC   r   r   rG   r  )rU   rP   r  r  rM   r  r  r  r  r  r9  r  r  cfr  r   r   r  r  r  )r   r  r  r  r  tokensfutsfutrM  r  r  r  r  r  s   ``       @@@@@r8    create_presigned_feedback_tokensz'Client.create_presigned_feedback_tokensK  s   @ 'C,>,>#FVBWBW,W,WT     	; $vM(:(::!+
J#2  JJ
 
H$566 		M#--//JJ
H$677 	M#2_ (D0#+r1R7  JJ Kj9I9IKKLLL      69!#36 6  
 
	# 	# 	# 	# 	# 	# 	# "s43G/H/HIII 		X    (,(<(B(B(D(D  D t,,  ::<<QQQQQ   		 		 		 		 		 		 		 		 		 		 		 		 		 		 		 s    A1GG"%G")r  (Iterator[ls_schemas.FeedbackIngestToken]c             #     K   t          |d          |t          |d          ndd}t          |                     d|                    D ]&\  }}t	          j        di |V  ||dz   |k    r dS 'dS )	a  List the feedback ingest tokens for a run.

        Args:
            run_id: The ID of the run to filter by.
            limit: The maximum number of tokens to return.

        Yields:
            FeedbackIngestToken
                The feedback ingest tokens.
        r  Nr  )r  r  r  r  ry   r6   )rV   ro  r  r  r  r  )r   r  r  r  r  tokens         r8   list_presigned_feedback_tokensz%Client.list_presigned_feedback_tokens  s      " vx00(-(9S___s
 
 "$$%7$GG
 
 	 	HAu 099599999 QUe^^	 	r7   )	queue_idsr  r   r  r  $Iterator[ls_schemas.AnnotationQueue]c             #    K   |d t          |          D             nd|||t          |d          ndd}t          |                     d|                    D ]&\  }}t          j        di |V  ||dz   |k    r dS 'dS )	a  List the annotation queues on the LangSmith API.

        Args:
            queue_ids : List[str or UUID] or None, default=None
                The IDs of the queues to filter by.
            name : str or None, default=None
                The name of the queue to filter by.
            name_contains : str or None, default=None
                The substring that the queue name should contain.
            limit : int or None, default=None

        Yields:
            AnnotationQueue
                The annotation queues.
        Nc                <    g | ]\  }}t          |d | d          S )z
queue_ids[r  )rV   r  s      r8   rz  z1Client.list_annotation_queues.<locals>.<listcomp>  s2    UUUfa#0A00011UUUr7   r  )r  r  r   r  /annotation-queuesr  ry   r6   )r  ro  r  r  AnnotationQueue)r   r  r  r   r  r  r  queues           r8   list_annotation_queueszClient.list_annotation_queues  s      4 ( VU	)@T@TUUUU*(-(9S___s	
 	
 "$$%9&$II
 
 	 	HAu ,        QUe^^	 	r7   )r  queue_idr  ls_schemas.AnnotationQueuec               $   |||pt          t          j                              d}|                     ddd |                                D                       }t          j        |           t          j        di |	                                S )a  Create an annotation queue on the LangSmith API.

        Args:
            name : str
                The name of the annotation queue.
            description : str, optional
                The description of the annotation queue.
            queue_id : str or UUID, optional
                The ID of the annotation queue.

        Returns:
            AnnotationQueue
                The created annotation queue object.
        )r  r  r  r  r  c                    i | ]
\  }}|||S r   r6   r1  s      r8   r   z2Client.create_annotation_queue.<locals>.<dictcomp>  s    AAA41a1=!Q===r7   r  r6   )
rC   rN   r   rJ  r   rW   rK  r  r  r   )r   r  r  r  r  rM  s         r8   create_annotation_queuezClient.create_annotation_queue  s    , &/c$*,,//
 

 ,, AA4::<<AAA - 
 

 	+H555) 
 
mmoo
 
 	
r7   c                J    t          |                     |g                    S )zRead an annotation queue with the specified queue ID.

        Args:
            queue_id (ID_TYPE): The ID of the annotation queue to read.

        Returns:
            ls_schemas.AnnotationQueue: The annotation queue object.
        )r  )r  r  )r   r  s     r8   read_annotation_queuezClient.read_annotation_queue  s%     D//8*/EEFFFr7   )r  c                   |                      ddt          |d           ||d          }t          j        |           dS )a[  Update an annotation queue with the specified queue_id.

        Args:
            queue_id (ID_TYPE): The ID of the annotation queue to update.
            name (str): The new name for the annotation queue.
            description (Optional[str], optional): The new description for the
                annotation queue. Defaults to None.
        r  /annotation-queues/r  )r  r  r  NrJ  rV   rW   rK  )r   r  r  r  rM  s        r8   update_annotation_queuezClient.update_annotation_queue&  s_     ,,B(8Z"@"@BB*  - 
 
 	+H55555r7   c                    |                      ddt          |d           ddi| j                  }t          j        |           dS )zDelete an annotation queue with the specified queue ID.

        Args:
            queue_id (ID_TYPE): The ID of the annotation queue to delete.
        r  r  r  r?  r>  r  Nr  )r   r  rM  s      r8   delete_annotation_queuezClient.delete_annotation_queue;  s_     ,,B(8Z"@"@BB1CT]C - 
 

 	+H55555r7   c                   |                      ddt          |d           dd t          |          D                       }t          j        |           dS )a  Add runs to an annotation queue with the specified queue ID.

        Args:
            queue_id (ID_TYPE): The ID of the annotation queue.
            run_ids (List[ID_TYPE]): The IDs of the runs to be added to the annotation
                queue.
        r  r  r  r$  c           
     V    g | ]&\  }}t          t          |d | d                    'S )zrun_ids[r  r  r  s      r8   rz  z7Client.add_runs_to_annotation_queue.<locals>.<listcomp>U  s6    WWW&!S#hsOqOOO4455WWWr7   r  N)rJ  rV   r  rW   rK  )r   r  r  rM  s       r8   add_runs_to_annotation_queuez#Client.add_runs_to_annotation_queueH  sk     ,,G(8Z"@"@GGGWWIgDVDVWWW - 
 

 	+H55555r7   c          
         |                      ddt          |d           dt          |d                     }t          j        |           dS )a
  Delete a run from an annotation queue with the specified queue ID and run ID.

        Args:
            queue_id (ID_TYPE): The ID of the annotation queue.
            run_id (ID_TYPE): The ID of the run to be added to the annotation
                queue.
        r  r  r  r  r  Nr  )r   r  r  rM  s       r8    delete_run_from_annotation_queuez'Client.delete_run_from_annotation_queueY  s^     ,,d(8Z"@"@ddQWYaHbHbdd
 
 	+H55555r7   r  %ls_schemas.RunWithAnnotationQueueInfoc                   dt          |d           d}|                     d| d| | j                  }t          j        |           t          j        di |                                S )a  Get a run from an annotation queue at the specified index.

        Args:
            queue_id (ID_TYPE): The ID of the annotation queue.
            index (int): The index of the run to retrieve.

        Returns:
            ls_schemas.RunWithAnnotationQueueInfo: The run at the specified index.

        Raises:
            ls_utils.LangSmithNotFoundError: If the run is not found at the given index.
            ls_utils.LangSmithError: For other API-related errors.
        r  r  r  rG  rJ   r  r6   )rV   rJ  rD  rW   rK  r  RunWithAnnotationQueueInfor   )r   r  r  base_urlrM  s        r8   get_run_from_annotation_queuez$Client.get_run_from_annotation_queuei  s      N(J)G)GMMM,,!!%!!M - 
 

 	+H5554GGx}}GGGr7   )rn  r  rw  r~   r  experimentsrn   ls_schemas.ComparativeExperimentc               R   |st          d          |!|                     |d                   j        }|st          d          |pt          t	          j                              |||||p-t          j                            t          j        j	                  i d}|||d         d<   t          d	 |                                D                       }	|                     d
dd|	i          }
t          j        |
           |
                                }t!          j        di |S )a  Create a comparative experiment on the LangSmith API.

        These experiments compare 2 or more experiment results over a shared dataset.

        Args:
            name: The name of the comparative experiment.
            experiments: The IDs of the experiments to compare.
            reference_dataset: The ID of the dataset these experiments are compared on.
            description: The description of the comparative experiment.
            created_at: The creation time of the comparative experiment.
            metadata: Additional metadata for the comparative experiment.

        Returns:
            The created comparative experiment object.
        z$At least one experiment is required.Nr   r?  z A reference dataset is required.)r  r  experiment_idsr)  r  rw  r  r  r~   c                    i | ]\  }}||	S r6   r6   r1  s      r8   r   z8Client.create_comparative_experiment.<locals>.<dictcomp>  s    999DAq1a999r7   r  z/datasets/comparativerk  r  r6   )rP   r  r)  rC   rN   r   r  r  r  r  r  r   rJ  rW   rK  r   r  ComparativeExperiment)r   r  r  rn  r  rw  r~   r  r  serrM  
response_ds               r8   create_comparative_experimentz$Client.create_comparative_experiment  sN   4  	ECDDD$ $ 1 1&q> !2 ! !"  ! 	A?@@@)DJLL)))$5&$T(9(=(=h>O>S(T(T 
  
 (0DM*%99DJJLL999::,,# - 
 
 	+H555]]__
/==*===r7   rq  )
evaluationconcurrency_levelr  project_metadatadataset_versionverboseinput_mapperr  llm_or_chain_factoryr  Optional[Any]r  r  r  r  r  Optional[Callable[[Dict], Any]]c                  K   t          j        dt                     	 ddlm} n# t
          $ r t          d          w xY w |d||| ||||||	|
|d| d{V S )zAsynchronously run the Chain or language model on a dataset.

        .. deprecated:: 0.1.0
           This method is deprecated. Use :func:`langsmith.aevaluate` instead.

        z}The `arun_on_dataset` method is deprecated and will be removed in a future version.Please use the `aevaluate` method instead.r   )arun_on_datasetzlThe client.arun_on_dataset function requires the langchainpackage to run.
Install with pip install langchain)r  r  clientr  r  r  r  r  r  r  r  Nr6   )r   r   rh  langchain.smithr  r'  )r   r  r  r  r  r  r  r  r  r  r  rh  _arun_on_datasets                r8   r  zClient.arun_on_dataset  s      * 	9 		
 	
 	
	KKKKKKK 	 	 	F  	
 &% 
%!5!/%-%#+
 
 
 
 
 
 
 
 
 
 	
s   % ?c                   t          j        dt                     	 ddlm} n# t
          $ r t          d          w xY w |d|||| |||||	|
|d|S )zRun the Chain or language model on a dataset.

        .. deprecated:: 0.1.0
           This method is deprecated. Use :func:`langsmith.aevaluate` instead.

        z{The `run_on_dataset` method is deprecated and will be removed in a future version.Please use the `evaluate` method instead.r   )run_on_datasetzkThe client.run_on_dataset function requires the langchainpackage to run.
Install with pip install langchain)r  r  r  r  r  r  r  r  r  r  r  r6   )r   r   rh  r  r  r'  )r   r  r  r  r  r  r  r  r  r  r  rh  _run_on_datasets                r8   r  zClient.run_on_dataset  s    * 	8 		
 	
 	
	        	 	 	F  	
  
%!5/!%-%#+
 
 
 
 	
s   # =ownerc                L    |                                  }|dk    p
|j        |k    S )zCheck if the current workspace has the same handle as owner.

        Args:
            owner (str): The owner to check against.

        Returns:
            bool: True if the current tenant is the owner, False otherwise.
        -)rQ  tenant_handle)r   r  settingss      r8   _current_tenant_is_ownerzClient._current_tenant_is_owner   s,     %%''|>x5>>r7   actionls_utils.LangSmithUserErrorc                j    t          j        d| d|                                 j         d|           S )NzCannot z% for another tenant.
Current tenant: z,
Requested tenant: )rW   rX   rQ  r  )r   r  r  s      r8   _owner_conflict_errorzClient._owner_conflict_error,  sS     *)f ) )#1133A) )!&) )
 
 	
r7   prompt_owner_and_namec                    |                      dd| d||d          }|                                d         }|r|d         d         nd	S )
a  Get the latest commit hash for a prompt.

        Args:
            prompt_owner_and_name (str): The owner and name of the prompt.
            limit (int): The maximum number of commits to fetch. Defaults to 1.
            offset (int): The number of commits to skip. Defaults to 0.

        Returns:
            Optional[str]: The latest commit hash, or None if no commits are found.
        rG  	/commits/rJ   )r  r  r  commitsr   commit_hashN)rJ  r   )r   r  r  r  rM  r  s         r8   _get_latest_commit_hashzClient._get_latest_commit_hash5  sh     ,,0-000"f55 - 
 

 --//),,3=wqz-((=r7   prompt_identifierlikeDict[str, int]c                    t          j        |          \  }}}|                     dd| d| d|i          }|                                 |                                S )a  Like or unlike a prompt.

        Args:
            prompt_identifier (str): The identifier of the prompt.
            like (bool): True to like the prompt, False to unlike it.

        Returns:
            A dictionary with the key 'likes' and the count of likes as the value.

        Raises:
            requests.exceptions.HTTPError: If the prompt is not found or
            another error occurs.
        r  z/likes/rJ   r  r  )rW   parse_prompt_identifierrJ  raise_for_statusr   )r   r  r  r  prompt_namer  rM  s          r8   _like_or_unlike_promptzClient._like_or_unlike_promptJ  st      !) @AR S S{A,,3e33k3364. - 
 
 	!!###}}r7   c           	         t          j        |          \  }}}|                     |          s| j         d| d| d|dd          S |                                 }| j         d| d|dd          d|j         S )zGet a URL for a prompt.

        Args:
            prompt_identifier (str): The identifier of the prompt.

        Returns:
            str: The URL for the prompt.

        z/hub/rJ   ra   N   z	/prompts/z?organizationId=)rW   r  r  r2  rQ  r  )r   r  r  r  r  r  s         r8   _get_prompt_urlzClient._get_prompt_urla  s     +3*J+
 +
'{K ,,U33 	SnRR5RR;RRRaRRRR%%''~ - - - -k"1"o - -'{- -	
r7   c                8    |                      |          }|rdndS )zCheck if a prompt exists.

        Args:
            prompt_identifier (str): The identifier of the prompt.

        Returns:
            bool: True if the prompt exists, False otherwise.
        TF)
get_prompt)r   r  rk   s      r8   _prompt_existszClient._prompt_existsx  s%     !233(tt5(r7   c                0    |                      |d          S )zLike a prompt.

        Args:
            prompt_identifier (str): The identifier of the prompt.

        Returns:
            A dictionary with the key 'likes' and the count of likes as the value.

        Tr  r  r   r  s     r8   like_promptzClient.like_prompt  s     **+<4*HHHr7   c                0    |                      |d          S )zUnlike a prompt.

        Args:
            prompt_identifier (str): The identifier of the prompt.

        Returns:
            A dictionary with the key 'likes' and the count of likes as the value.

        Fr  r  r  s     r8   unlike_promptzClient.unlike_prompt  s     **+<5*IIIr7   r  desc)r  r  	is_publicis_archived
sort_fieldsort_directionr  r  r  r  ls_schemas.PromptSortFieldr  Literal['desc', 'asc']ls_schemas.ListPromptsResponsec          	         |||rdn|dnd|rdnd||||rdndd}|                      dd|          }	t          j        di |	                                S )	a  List prompts with pagination.

        Args:
            limit (int): The maximum number of prompts to return. Defaults to 100.
            offset (int): The number of prompts to skip. Defaults to 0.
            is_public (Optional[bool]): Filter prompts by if they are public.
            is_archived (Optional[bool]): Filter prompts by if they are archived.
            sort_field (ls_schemas.PromptsSortField): The field to sort by.
              Defaults to "updated_at".
            sort_direction (Literal["desc", "asc"]): The order to sort by.
              Defaults to "desc".
            query (Optional[str]): Filter prompts by a search query.

        Returns:
            ls_schemas.ListPromptsResponse: A response object containing
            the list of prompts.
        r  Nfalse)r  r  r  r  r  r  r  match_prefixrG  /repos/r  r6   )rJ  r  ListPromptsResponser   )
r   r  r  r  r  r  r  r  r  rM  s
             r8   list_promptszClient.list_prompts  s    : #SI4It%0=66g$,&+5FF
 
 ,,UIf,MM-@@@@@r7   Optional[ls_schemas.Prompt]c                    t          j        |          \  }}}	 |                     dd| d|           }t          j        di |                                d         S # t           j        $ r Y dS w xY w)a  Get a specific prompt by its identifier.

        Args:
            prompt_identifier (str): The identifier of the prompt.
            The identifier should be in the format "prompt_name" or "owner/prompt_name".

        Returns:
            Optional[ls_schemas.Prompt]: The prompt object.

        Raises:
            requests.exceptions.HTTPError: If the prompt is not found or
            another error occurs.
        rG  r  rJ   repoNr6   )rW   r  rJ  r  Promptr   r  r   r  r  r  r  rM  s         r8   r  zClient.get_prompt  s     !) @AR S S{A	008W%8W8W+8W8WXXH$??x}}v'>???. 	 	 	44	s   AA A21A2r  readmer  r  r  ls_schemas.Promptc                  |                                  }|r|j        st          j        d          t          j        |          \  }}}	|                     |          s|                     d|          ||pd|pd|pg |d}
|                     dd|
          }|                                 t          j
        d
i |                                d	         S )a  Create a new prompt.

        Does not attach prompt object, just creates an empty prompt.

        Args:
            prompt_name (str): The name of the prompt.
            description (Optional[str]): A description of the prompt.
            readme (Optional[str]): A readme for the prompt.
            tags (Optional[Sequence[str]]): A list of tags for the prompt.
            is_public (bool): Whether the prompt should be public. Defaults to False.

        Returns:
            ls_schemas.Prompt: The created prompt object.

        Raises:
            ValueError: If the current tenant is not the owner.
            HTTPError: If the server request fails.
        Cannot create a public prompt without first
creating a LangChain Hub handle. You can add a handle by creating a public prompt at:
https://smith.langchain.com/prompts)r  zcreate a promptr[  )repo_handler  r  r  r  r  r  r  r  r6   )rQ  r  rW   rX   r  r  r  rJ  r  r  r  r   )r   r  r  r  r  r  r  r  r  r  r   rM  s               r8   create_promptzClient.create_prompt  s   6 %%'' 	X3 	-6   !) @AR S S{A,,5,99 	G,,->FFF '&,"lJB"<
 <
 ,,VYT,JJ!!### ;;8==??6#:;;;r7   parent_commit_hashobjectr%  c                  |                      |          st          j        d          	 ddlm} n# t
          $ r t          d          w xY w ||          }t          j        |          }t          j        |          \  }}}	| d| }
|dk    s|| 	                    |
          }||d}| 
                    d	d
|
 |          }|                                d         d         }|                     |
 d|           S )a  Create a commit for an existing prompt.

        Args:
            prompt_identifier (str): The identifier of the prompt.
            object (Any): The LangChain object to commit.
            parent_commit_hash (Optional[str]): The hash of the parent commit.
                Defaults to latest commit.

        Returns:
            str: The url of the prompt commit.

        Raises:
            HTTPError: If the server request fails.
            ValueError: If the prompt does not exist.
        z0Prompt does not exist, you must create it first.r   )r7  zvThe client.create_commit function requires the langchain_corepackage to run.
Install with `pip install langchain_core`rJ   r  N)parent_commitmanifestr  r  r  commitr  ra   )r  rW   r  langchain_core.load.dumpr7  r'  r   r   r  r  rJ  r  )r   r  r&  r%  r7  json_objectmanifest_dictr  r  r  r  request_dictrM  r  s                 r8   create_commitzClient.create_commit  sd   , ""#455 	1B  	6666666 	 	 	M  	 eFmm
;// ( @AR S S{A#( 8 8; 8 8))-?-G!%!=!=>S!T!T);WW,,7 577l - 
 
 mmooh/>##'<$L$L{$L$LMMMs	   2 A)r  r  r  r  r  c               `   |                                  }|r|j        st          d          i }|||d<   |||d<   |||d<   |||d<   |||d<   t          j        |          \  }	}
}|                     dd	|	 d
|
 |          }|                                 |                                S )a$  Update a prompt's metadata.

        To update the content of a prompt, use push_prompt or create_commit instead.

        Args:
            prompt_identifier (str): The identifier of the prompt to update.
            description (Optional[str]): New description for the prompt.
            readme (Optional[str]): New readme for the prompt.
            tags (Optional[Sequence[str]]): New list of tags for the prompt.
            is_public (Optional[bool]): New public status for the prompt.
            is_archived (Optional[bool]): New archived status for the prompt.

        Returns:
            Dict[str, Any]: The updated prompt data as returned by the server.

        Raises:
            ValueError: If the prompt_identifier is empty.
            HTTPError: If the server request fails.
        r!  Nr  r  r  r  r  r  r  rJ   r  )rQ  r  rP   rW   r  rJ  r  r   )r   r  r  r  r  r  r  r  r   r  r  r  rM  s                r8   update_promptzClient.update_promptF  s    : %%'' 	X3 	6   <>""-D#DN  )D""-DDL ( @AR S S{A,,4u44{444 - 
 
 	!!###}}r7   c                    t          j        |          \  }}}|                     |          s|                     d|          |                     dd| d|           }|                                 dS )a6  Delete a prompt.

        Args:
            prompt_identifier (str): The identifier of the prompt to delete.

        Returns:
            bool: True if the prompt was successfully deleted, False otherwise.

        Raises:
            ValueError: If the current tenant is not the owner of the prompt.
        zdelete a promptr  r  rJ   N)rW   r  r  r  rJ  r  r  s         r8   delete_promptzClient.delete_prompt  s     !) @AR S S{A,,U33 	G,,->FFF,,X7V7V7V7V7VWW!!#####r7   include_modelr5  ls_schemas.PromptCommitc          
        t          j        |          \  }}}	 t          j        | j        j        d          }n,# t
          $ r t                              d           d}Y nw xY w|s3|dk    r-|                     | d|           }|t          d          |}| 	                    dd	| d| d| |rd
nd           }t          j        di ||d|                                S )a"  Pull a prompt object from the LangSmith API.

        Args:
            prompt_identifier (str): The identifier of the prompt.

        Returns:
            ls_schemas.PromptObject: The prompt object.

        Raises:
            ValueError: If no commits are found for the prompt.
        z0.5.23zHFailed to parse LangSmith API version. Defaulting to using optimization.Tr  rJ   NzNo commits foundrG  r  z?include_model=truer[  r  r  r6   )rW   r  rm  r   r   rP   r   	exceptionr  rJ  r  PromptCommitr   )	r   r  r5  r  r  r  use_optimizationlatest_commit_hashrM  s	            r8   pull_prompt_commitzClient.pull_prompt_commit  sp   " +3*J+
 +
'{K	$'C	!8     	$ 	$ 	$Z    $		$   	1K8$;$;!%!=!=>V>V>V>V!W!W!) !34440,,DE D DK D D+ D,9A((rD D
 
 & 
 
{FFhmmooF
 
 	
s   : &A#"A#r  r  r5  'Iterator[ls_schemas.ListedPromptCommit]c             #    K   t          j        |          \  }}}|t          d|          n|||d}d}		 ||d<   |                     dd| d	| d	|
          }
|
                                }|d         }|d         }|sdS |D ]*}|	|	|k    r dS t          j        di ||d|V  |	dz  }	+|t          |          z  }||k    rdS )a  List commits for a given prompt.

        Args:
            prompt_identifier (str): The identifier of the prompt in the format 'owner/repo_name'.
            limit (Optional[int], optional): The maximum number of commits to return. If None, returns all commits. Defaults to None.
            offset (int, optional): The number of commits to skip before starting to return results. Defaults to 0.
            include_model (bool, optional): Whether to include the model information in the commit data. Defaults to False.

        Returns:
            Iterator[ls_schemas.ListedPromptCommit]: An iterator of ListedPromptCommit objects representing the commits.

        Yields:
            ls_schemas.ListedPromptCommit: A ListedPromptCommit object for each commit.

        Note:
            This method uses pagination to retrieve commits. It will make multiple API calls if necessary to retrieve all commits
            or up to the specified limit.
        Nr  r>  r   Tr  rG  r  rJ   r  r  rq   r8  ry   r6   )rW   r  ro  rJ  r   r  ListedPromptCommitrU   )r   r  r  r  r5  r  r  r  r  r  rM  valr   rq   its                  r8   list_prompt_commitszClient.list_prompt_commits  sO     4 !) @AR S S{A ).(9Se___u*
 

 	%F8002E22K222 1  H
 --//C	NELE   $eFF 3   %{AAbA     Qc%jj F/	r7   c          	     t   	 ddl m} ddlm} ddlm} ddlm} ddlm	} ddl
m}m}	 n# t          $ r t          d          w xY w	 dd	lm}
 n%# t          $ r t           j        d
             }
Y nw xY w|                     ||          } |
            5   |t'          j        |j                            }ddd           n# 1 swxY w Y   t-          ||          s%t-          ||	          rt-          |j        |          rt-          ||          r|n-t-          ||	          rt-          |j        |          r|j        nd}|t1          j        d          |j        i |_        |j                            |j        |j        |j        d           |r!t-          ||	          rt-          |j        |          rt?          |j                   dk    rt-          |j!        |          st-          |j!        |          rt-          |j!        j"        |          rytG          |	|j        |j!        j"        z            }t?          |j                   dk    r<|j         d         } |	|j         |j$        di i |j!        j%        |j!                  }n)|}n&t-          |j!        |          r|j        |j!        z  }n	 |S )a  Pull a prompt and return it as a LangChain PromptTemplate.

        This method requires `langchain_core`.

        Args:
            prompt_identifier (str): The identifier of the prompt.

        Returns:
            Any: The prompt object in the specified format.
        r   )BaseLanguageModel)r   )BaseOutputParser)BasePromptTemplate)StructuredPrompt)RunnableBindingRunnableSequenceztThe client.pull_prompt function requires the langchain_corepackage to run.
Install with `pip install langchain_core`)suppress_langchain_beta_warningc               3     K   d V  d S r   r6   r6   r7   r8   rL  z;Client.pull_prompt.<locals>.suppress_langchain_beta_warning  s      r7   r4  Nz-Prompt object is not a valid prompt template.)lc_hub_ownerlc_hub_repolc_hub_commit_hashr>   rn   ry   r6   )&#langchain_core.language_models.baserF  langchain_core.load.loadr   langchain_core.output_parsersrG  langchain_core.promptsrH  !langchain_core.prompts.structuredrI  langchain_core.runnables.baserJ  rK  r'  langchain_core._apirL  
contextlibcontextmanagerr=  r   r7  r)  rM   firstrW   r  r~   r  r  r  r  rU   stepslastboundr   bindrh  )r   r  r5  rF  r   rG  rH  rI  rJ  rK  rL  prompt_objectrk   prompt_templateseqrebound_llms                   r8   pull_promptzClient.pull_prompt  s   	MMMMMM666666FFFFFFAAAAAAJJJJJJWWWWWWWWW 	 	 	M  	
	KKKKKKK 	 	 	&  '&  	 //] 0 
 
 -,.. 	? 	?U4:m&<==>>F	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? v122	&"233	 6<);<<	 f&899 "&*:;;"6<1CDDFLL   &-C   '/+-($++$1$7#0#5*7*C    	6#344	 6<)9::	 FL!!Q&&z&+GW/X/X& &+77 J!#4= =  +V\FK<M-MNNsy>>Q&&"%)A,K--((BB+Afk.@+ABB FF !FFFK):;; +1<&++Es-   &) AA A0/A0#CC
C)r&  r%  r  r  r  r  c               <   |                      |          r8t          d ||||fD                       r|                     |||||           n|                     |||nd|||           ||                     |          S |                     |||          }|S )a  Push a prompt to the LangSmith API.

        Can be used to update prompt metadata or prompt content.

        If the prompt does not exist, it will be created.
        If the prompt exists, it will be updated.

        Args:
            prompt_identifier (str): The identifier of the prompt.
            object (Optional[Any]): The LangChain object to push.
            parent_commit_hash (str): The parent commit hash.
              Defaults to "latest".
            is_public (Optional[bool]): Whether the prompt should be public.
                If None (default), the current visibility status is maintained for existing prompts.
                For new prompts, None defaults to private.
                Set to True to make public, or False to make private.
            description (Optional[str]): A description of the prompt.
              Defaults to an empty string.
            readme (Optional[str]): A readme for the prompt.
              Defaults to an empty string.
            tags (Optional[Sequence[str]]): A list of tags for the prompt.
              Defaults to an empty list.

        Returns:
            str: The URL of the prompt.

        c              3     K   | ]}|d uV  	d S r   r6   )rx  params     r8   r2  z%Client.push_prompt.<locals>.<genexpr>  s8        &+T!     r7   r  NF)r  r  r  r  )r  r$  )r  anyr1  r#  r  r/  )	r   r  r&  r%  r  r  r  r  r^   s	            r8   push_promptzClient.push_prompt`  s   N 011 	  09;PT/U     	 ""% +!' #    !'0'<))%'     >'':K'LLL   1 ! 
 

 
r7   c                    d| _         dS )z2Manually trigger cleanup of the background thread.TN)r   r7  s    r8   cleanupzClient.cleanup  s    #r7   r   )rB   r   r   r   r   r   r   r   r   r   r   r   r   r_   r   r  r   r  r   r  r   r  r   r   rG   r   )rG   rC   )rG   r   )rG   rE  )rG   rN  )rR  rS  rG   r   )rb  rc  rd  rC   r\  re  r]  rE   r^  rf  r_  rf  r`  rg  ra  rC   rh  r   rG   ri  )rS   rC   r  r  rG   r  )
rS   rC   r  r  r  r  r  rC   rG   r  )r  r  r  rC   r  r  r  r  r  r   r  r  rG   r  )r  r  r  r  r  r  r  r   r  r   r  r  rG   r  )FF)r  r  r  r_   r  r_   rG   r|   )r  r  rG   r   )r  r  r
  r_   rG   r  )r  rC   r  r  r  r  r  r   r  r   rh  r   rG   r   )r  r|   )r  r|   )r  r|   )r+  r,  rG   r   r  )rM  rN  r  rN  rL  r_   rG   r   )r  r`  ra  rC   )r+  rf  rG   r   )rw  r&   rv  rE   )r  r   r  r   r  r  r8  r   r  r  r  r  r.  r  r  r  r  r  r5  r  rh  r   rG   r   )r  r|   rG   r   )r  r  rG   r  r   )r  r   r  r_   rG   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  r8  r  r  r  r  r  r  rS  rh  r   rG   r  )"r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r   r  r   r8  r  r  r   r  r   r  r   r  r   r  r  r  r   rG   r  )r  r  r  r   r  r  rG   rC   )r  r   r  r  rG   rC   )r  r   rG   r   )r  r   rG   r   )r  r   rG   r_   )r  r  r  r  rG   r  )r  r  r  r  rG   r  )r  r  r  r   rG   r  )r  r   rG   r   )r  rC   rG   r  )r  rC   r  r  rG   r  )r!  rC   r  r  r  r   r   r   r  rS  rG   r"  )r  rC   r  r   r~   r  r'  r_   r(  r  r)  r  rG   r*  )r  r   r  r   r  r   r~   r  r(  r  r  r  rG   r*  )rG   r   )rG   r   )r  r   r  r   r:  r_   rG   r;  )r  rC   r  r   rG   r_   )r  r  r  r   rG   r  )NNNNNNNN)r  r  r  r   r   r   r)  r  ri  r   rj  r  r  rS  r~   rk  rG   rl  )r  r   r  r   rG   r   )r  rC   r  r   r  ru  rs  rk  rt  rk  r~   r  rG   r  )r  r   r  r   rG   r_   )r  r   r  r  rG   r  )
r  r  r  r   r  r  r  r  rG   r  )r  r   r  r   rG   r  )r  r  r  r   r  r   r  r   r~   rk  r  rS  rG   r  )r  r  r  r   rG   r   )
r  r  r  r   r  r  r  rC   rG   r   )
r  r  r  r   r  r   r  rS  rG   r  )
r  r  r  r   r  r  r  r   rG   r  )r  rC   r  r   r  r   rG   r  )r  r   rG   ru  )NNNN)rk   rC   r  r   r  r  r  r   rw  r  rG   r  )r  r  r  r  r  r  r  r   rw  r  rG   r  )NNN)
r  r  r  r  r  r   rw  r  rG   r  )r  r  r  r  r~   r  r  r  r  r  r  r  r  r  r  r   rh  r   rG   r   )r  r  r  r  r  r   rw  r  r  r  r~   r  rT   r  rF  r  r  r  rG   r  )rF  r   r  r  rG   r  )NNNNNT)r  r  r  r   r  r  r  r  r  r  r  r_   r  rE   r  rS  r~   r  r  r   rh  r   rG   r  )r  r   r  rC   rh  r   rG   r   )r  r|   r  rE   r  r   r  r   rh  r   rG   r  )rF  r   r  rk  r  r  r~   r  rT   r  r  r  rG   r  )r  r  r  r   r  r  r~   r  r  r  r  r  rG   r  )rF  r   rG   r   )r  r  r  r   r  r  rG   r  )r  r  r  r   r  rC   r  r  r  r_   rG   r   )r  r  r  r_   rG   r  )rI  r  r  r  rG   r   )rc  r%  r$  r   rG   r&  )r  r  r:   r9  r8  rk  r  r:  r  r_   rG   r*  )rA  r%  r  rC  r8  rk  r  r  rB  rD  rG   r&  )r  rT  r:   r9  r8  rk  r  r:  r  r_   rG   r*  )&r  r  rF  rC   rI  rZ  r   r[  rJ  r\  r-  r]  r8  rk  rL  r^  r  r  rW  r  rK  r_  r]  rE   r  r  rX  r  rY  r  r  r  r  r  rh  r   rG   r`  )rW  r   rI  rZ  r   rr  rJ  r\  r-  r]  rG   r   )rW  r   rG   r`  )r  r  rz  r  rL  r{  r  rS  rh  r   rG   r|  )rW  r   rG   r   )r  rA   rI  rZ  r   rr  rJ  r\  r-  r]  r~   r  rG   r   )r  r   rz  rC   r  r  rK  r_  rW  r  rG   r  )
r  r   r  r  r  r  r  r  rG   r  )r  r   r  rS  rG   r  )
r  r  r  r   r   r   r  rS  rG   r  )r  rC   r  r   r  r  rG   r  )r  r   rG   r  )r  r   r  rC   r  r   rG   r   )r  r   rG   r   )r  r   r  r  rG   r   )r  r   r  r   rG   r   )r  r   r  rE   rG   r  )r  rC   r  r  rn  r  r  r   rw  r  r~   rk  r  r  rG   r  )r  rC   r  r   r  r  r  rE   r  r   r  rk  r  r  r  r_   r  r  r  r   rh  r   rG   r  )r  rC   rG   r_   )r  rC   r  rC   rG   r  )ry   r   )r  rC   r  rE   r  rE   rG   r   )r  rC   r  r_   rG   r  )r  rC   rG   rC   )r  rC   rG   r_   )r  rC   rG   r  )r  rE   r  rE   r  r  r  r  r  r  r  r  r  r   rG   r  )r  rC   rG   r  )r  rC   r  r   r  r   r  r  r  r_   rG   r  )r  rC   r&  r   r%  r   rG   rC   )r  rC   r  r   r  r   r  r  r  r  r  r  rG   r  )r  rC   rG   r   )r  rC   r5  r  rG   r6  )
r  rC   r  rS  r  rE   r5  r_   rG   r?  )r  rC   r5  r  rG   r   )r  rC   r&  r  r%  rC   r  r  r  r   r  r   r  r  rG   rC   )rG   r   )r2   r3   r4   r5   	__slots__r   r4  r8  propertyr:  r2  rD  r   rQ  rZ  rJ  r  r  r  r  r  r  r  r  staticmethodr  r  r  r!  r  r  rK  r_  r=  rk  ru  rh  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r&  r0  r3  r  r  rW   xor_argsr  rA  rh  rp  rr  rz  r}  r
  r  r  r  r  r  r  r  r  r%  r  r  r  r  r  r  rJ  r"   r  r  r  r  r
  r  r  r  r#  r7  r>  r?  rV  rP  ri  rG  rv  ry  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	  PromptSortField
updated_atr  r  r#  r/  r1  r3  r=  rD  rc  rh  rj  r6   r7   r8   r   r   ]  s       88  I2 "&w% "&(,<@!%.2#'7;EIFJ@D-1w% w% w% w% w% w%r	X 	X 	X 	X3 3 3 3 ( ( ( X( B B B XB    X     X4      . -1"#<@=AMQm
 m
 m
 m
 m
 m
` 6:$! $! $! $! $! $!T  $17-0 -0 -0 -0 -0 -0l &*3=3F3I/
 /
 /
 /
 /
 /
n #%)3=3F3IO
 O
 O
 O
 O
 O
h 	1 1 1 1 1f    \ 6;     H '+%)I) I) I) I) I) I)V   ) ) ) )+ + + +C C C CR  M3 "M3 M3 M3 M3 M3 M3^N N N N24 4 4 4.  _3 "_3 _3 _3 _3 _3 _3B UV - - - - - -f #04#!%"&+/ $$( Y# Y# Y# Y# Y# Y#v    " " " "J 8=    8 CG<@"&&*26# $&*%)"&+/26 $/3*.#%A A A A A AL '+#'(,"&-1/39=$("& $# $&*%)"&*.%U U U U U Uv '+(,*
 *
 *
 *
 *
 *
X KO : : : : : :"6 6 6 6D D D D*        MQK K K K K" PT	B 	B 	B 	B 	B )-&
 '+	&
 &
 &
 &
 &
 &
T )-
 '+	
 
 
 
 
 
66 6 6 6
 
 
 
$ KO
 
 
 
 
 
. 04"'+## # # # # #R &*#'(,266U 6U 6U 6U 6U 6Ux #%)#'(,040U 0U 0U 0U 0U 0Ud   (    X566 %)&*#+
 +
 +
 +
 +
 76+
\ AE     4 )-&*	bF bF bF bF bF bFL 04"'+2604)-#-1C C C C CJ X566/3QU6 6 6 6 6 7666 &*)3)<)?2637#'7
 7
 7
 7
 7
 7
t 04QU     . X566 '+(,	0
 0
 0
 0
 0
 760
h )-I= '+	I= I= I= I= I= I=X +/QU     D 04#'&*/3-1#' ' ' ' ' 'R X566 )-&*	6 6 6 6 6 766: )-&*	76 76 76 76 76 76x )-&* $#! ! ! ! ! !L )-&*-1!1< 1< 1< 1< 1< 1<n )-&*B B B B B BH! ! ! ! X566 %)(,&*26
 
 
 
 76
" X566 (,&*26%
 %
 %
 %
 76%
T )-&*26M
 M
 M
 M
 M
f DHDH@D@D59(,&*R6 R6 R6 R6 R6 R6h X566 )-&*26/304+/(,+/E
 E
 E
 E
 76E
P LP
 
 
 
 
 
4 )-&*379=*.#G ##' $G G G G G GR 
 	2 2 2 2 2 Y2D  !%V V V V V YVx ,0/3#'+/(,/ / / / / /j @DCG7;@D=AP P P P P Pd6 6 6 6$ )-&*9=" " " " " "N )-&* &6 &6 &6 &6 &6 &6P   <!" !" !" !"R "&% % % % % %X 15  %- - - - - -h )-04(,. 6:. . . . . .j 15  %- - - - - -h 04(,(,$(04 )-+/)-?C"$(,7;/3 $&*+g g g g g gZ 04:>(,$('6 '6 '6 '6 '6 '6R6 6 6 6, 0404RV#, , , , , ,\6 6 6 6$ 0446
 ;?(,$(#'46 46 46 46 46 46v HL?C)-=A =A =A =A =A =AH HL b b b b b bP  $	     @ .2"'+#( ( ( ( ( (\ &*&*"
 "
 "
 "
 "
 "
H
G 
G 
G 
G MQ6 6 6 6 6 6*6 6 6 66 6 6 6"6 6 6 6 H H H H< 04%)26-1 $8> 8> 8> 8> 8> 8>~ %)!"&*59CG8<%)/
 /
 /
 /
 /
 /
l %)!"&*59CG8<%)1
 1
 1
 1
 1
 1
f
? 
? 
? 
?
 
 
 
 IJ> > > > >*   .
 
 
 
.
) 
) 
) 
)
I 
I 
I 
I
J 
J 
J 
J $(&+1;1K1V17#*A *A *A *A *A *AX   2 &* $(,2< 2< 2< 2< 2< 2<r -13N 3N 3N 3N 3N 3Nr &* $(,$(&*8 8 8 8 8 8t$ $ $ $. ).	.
 .
 .
 .
 .
 .
h  $#9 9 9 9 9 9x JO` ` ` ` ` `L !%"*$(%) $(,D D D D D DL$ $ $ $ $ $r7   r   r  r   model_kwargsrk  r|   c                   	 ddl m} n# t          $ r t          d          w xY w |            }|pi }|                    dd          }	  |j        | fd|i|S # t
          $ r}t          j        d|           d}~ww xY w)a%  Convert a prompt to OpenAI format.

    Requires the `langchain_openai` package to be installed.

    Args:
        messages (Any): The messages to convert.
        model_kwargs (Optional[Dict[str, Any]]): Model configuration arguments including
            `stop` and any other required arguments. Defaults to None.

    Returns:
        dict: The prompt in OpenAI format.

    Raises:
        ImportError: If the `langchain_openai` package is not installed.
        ls_utils.LangSmithError: If there is an error during the conversion process.
    r   )
ChatOpenAIzThe convert_prompt_to_openai_format function requires the langchain_openaipackage to run.
Install with `pip install langchain_openai`stopNz#Error converting to OpenAI format: )langchain_openairs  r'  r  _get_request_payloadrd   rW   r  )r  rq  rs  openairt  r   s         r8   convert_prompt_to_openai_formatrx    s    (
/////// 
 
 
K
 
 	

 Z\\F%2LFD))DQ*v*8OO$O,OOO Q Q Q%&OA&O&OPPPQs    	 #A 
B%A<<Bc                r   	 ddl m} n# t          $ r t          d          w xY w|pi }|                    dd          }|                    dd          }|                    dd          } |d|||d	|}	 |                    | |
          S # t
          $ r}t          j        d|           d}~ww xY w)a  Convert a prompt to Anthropic format.

    Requires the `langchain_anthropic` package to be installed.

    Args:
        messages (Any): The messages to convert.
        model_kwargs (Optional[Dict[str, Any]]):
            Model configuration arguments including `model_name` and `stop`.
            Defaults to None.

    Returns:
        dict: The prompt in Anthropic format.
    r   )ChatAnthropiczThe convert_prompt_to_anthropic_format function requires the langchain_anthropic package to run.
Install with `pip install langchain_anthropic`
model_namezclaude-3-haiku-20240307rt  NrH  )r{  rH  rt  )rt  z&Error converting to Anthropic format: r6   )langchain_anthropicrz  r'  r  rv  rd   rW   r  )r  rq  rz  r{  rt  rH  	anthropicr   s           r8   "convert_prompt_to_anthropic_formatr~    s    "
5555555 
 
 
=
 
 	

  %2L!!,0IJJJFD))Dy$//G wT =I IT--hT-BBB T T T%&Rq&R&RSSSTs    	 #9B 
B6B11B6)r>   r?   )
r@   rA   rB   rC   rD   rE   rF   rC   rG   rH   )r^   rC   rG   r_   )rG   r   )r   r   rG   r   )rB   rC   r   r   rG   r   )rG   r   )r   r   rG   r   r   )r   r   rK   r   rG   r   )r   r   rG   r   )r   r   r   r_   rG   r   )r   r   r   r_   )r  r   rq  rk  rG   r|   )r5   
__future__r   r  r:  r  r  r  rX  r  r#  r}   importlib.metadatar  r[  r   loggingr   r  r  r  rb  typingrN   r   r  inspectr   r  r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   urllibr   rQ   r  r   r   requests_toolbeltr   rz  typing_extensionsr   urllib3.poolmanagerr   urllib3.utilr   r@  r   r  r   r  r   rW   langsmith._internalr   &langsmith._internal._background_threadr    r!   r  #langsmith._internal._beta_decoratorr"   langsmith._internal._constantsr#   r$   r%   langsmith._internal._multipartr&   r'   langsmith._internal._operationsr(   r)   r*   r+   r,   r-   r.   langsmith._internal._serder/   r  zoneinfor0   r'  r[  rb  r5  r:   r/  	getLoggerr2   r   r  rB  WARNED_ATTACHMENTSr<   __annotations__r   hexr|  
parametersr   r]   re   rO   rC   r   r  r   r   r   r   r   rV   overloadr   r$  r   HTTPAdapterr   r   rx  r~  r6   r7   r8   <module>r     s  
 
 
 # " " " " "                             				       				                                                             $ ) ( ( ( ( (  2 2 2 2 2 2      ( ' ' ' ' ' ' ' ' ' ' '           # # # # # # + + + + + + ' ' ' ' ' ' ' ' ' ' ' '           : 9 9 9 9 9         
                         A @ @ @ @ @(!!!!!!! ( ( (( ( ( ( ( ( ( ( ( ((  ?>>>>>> 
	8	$	$#'#$<==	  	        4:<<,		'0B0B0MM  	    :   ( 	3
H

3 3 3 3B	 	 	 	   0   ($ $ $ $&      J J J  J CG     
 QV       Q   T T T T T-9 T T T8KU$ KU$ KU$ KU$ KU$ KU$ KU$ KU$`j .2$Q $Q $Q $Q $QR .2&T &T &T &T &T &T &Ts   D D-,D-