o
    +if                    @  s  d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlmZmZ ddlmZmZ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( ddl)m*Z+ ddl,Z,ddl,m-Z. dd	l/m0Z0 ddl1Z1dd
l1m2Z3 ddl1m4Z5 ddl1m6Z7 ddl8m9Z: erddl;Z<e
=e>Z?e
=d@e7A  dcddZBddddZCdcddZDe'ejEeFf ZGdeddZHeFeIeJeKfZLdZMdfdgd$d%ZNdhd)d*ZOdid-d.ZPdjd0d1ZQdkd2d3ZRdld4d5ZSdmd8d9ZTdnd;d<ZUdodAdBZVedCdDG dEdF dFZWG dGdH dHZX	CdpdqdOdPZYdrdSdTZZdUZ[dVZ\dWZ]dsd[d\Z^dtd_d`Z_dtdadbZ`dS )uzThe LangSmith Client.    )annotationsN)	dataclassfield)EmptyPriorityQueueQueue)TYPE_CHECKINGAnyCallableDefaultDictDictIterableIteratorListMappingOptionalSequenceTupleTypeUnioncast)parse)adapters)Retry)env)schemas)utils)	evaluatorzurllib3.connectionpoolurlstrreturnboolc                 C  sV   zt | jdd }t|}|dkp|dp|dW S  tjy*   Y dS w )zCheck if the URL is localhost.

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

    Returns
    -------
    bool
        True if the URL is localhost, False otherwise.
    :r   z	127.0.0.1z0.0.0.0z::F)urllib_parseurlsplitnetlocsplitsocketgethostbyname
startswithgaierror)r   r%   ip r,   I/var/www/html/corbot_env/lib/python3.10/site-packages/langsmith/client.py_is_localhost<   s   
r.   url_or_tokenapi_urlTuple[str, str]c                 C  sj   z
t |  || fW S  ty   Y nw t| }|jd}t|dkr-|d }||fS t	d|  )z*Parse a public dataset URL or share token./   zInvalid public dataset URL: )
uuidUUID
ValueErrorr#   urlparsepathr&   lenls_utilsLangSmithUserError)r/   r0   
parsed_url
path_parts
token_uuidr,   r,   r-   _parse_token_or_urlQ   s   


r@   c                 C  s8   zt | jdd }|dW S  ty   Y dS 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"   r   zlangchain.comF)r#   r$   r%   r&   endswith	Exception)r   r%   r,   r,   r-   _is_langchain_hostedd   s   rC   r   c                  C  sT   t dg ddddd} tjd}ttt|ddk}|r#d	| d
< t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  i          ?F)totalstatus_forcelistbackoff_factorraise_on_redirectraise_on_statusurllib3.)      Nallowed_methodsr,   )	dict	importlibmetadataversiontuplemapintr&   r   )retry_paramsurllib3_versionuse_allowed_methodsr,   r,   r-   _default_retry_config{   s   
r[   r3   objr	   depthrW   c           	        sB  z t krz
ttW W S  ty   t Y W S w ttjr) W S tt	j
r4tW S d u s=ttr@W S ttrKdW S ttttfr_ fddtD W S ttrp fdd D W S g d}|D ]O\}}t|rtt|rzt|}|r||dn| }t|W   W S  ty } ztdt d	|  tW  Y d }~  W S d }~ww qvtrtW S td
rfddjD }ntdrt}ntW S  fdd| D W S  ty  } ztdt d	|  tW  Y d }~S d }~ww )Nzutf-8c                   s   g | ]	}t | d  qS rN   _serialize_json).0xr]   r,   r-   
<listcomp>       z#_serialize_json.<locals>.<listcomp>c                   s    i | ]\}}|t | d  qS r^   r_   ra   kvrc   r,   r-   
<dictcomp>   s     z#_serialize_json.<locals>.<dictcomp>))model_dump_jsonT)jsonT)to_jsonFexclude_nonezFailed to serialize z
 to JSON: 	__slots__c                   s   i | ]	}|t  |d qS N)getattr)ra   slot)r\   r,   r-   ri      re   __dict__c                   s2   i | ]\}}||urt | d  dnt|qS )rN   rc   )r`   reprrf   r]   r\   r,   r-   ri      s     ) 
_MAX_DEPTHrk   loadsdumpsBaseExceptionrt   
isinstancedatetime	isoformatr5   r6   r   _PRIMITIVE_TYPESbytesdecodesetlistrU   rQ   itemshasattrcallablerq   rB   loggerdebugtypedataclassesis_dataclassasdictro   vars)	r\   r]   serialization_methodsattrrn   methodjson_stre	all_attrsr,   ru   r-   r`      s`   









r`   sessionrequests.SessionNonec                 C  s   t d |   dS )zjClose the session.

    Parameters
    ----------
    session : Session
        The session to close.
    zClosing Client.sessionN)r   r   close)r   r,   r,   r-   close_session   s   
r   api_keyOptional[str]c                 C  s   |st | rtd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)rC   r;   r<   r0   r   r,   r,   r-   _validate_api_key_if_hosted   s   r   float | Nonec                  C  sB   t d} | du rdS t| }|dk s|dkrtd| |S )ziGet the tracing sampling rate.

    Returns
    -------
    float
        The tracing sampling rate.
    LANGCHAIN_TRACING_SAMPLING_RATENr   rN   zELANGCHAIN_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: )osgetenvfloatr;   r<   )sampling_rate_strsampling_rater,   r,   r-   _get_tracing_sampling_rate   s   
r   c                 C  s>   | d ur| nt d} | d u s|  sd S |  ddS )NLANGCHAIN_API_KEY"')r   r   strip)r   r,   r,   r-   _get_api_key  s   r   c                 C  sD   | d ur| nt dd}| std| dddS )NLANGCHAIN_ENDPOINTzhttps://api.smith.langchain.comz!LangSmith API URL cannot be emptyr   r   r2   )r   r   r   r;   r<   rstrip)r0   r   _api_urlr,   r,   r-   _get_api_url  s   
r   inputsDict[str, Any]c                 C     t jddkr
i S | S )NLANGCHAIN_HIDE_INPUTStruer   environgetr   r,   r,   r-   _hide_inputs#     r   outputsc                 C  r   )NLANGCHAIN_HIDE_OUTPUTSr   r   r   r,   r,   r-   _hide_outputs)  r   r   valueID_TYPEvar	uuid.UUIDc              
   C  sN   zt | tjst| W S | W S  ty& } zt| d|  |d }~ww )Nz* must be a valid UUID or UUID string. Got )rz   r5   r6   r7   r;   r<   )r   r   r   r,   r,   r-   _as_uuid/  s   r   T)orderc                   @  s0   e Zd ZU ded< ded< eddZded< dS )	TracingQueueItemr   priorityactionF)comparer	   itemN)__name__
__module____qualname____annotations__r   r   r,   r,   r,   r-   r   8  s   
 r   c                   @  s
  e Zd ZdZg dZ	dddddddddddZdddZdddZedddZ	edddZ
edd!d"Zeejd#d$dd'd(Z	#		ddd2d3Z	ddd7d8Zdd9dd<d=Zdd>d?d@ddCdDZdejjdEddPdQZddejjdRddUdVZeddZd[Zedd]d^Zd_d`ddddeZdddfddodpZ		dd_dqddvdwZddddddxdddZdddZ	_ddddZ dddddddddddddddZ!ddddddZ"dddddZ#dddZ$dddZ%dddZ&	ddddZ'	ddddddZ(	ddddddZ)dddZ*dddZ+dddddZ,dddddddZ-ddd_dddÜdddʄZ.dddddd˜ddd̈́Z/dddЄZ0e12dѡddd_dҜdddքZ3ddלdddلZ4dddќddd܄Z5						ddddZ6e12dddddddZ7dejjdEdddZ8ddddddZ9e12dddddddZ:	ddddddZ;ddddddddZ<e12dddddddZ=ddddddZ>dddZ?e12d				ddddZ@e12d				ddd	d
ZA			ddddZBdddddddZCe12d					ddddZDdddZE				dÐdĐddZFdddddŐdd ZGdƐd!d"ZHdǐd$d%ZIdȐd)d*ZJdɐd.d/ZKddd_d0dʐd7d8ZL	ddːd:d;ZMddd_d0d̐d=d>ZNdddddejOjPddd_d?d@
d͐dPdQZQdddddRdΐdSdTZRdϐdUdVZSddddWdАd\d]ZTdѐd^d_ZUdddd`dҐdcddZVdddedӐdhdiZWdԐdjdkZXddldՐdmdnZYd֐dodpZZdאdrdsZ[dؐdudvZ\ddwddd_ddddxdِddZ]ddwddd_ddddxdِddZ^dS (  Clientz.Client for interacting with the LangSmith API.)__weakref__r0   r   retry_config
timeout_msr   _get_data_type_cached_web_url
_tenant_idtracing_sample_rate_sampled_post_uuidstracing_queueNT)r   r   r   web_urlr   auto_batch_tracingr0   r   r   r   Optional[Retry]r   Optional[int]r   r   Optional[requests.Session]r   r!   r    r   c          	      C  s   t  | _t | _t|| _t|| j| _t| j| j |pt	 | _
|p$d| _|| _d| _|r0|nt | _t| t| j |rQt | _tjtt| fd  nd| _tj| j
d}| jd| | jd| tjdd| j | _!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 or None, default=None
            Timeout in milliseconds for the HTTPAdapter.
        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.

        Raises
        ------
        LangSmithUserError
            If the API key is not provided when using the hosted service.
        i'  Ntargetargs)max_retrieszhttp://zhttps://
   maxsize)"r   r   r   r   r   r   r   r0   r   r[   r   r   r   r   requestsSessionr   weakreffinalizer   r   r   	threadingThread_tracing_control_thread_funcrefstartrequests_adaptersHTTPAdaptermount	functools	lru_cache_get_data_typer   )	selfr0   r   r   r   r   r   r   adapterr,   r,   r-   __init__Q  s2   %




zClient.__init__r   c                 C  s   | 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   linkr,   r,   r-   _repr_html_  s   zClient._repr_html_c                 C  s   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: ))r0   r   r,   r,   r-   __repr__  s   zClient.__repr__c                 C  s~   | j r| j }|S t| j}t| jrd}|S |jdr1|jddd }t|j	|d}|S |j
dr;d}|S d}|S )	zThe web host url.zhttp://localhostz/apirN   r   )r9   zdev.zhttps://dev.smith.langchain.comzhttps://smith.langchain.com)r   r#   r8   r0   r.   r9   rA   rsplit
urlunparse_replacer%   r)   )r   r   r=   new_pathr,   r,   r-   r     s    
zClient._host_urlDict[str, str]c                 C  s$   ddt j i}| jr| j|d< |S )zGet the headers for the API request.

        Returns
        -------
        Dict[str, str]
            The headers for the API request.
        z
User-Agentzlangsmith-py/z	x-api-key)	langsmith__version__r   )r   headersr,   r,   r-   _headers  s   	
zClient._headers"Optional[ls_schemas.LangSmithInfo]c                 C  s<   t | j| j| j}|du r| jdurd| _ttt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)
r   	_get_infor   r0   r   r   r   r   
ls_schemasLangSmithInfo)r   infor,   r,   r-   r    s   
zClient.inforN   r   r   rW   c              
   C  s   z| j |d ddi|d d}t| tjdi | W S  tjy)   Y d S  tyH } zt	
d| dt|  W Y d }~d S d }~ww )	Nz/infoAcceptapplication/json  )r   timeoutzFailed to get info from z: r,   )r   r;   raise_for_status_with_textr  r  rk   r   	HTTPErrorry   r   warningrt   )r   r0   r   responser   r,   r,   r-   r    s   
zClient._get_inforequest_methodr   request_kwargsr   stop_after_attemptretry_on'Optional[Sequence[Type[BaseException]]]	to_ignorerequests.Responsec                 C  s  g |pg t jt jfR }g |pdR }d}	t|D ]R}
zz| jj||fddi|}	t |	 |	W W   S  tjy } z|	dur|	j	dkrYt d| d| dt
| |	j	d	krkt d
| dt
| |	j	dkr}t d| dt
| |	j	dkrt d| dt
| |	j	dkrt d| dt
| t d| d| dt
| t d| d| dt
| d}~w tjy } zt d| d| dt
| |d}~w ty% } z7t|j}t|dkr|d nd}|dd}d|d g|g |dd  }t d| d| d| |d}~ww  |yM } z|	durCtd| |	W  Y d}~  S W Y d}~qd}~w |ym   |
d |kr\ d|
 t d  }t| Y qw t d| d| d)a  Send a request with retries.

        Parameters
        ----------
        request_method : str
            The HTTP request method.
        url : str
            The URL to send the request to.
        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.

        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.
        r,   NstreamFi  zServer error caused failure to  z in LangSmith API. rE   zRate limit exceeded for z. i  zAuthentication failed for i  zResource not found for i  zConflict for z
Failed to z#Connection error caused failure to z<  in LangSmith API. Please confirm your LANGCHAIN_ENDPOINT. rN    r   zsession (project)
r   r3   zPassing on exception %srF   z in LangSmith API.)r;   LangSmithConnectionErrorLangSmithAPIErrorranger   requestr
  r   r  status_codert   LangSmithRateLimitErrorLangSmithAuthErrorLangSmithNotFoundErrorLangSmithConflictErrorLangSmithErrorr<   ConnectionErrorrB   r   r   r:   replacejoinr   r   randomtimesleep)r   r  r   r  r  r  r  	retry_on_
to_ignore_r  idxr   r   msgemsg
sleep_timer,   r,   r-   request_with_retries  s   ,







"

zClient.request_with_retriesr9   paramsOptional[Dict[str, Any]]c                 C  s*   | j d| j | || j| jd ddS )Nr   r  )r0  r   r	  r  )r/  r0   r   r   )r   r9   r0  r,   r,   r-   _get_with_retriesi  s   zClient._get_with_retriesr0  Optional[dict]Iterator[dict]c                c  s    |r|  ni }|dd}|dd|d< 	 ||d< | j||d}| }|s+dS |E dH  t||d k r:dS |t|7 }q)a1  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   limitd   Tr4  N)copyr   r3  rk   r:   )r   r9   r0  params_r7  r  r   r,   r,   r-   _get_paginated_listv  s   
zClient._get_paginated_listpostruns)bodyr  data_keyr?  r@  c          	      c  s    |r|  ni }	 | j|| j | tj|td| j| jd dd}| }|s,dS ||s3dS || E dH  |d}|sCdS |dsJdS |d |d	< q
)
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.
        Tdefaultr  datar   r	  r2  Ncursorsnextcursor)	r:  r/  r0   rk   rx   r`   r   r   r   )	r   r9   r?  r  r@  r;  r  response_bodyrE  r,   r,   r-   _get_cursor_paginated_list  s0   	


z!Client._get_cursor_paginated_list)description	data_typedfpd.DataFramename
input_keysSequence[str]output_keysrJ  rK  Optional[ls_schemas.DataType]ls_schemas.Datasetc                C  s:   t  }|j|dd |d | jd|f|||||d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)rO  rQ  rJ  rN  rK  )ioBytesIOto_csvseek
upload_csv)r   rL  rN  rO  rQ  rJ  rK  csv_filer,   r,   r-   upload_dataframe  s   %
zClient.upload_dataframerN  rJ  rK  rZ  "Union[str, Tuple[str, io.BytesIO]]c                C  s<  ||d}|r||d< |r||d< |rt ||d< t|trGt|d}d|i}	| jj| jd | j||	d}
W d	   n1 sAw   Y  nt|t	r]| jj| jd | j|d|id}
nt
d
t |
 |
 }d|v rd|d v rt|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.
        )rO  rQ  rN  rJ  rK  rbfilez/datasets/upload)r   rD  filesNz"csv_file must be a string or tupledetailzalready existsr   r2   Dataset z already existsr   r   r,   )r;   get_enum_valuerz   r   openr   r=  r0   r   rU   r7   r
  rk   r&   r  Datasetr   _get_tenant_id)r   rZ  rO  rQ  rN  rJ  rK  rD  ffile_r  result	file_namer,   r,   r-   rY    sN   (




zClient.upload_csvrun3Union[ls_schemas.Run, dict, ls_schemas.RunLikeDict]rQ   c                 C  s   t | drtt| dr|  }ntt| }d|vr!t |d< nt| d tr1t	| d | d< d|v r=t
|d |d< d|v rIt|d |d< |dsUtj |d< |S )z
        Transforms the given run object into a dictionary representation.

        Args:
            run (Union[ls_schemas.Run, dict]): The run object to transform.

        Returns:
            dict: The transformed run object as a dictionary.
        rQ   idr   r   
start_time)r   r   rq   rQ   r   r5   uuid4rz   r   r6   r   r   r   r{   utcnow)rm  
run_creater,   r,   r-   _run_transformH  s   


zClient._run_transformSequence[dict]c                   st   t  }| D ]1}tt|di }|di }i |||d< |di  t  }  fdd| D  qd S )NextraruntimerS   c                   s   i | ]\}}| vr||qS r,   r,   rf   rS   r,   r-   ri   q      z.Client._insert_runtime_env.<locals>.<dictcomp>)ls_envget_runtime_and_metricsr   rQ   
setdefaultget_langchain_env_var_metadataupdater   )r>  runtime_envrs  	run_extrarw  langchain_metadatar,   rx  r-   _insert_runtime_enve  s   zClient._insert_runtime_envFpatchIterable[dict]r  
list[dict]c                C  s   | j d u r	t|S |r(g }|D ]}|d | jv r%|| | j|d  q|S g }|D ]}t | j k rB|| | j|d  q,|S )Nro  )r   r   r   appendremover&  add)r   r>  r  sampledrm  r,   r,   r-   _filter_for_samplingt  s"   


zClient._filter_for_sampling)project_namerevision_idr   r   run_typer  r  Optional[ID_TYPE]kwargsr	   c          	      K  s   |p	| dt }i |||||d}| |gsdS | |}| |g |dur4||d d d< | jdurX|ddurX|ddurX| jdurX| j	t
|d d	|S i | jd
d
d}| jd| j dtj|td|| jd dtjfd dS )ay  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  rN  r   r  Nrv  rS   r  trace_iddotted_ordercreater  r  Content-Typer=  /runsrA  r  rC  r  r  )popr;   get_tracer_projectr  rt  r  r   r   r  putr   r   r/  r0   rk   rx   r`   r   r!  )	r   rN  r   r  r  r  r  rs  r   r,   r,   r-   
create_run  sP   




zClient.create_run)pre_sampledr  GOptional[Sequence[Union[ls_schemas.Run, ls_schemas.RunLikeDict, Dict]]]r~  r  c          
   	     s~  |s|sdS  fdd|pg D } fdd|pg D }|rL|rLdd |D }g }|D ]}|d |v rD||d   dd | D  q+|| q+|}|D ]}|d	rZ|d
s_tdqN|D ]}|d	rn|d
sstdqb|r|||d}	n | j|ddd}	|	d s|	d sdS  |	d   jd j	 dt
j|	td jd i  jddddtjfd dS )a  
        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: If both `create` and `update` are 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 | ]}  |qS r,   rt  ra   rm  r   r,   r-   rd          z,Client.batch_ingest_runs.<locals>.<listcomp>c                   r  r,   r  r  r   r,   r-   rd     r  c                 S  s   i | ]}|d  |qS ro  r,   r  r,   r,   r-   ri     r  z,Client.batch_ingest_runs.<locals>.<dictcomp>ro  c                 S     i | ]\}}|d ur||qS rp   r,   rf   r,   r,   r-   ri   	  ry  r  r  z:Batch ingest requires trace_id and dotted_order to be set.)r=  r  Tr  r=  r  z/runs/batchrA  r  r  r  )rD  r	  r   r  )r~  r   r  r   r;   r<   r  r  r/  r0   rk   rx   r`   r   r   r!  )
r   r  r~  r  create_dictsupdate_dictscreate_by_idstandalone_updatesrm  r?  r,   r   r-   batch_ingest_runs  sd   $
	
zClient.batch_ingest_runs)end_timeerrorr   r   eventsrun_idr   r  Optional[datetime.datetime]r  Optional[Dict]r   r  Optional[Sequence[dict]]c          
      K  s0  i | j ddd}t|d|dd|dd|ddd}	| j|	gd	d
s*dS |dur4| |	d< |dur<||	d< |durFt||	d< |durPt||	d< |durX||	d< | jdurz|	d durz|	d durz| jdurz| j	t
|	d d|	S | jd| j d|	d  tj|	td|| jd dd dS )at  Update a run in the LangSmith API.

        Parameters
        ----------
        run_id : str or UUID
            The ID of the run to update.
        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.
        **kwargs : Any
            Kwargs are ignored.
        r  r  r  r  Nparent_run_idr  )ro  r  r  r  Tr  r  r  r   r   r  r~  r  /runs/ro  rA  r  rC  r2  )r   r   r  r  r|   r   r   r   r  r  r   r/  r0   rk   rx   r`   r   )
r   r  r  r  r   r   r  r  r   rD  r,   r,   r-   
update_run7  sL   





zClient.update_runls_schemas.Runc                 C  s   | j |jd}tt}i }t|dd dD ]}|jdu r'td|j	 d||j 
| |||j	< q||j	g |_| D ]	\}}||| _qA|S )aG  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.
        r  c                 S  s   | j S rp   )r  )rr,   r,   r-   <lambda>  s    z)Client._load_child_runs.<locals>.<lambda>)keyNz
Child run z has no parent)	list_runschild_run_idscollectionsdefaultdictr   sortedr  r;   r"  ro  r  r  
child_runsr   )r   rm  r  treemapr>  	child_runr  childrenr,   r,   r-   _load_child_runs  s"   

zClient._load_child_runsload_child_runsc                 C  sL   |  dt|d }tjdi | d| ji}|r$|jr$| |}|S )a5  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.
        r  r  r   Nr,   )r3  r   r  Runrk   r   r  r  )r   r  r  r  rm  r,   r,   r-   read_run  s
   

zClient.read_run)
project_idr  r  reference_example_idqueryfilterexecution_orderr  rp  r  run_idsr  r  r  r  r  r  rp  Optional[bool]r  Optional[List[ID_TYPE]]Iterator[ls_schemas.Run]c                +  s    |dur|durt d j|dj}|r|gnd||r |gnd|||||	r+|	 nd|
|d
|}dd | D } fdd jd	|d
dD E dH  dS )a  List runs from the LangSmith API.

        Parameters
        ----------
        project_id : UUID or None, default=None
            The ID of the project to filter by.
        project_name : str or None, default=None
            The name of the project to filter by.
        run_type : str or None, default=None
            The type of the runs 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.
        execution_order : int or None, default=None
            The execution order to filter by. Execution order is the position
            of the run in the full trace's execution sequence.
                All root run traces have execution_order 1.
        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.
        **kwargs : Any
            Additional keyword arguments.

        Yields
        ------
        Run
            The runs.
        Nz3Only one of project_id or project_name may be givenr  )
r   r  reference_exampler  r  r  
parent_runrp  r  ro  c                 S  r  rp   r,   rf   r,   r,   r-   ri     ry  z$Client.list_runs.<locals>.<dictcomp>c                 3  *    | ]}t jdi |d  jiV  qdS r   Nr,   r  r  r   r  r   r,   r-   	<genexpr>  
    
z#Client.list_runs.<locals>.<genexpr>z/runs/queryr=  )r?  r  )r7   read_projectro  r|   r   rI  )r   r  r  r  r  r  r  r  r  rp  r  r  r  
body_queryr,   r   r-   r    s0   4
zClient.list_runs)r  r  ls_schemas.RunBasec                C  s   t |dr|jdur|j}n|dur|}n|dur!| j|dj}nt }| j|dj}t|d}| j d|   d| d|j dS )ad  Get the URL for a run.

        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.
        
session_idNr  z/o/z/projects/p/z/r/z
?poll=true)	r   r  r  ro  r;   r  r   r   rh  )r   rm  r  r  r  session_id_r,   r,   r-   get_run_url  s   
zClient.get_run_url)share_idr  c                C  sn   t |d}t||ptt d}| jj| j d| d| j|d}t	| |
 d }| j d| dS )	zGet a share link for a run.r  )r  share_tokenr  /sharer   rk   r  /public//r)r   r   r5   rq  r   r  r0   r   r;   r
  rk   r   )r   r  r  run_id_rD  r  r  r,   r,   r-   	share_run2  s   

zClient.share_runc                 C  4   | j j| j dt|d d| jd}t| dS )zDelete share link for a run.r  r  r  r   Nr   deleter0   r   r   r;   r
  )r   r  r  r,   r,   r-   unshare_runB  
   zClient.unshare_runc                 C  sb   | j j| j dt|d d| jd}t| | }|d u s$d|vr&d S | j d|d  dS )Nr  r  r  r  r  r  r  )	r   r   r0   r   r   r;   r
  rk   r   )r   r  r  rk  r,   r,   r-   read_run_shared_linkJ  s   
zClient.read_run_shared_linkc                 C  s   |  t|d}|duS )zGet share state for a run.r  N)r  r   )r   r  r   r,   r,   r-   run_is_sharedU  s   zClient.run_is_sharedr  Optional[List[str]]List[ls_schemas.Run]c                   sV   |t |d} jj j dt|d d j|d}t|  fdd| D S )zGet shared runs.)ro  r  r  r  r  r   r0  c                   &   g | ]}t jdi |d  jiqS r   r,   r  r  r   r,   r-   rd   e      z+Client.list_shared_runs.<locals>.<listcomp>)	r   r   r   r0   r   r   r;   r
  rk   )r   r  r  r0  r  r,   r   r-   list_shared_runsZ  s   

zClient.list_shared_runsdataset_name
dataset_idr  ls_schemas.DatasetShareSchemac             	   C  s   |d u r|d u rt d|d u r| j|dj}| jj| j dt|d d| jd}t	| |
 }ttji |d| j dt|d	 d
 diS )N/Either dataset_id or dataset_name must be givenr  
/datasets/r  r  r  r   r  r  zresponse.share_token/d)r7   read_datasetro  r   r   r0   r   r   r;   r
  rk   r   r  DatasetShareSchemar   )r   r  r  r  dr,   r,   r-   read_dataset_shared_schemai  s(   

z!Client.read_dataset_shared_schemac                C  s   |du r|du rt d|du r| j|dj}dt|i}| jj| j dt|d d| j|d}t	
| | }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  )r7   r  ro  r   r   r  r0   r   r   r;   r
  rk   r   r  r  r   )r   r  r  rD  r  r  r,   r,   r-   share_dataset  s"   
 zClient.share_datasetc                 C  r  )z Delete share link for a dataset.r  r  r  r  Nr  )r   r  r  r,   r,   r-   unshare_dataset  r  zClient.unshare_datasetc                 C  sX   | j j| j dt|d d| jd}t| tjdi |	 | j
d| ddS )	zGet shared datasets.r  r  	/datasetsr  r  )r   _public_pathNr,   )r   r   r0   r   r   r;   r
  r  rg  rk   r   )r   r  r  r,   r,   r-   read_shared_dataset  s   


zClient.read_shared_datasetexample_idsr  List[ls_schemas.Example]c                  sf   i }|durdd |D |d<  j j j dt|d d j|d}t|  fd	d| D S )
zGet shared examples.Nc                 S  s   g | ]}t |qS r,   )r   )ra   ro  r,   r,   r-   rd     s    z/Client.list_shared_examples.<locals>.<listcomp>ro  r  r  	/examplesr  c                   r  r  )r  Exampler   ra   datasetr   r,   r-   rd         )r   r   r0   r   r   r;   r
  rk   )r   r  r  r0  r  r,   r   r-   list_shared_examples  s   

zClient.list_shared_examples)project_idsrN  name_containsdataset_share_tokenr  r  (Iterator[ls_schemas.TracerSessionResult]c                #  sF    |||d}t |d} fdd jd| d|dD E d H  d S )N)ro  rN  r  r  c                   r  r  r  TracerSessionResultr   ra   projectr   r,   r-   rd     r
  z/Client.list_shared_projects.<locals>.<listcomp>r  z/datasets/sessionsr4  )r   r<  )r   r  r  rN  r  r0  r  r,   r   r-   list_shared_projects  s   


zClient.list_shared_projects)rJ  rS   upsertproject_extrareference_dataset_idrS   r  r  r  ls_schemas.TracerSessionc                C  s   | j  d}|}|ri |pi d|i}|||d}	i }
|r"d|
d< |dur*||	d< | jj|i | jdd	itj|	td
d}t| 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.
        	/sessionsrS   )rN  rv  rJ  Tr  Nr  r  r  rA  r   rD  r   r,   )r0   r   r=  r   rk   rx   r`   r;   r
  r  TracerSessionr   )r   r  rJ  rS   r  r  r  endpointrv  r?  r0  r  r,   r,   r-   create_project  s(    
zClient.create_project)rN  rJ  rS   r  r  c                C  s   | j  dt|d }|}|ri |pi d|i}||||r"| ndd}	| jj|i | jdditj|	tdd	}
t	
|
 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  rS   N)rN  rv  rJ  r  r  r  rA  r  r   r,   )r0   r   r|   r   r  r   rk   rx   r`   r;   r
  r  r  r   )r   r  rN  rJ  rS   r  r  r  rv  r?  r  r,   r,   r-   update_project  s    
zClient.update_projectr   c                 C  sj   | j d ur| j S | jdddid}| }t|tr0tjdi |d d| ji}|j| _ | j S t	
d)	Nr  r8  rN   r4  r   r   zNo projects foundr,   )r   r3  rk   rz   r   r  r  r   	tenant_idr;   r"  )r   r  rk  tracer_sessionr,   r,   r-   rh  ?  s   


zClient._get_tenant_id)r  r  )r  r  include_statsr"  ls_schemas.TracerSessionResultc                C  s   d}ddi}|dur|dt |d 7 }n|dur||d< ntd||d	< | j||d
}| }t|trTt|dkrEt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  r8  rN   Nr2   r  rN  'Must provide project_name or project_idr"  r4  r   zProject 
 not foundr   r,   )r   r7   r3  rk   rz   r   r:   r;   r   r  r  r   )r   r  r  r"  r9   r0  r  rk  r,   r,   r-   r  L  s*   


zClient.read_project)r  c                C  s*   z	| j |d W dS  tjy   Y dS w )aL  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  r;   r   )r   r  r  r,   r,   r-   has_projectz  s   zClient.has_project'pd.DataFrame'c                  s  ddl }| j||dd}g }g |D ]X}d|jidd |j D dd |jp)i  D }|jrF|j D ]\}}	|	d	|d
| < q7||j	rS|j	|j
  nd|j|jd |jre|j || q||d}
d g } fddtdt D D ]}| j|dD ]}|d|jidd |jpi  D  qq|r||d}|j|
ddd}
||
jddS )aR  Read the record-level information from a test project 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.
        r   NrN   )r  r  r  
example_idc                 S     i | ]
\}}d | |qS )zinput.r,   rf   r,   r,   r-   ri         z+Client.get_test_results.<locals>.<dictcomp>c                 S  r)  )zoutputs.r,   rf   r,   r,   r-   ri     r*  avgz	feedback.)execution_timer  ro  r9  c                   s   g | ]
}||   qS r,   r,   )ra   i
batch_sizer  r,   r-   rd     s    z+Client.get_test_results.<locals>.<listcomp>r  c                 S  r)  )z
reference.r,   rf   r,   r,   r-   ri     s    
T)
left_indexright_indexrecords)orient)pandasr  r  r   r   r   feedback_statsr   r~  r  rp  total_secondsr  ro  r  	DataFrame	set_indexr  r:   list_examplesmergejson_normalizeto_dict)r   r  r  pdr>  resultsr  rowrg   rh   rk  example_outputsbatchexamplerL  r,   r.  r-   get_test_results  s^   

zClient.get_test_resultsreference_dataset_namereference_free"Iterator[ls_schemas.TracerSession]c                 #  s    i }|dur||d< |dur||d< |dur||d< |dur,|dur't d||d< n|dur; j|dj}||d< |durC||d<  fd	d
 jd|dD E dH  dS )a  
        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.

        Yields
        ------
        TracerSession
            The projects.
        Nro  rN  r  zGOnly one of reference_dataset_id or reference_dataset_name may be givenreference_datasetr  rE  c                 3  r  r  r  r  r   r,   r-   r    r  z'Client.list_projects.<locals>.<genexpr>r  r4  )r7   r  ro  r<  )r   r  rN  r  r  rD  rE  r0  r,   r   r-   list_projects  s4    

zClient.list_projectsc                C  s^   |durt | j|dj}n|du rtd| jj| jdt|d  | jd}t	
| 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  r  r  )r   r  ro  r7   r   r  r0   r   r   r;   r
  )r   r  r  r  r,   r,   r-   delete_project  s   zClient.delete_projectls_schemas.DataTypec                C  sh   t j|||d}| jj| jd i | jddi| d}t| 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.

        Returns
        -------
        Dataset
            The created dataset.
        r\  r   r  r  r  rd  Nr,   )r  DatasetCreater   r=  r0   r   rk   r;   r
  rg  r   rh  )r   r  rJ  rK  r	  r  r,   r,   r-   create_dataset'  s"   

zClient.create_datasetr  r  c                C  s,   z
| j ||d W dS  tjy   Y dS w )an  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.
        rM  TF)r  r;   r   )r   r  r  r,   r,   r-   has_datasetO  s   zClient.has_datasetc                C  s   d}ddi}|dur|dt |d 7 }n|dur||d< ntd| j||d	}| }t|trSt|d
krAtd| dt	j
di |d
 | j|  dS t	j
di || j|  dS )aY  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   r8  rN   Nr2   r  rN  'Must provide dataset_name or dataset_idr4  r   rc  r%  rd  r,   )r   r7   r3  rk   rz   r   r:   r;   r   r  rg  r   rh  )r   r  r  r9   r0  r  rk  r,   r,   r-   r  f  s6   






zClient.read_datasetr   c                C  sh   d}|durn|dur| j |dj}ntd| | dt|d d}dd	 |j d
D }|S )aw  
        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  rO  r2   r  z
/openai_ftc                 S  s   g | ]}t |qS r,   )rk   rw   )ra   liner,   r,   r-   rd     r  z9Client.read_dataset_openai_finetuning.<locals>.<listcomp>r  )r  ro  r7   r3  r   textr   r&   )r   r  r  r9   r  r	  r,   r,   r-   read_dataset_openai_finetuning  s   z%Client.read_dataset_openai_finetuning)dataset_idsrK  r  dataset_name_containsrS  rT  Iterator[ls_schemas.Dataset]c                #  sl    i }|dur||d< |dur||d< |dur||d< |dur#||d<  fdd j d|d	D E dH  dS )
zyList the datasets on the LangSmith API.

        Yields
        ------
        Dataset
            The datasets.
        Nro  rK  rN  r  c                 3  0    | ]}t jdi | j  d V  qdS rd  Nr,   )r  rg  r   rh  r  r   r,   r-   r        

z'Client.list_datasets.<locals>.<genexpr>r   r4  r<  )r   rS  rK  r  rT  r0  r,   r   r-   list_datasets  s   
zClient.list_datasets)r  r  c                C  sX   |dur| j |dj}|du rtd| jj| j dt|d | jd}t	| 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  z&Must provide either dataset name or IDr  r  r  )
r  ro  r7   r   r  r0   r   r   r;   r
  )r   r  r  r  r,   r,   r-   delete_dataset  s   zClient.delete_dataset)source_api_urlr  token_or_urlr\  c          
   
   C  s   |p| j }t||\}}t|dd}||}|p|j}| j|dr-td| d dS zEt|	|}| j
||j|jp@tjjd}z| jdd	 |D d
d	 |D |jd W W ~dS  tyr }	 ztd| d |	d}	~	ww ~w )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  rc  z) already exists in your tenant. Skipping.N)r  rJ  rK  c                 S     g | ]}|j qS r,   r   ra   r   r,   r,   r-   rd         z/Client.clone_public_dataset.<locals>.<listcomp>c                 S  r_  r,   r   r`  r,   r,   r-   rd     ra  r   r   r  z)An error occurred while creating dataset z . You should delete it manually.)r0   r@   r   r  rN  rN  r   r  r   r  rL  rJ  rK  r  DataTypekvcreate_examplesro  ry   r  )
r   r]  r\  r  r?   source_clientdsexamplesr	  r   r,   r,   r-   clone_public_dataset  sF   





zClient.clone_public_datasetc                 C  s   | j |d}|jS )Nr  )r  rK  )r   r  r	  r,   r,   r-   r   -  s   zClient._get_data_typeprompt
generation
created_atls_schemas.Examplec                 C  s   | j d|id|i|||dS ),Add an example (row) to an LLM-type dataset.inputoutputr   r   r  r  rm  )create_example)r   rk  rl  r  r  rm  r,   r,   r-   create_llm_example1  s   
zClient.create_llm_examplemessages:List[Union[Mapping[str, Any], ls_schemas.BaseMessageLike]]generations>Optional[Union[Mapping[str, Any], ls_schemas.BaseMessageLike]]c           	      C  s   g }|D ]}t |r|t ttj| q|tt| qd}|dur;t |r6t ttj|}ntt|}| jd|i|durHd|ind|||dS )z,Add an example (row) to a Chat-type dataset.Nrp  rq  rr  )	r;   is_base_message_liker  convert_langchain_messager   r  BaseMessageLikerQ   rs  )	r   ru  rw  r  r  rm  final_inputmessagefinal_generationsr,   r,   r-   create_chat_exampleC  s.   




zClient.create_chat_examplec           
      C  s  |du r| j |dj}d}| |}|tjjkrm|jdkr&td|j dzt	|j
}W n tyA   td|j d|j
 w d|i}|jsLd}nzt|j}	W n tyg   td	|j d
|j w d|	i}nk|tjjkr|jdkrtd|j dz
dt|j
i}W n ty   td|j d|j
 w |jsd}n3z
dt|ji}W n( ty   td|j d
|j w |tjjkr|j
}|j}ntd| d| j|||||dS )ro  Nr  llmz	Run type z+ is not supported for dataset of type 'LLM'z2Error converting LLM run inputs to prompt for run z with inputs rp  z7Error converting LLM run outputs to generation for run z with outputs rq  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.rr  )r  ro  r   r  rc  r  r  r7   r;   get_prompt_from_inputsr   r   get_llm_generation_from_outputschatget_messages_from_inputs#get_message_generation_from_outputsrd  rs  )
r   rm  r  r  rm  dataset_typerk  r   r   rl  r,   r,   r-   create_example_from_runk  s   



zClient.create_example_from_run)r   r  r  Sequence[Mapping[str, Any]]/Optional[Sequence[Optional[Mapping[str, Any]]]]c                  s    du r|du rt d du r| j|dj  fddt||p&dgt| D }| jj| j di | jddit	j
|td	d
}t| dS )a  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.
        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.

        Returns
        -------
        None

        Raises
        ------
        ValueError
            If both `dataset_id` and `dataset_name` are `None`.
        Nz3Either dataset_id or dataset_name must be provided.r  c                   s   g | ]
\}}|| d qS )rb  r,   )ra   in_out_rj  r,   r-   rd     s    z*Client.create_examples.<locals>.<listcomp>z/examples/bulkr  r  rA  r  )r7   r  ro  zipr:   r   r=  r0   r   rk   rx   r`   r;   r
  )r   r   r   r  r  r  rh  r  r,   rj  r-   re    s   
	
zClient.create_examplesMapping[str, Any]Optional[Mapping[str, Any]]r(  c                 C  s   |du r| j |dj}|||d}|r| |d< |r||d< tjdi |}| jj| j di | jddi|	 d	}	t
|	 |		 }
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.

        Parameters
        ----------
        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.
        exemple_id : UUID or None, default=None
            The ID of the example to create. If not provided, a new
            example will be created.

        Returns
        -------
        Example
            The created example.
        Nr  rb  rm  ro  r  r  r  r  rd  r,   )r  ro  r|   r  ExampleCreater   r=  r0   r   rk   r;   r
  r  r   rh  )r   r   r  r  rm  r   r(  rD  rB  r  rk  r,   r,   r-   rs    s.   %



zClient.create_examplec                 C  s:   |  dt|d }tjdi | | j|  dS )zRead an example from the LangSmith API.

        Parameters
        ----------
        example_id : str or UUID
            The ID of the example to read.

        Returns
        -------
        Example
            The example.
        
/examples/r(  rd  Nr,   )r3  r   r  r  rk   r   rh  r   r(  r  r,   r,   r-   read_example+	  s   
zClient.read_exampleOptional[Sequence[ID_TYPE]]inline_s3_urlsIterator[ls_schemas.Example]c                 #  sx    i }|dur||d< n|dur j |dj}||d< n	 |dur%||d< ||d<  fdd jd|d	D E dH  dS )
a  Retrieve the example rows of the specified dataset.

        Parameters
        ----------
        dataset_id : UUID or None, default=None
            The ID of the dataset to filter by.
        dataset_name : str or None, default=None
            The name of the dataset to filter by.
        example_ids : List[UUID] or None, default=None
            The IDs of the examples to filter by.

        Yields
        ------
        Example
            The examples.
        Nr	  r  ro  r  c                 3  rV  rW  )r  r  r   rh  )ra   rB  r   r,   r-   r  c	  rX  z'Client.list_examples.<locals>.<genexpr>r  r4  )r  ro  r<  )r   r  r  r  r  r0  r,   r   r-   r9  A	  s   


zClient.list_examplesrb  c                C  s\   t j|||d}| jj| j dt|d i | jddi|jddd}t	| | 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.
        dataset_id : UUID or None, default=None
            The ID of the dataset to update.

        Returns
        -------
        Dict[str, Any]
            The updated example.
        rb  r  r(  r  r  Trm   r  )
r  ExampleUpdater   r  r0   r   r   rk   r;   r
  )r   r(  r   r   r  rB  r  r,   r,   r-   update_examplej	  s   

zClient.update_examplec                 C  2   | j j| j dt|d | jd}t| dS )zDelete an example by ID.

        Parameters
        ----------
        example_id : str or UUID
            The ID of the example to delete.
        r  r(  r  Nr  r  r,   r,   r-   delete_example	  
   zClient.delete_example9Union[ls_schemas.Run, ls_schemas.RunBase, str, uuid.UUID]c                 C  s*   t |ttjfr| j||d}|S |}|S )az  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  )rz   r   r5   r6   r  )r   rm  r  run_r,   r,   r-   _resolve_run_id	  s
   zClient._resolve_run_idrB  5Union[ls_schemas.Example, str, uuid.UUID, dict, None]Optional[ls_schemas.Example]c                 C  s   t |ttjfr| |}|S t |tjr|}|S t |tr0tjdi || j| 	 d}|S |j
dur=| |j
}|S d}|S )aB  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.
        rd  Nr,   )rz   r   r5   r6   r  r  r  rQ   r   rh  r  )r   rB  rm  reference_example_r,   r,   r-   _resolve_example_id	  s$   
	



zClient._resolve_example_idr>  DUnion[ls_evaluator.EvaluationResult, ls_evaluator.EvaluationResults]#List[ls_evaluator.EvaluationResult]c                 C  sT   t |tjr|g}|S t |tr d|v r tttj |d }|S tdt| d)Nr>  zInvalid evaluation result type z1. Expected EvaluationResult or EvaluationResults.)rz   ls_evaluatorEvaluationResultrQ   r   r   	TypeErrorr   )r   r>  results_r,   r,   r-   _select_eval_results	  s   zClient._select_eval_results)source_infor  r  r   ls_evaluator.RunEvaluatorr  r  9Optional[Union[ls_schemas.Example, str, dict, uuid.UUID]]ls_evaluator.EvaluationResultc          
      C  s@   | j ||d}| ||}|j||d}| j|||d}	|	d S )a0  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  rB  r  r   )r  r  evaluate_run_log_evaluation_feedback
r   rm  r   r  r  r  r  r  evaluator_responser>  r,   r,   r-   r  	  s   !zClient.evaluate_runr  c                 C  sr   |  |}|D ]/}|pi }|jri |j|}|jr|jn|j}| j||j|j|j|j|j	||j
tjjd	 q|S )N)scorer   comment
correctionr  source_run_idfeedback_source_type)r  evaluator_infotarget_run_idro  create_feedbackr  r  r   r  r  r  r  FeedbackSourceTypeMODEL)r   r  rm  r  r>  ressource_info_r  r,   r,   r-   r  
  s$   
zClient._log_evaluation_feedback%Union[ls_schemas.Run, str, uuid.UUID]c          
        sH   | j ||d}| ||}|j||dI dH }| j|||d}	|	d S )a7  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  r,   r,   r-   r  7
  s   !zClient.aevaluate_runr   )
r  r   r  r  r  r  r  feedback_ideagerr  r  r  Union[float, int, bool, None]r   (Union[float, int, bool, str, dict, None]r  Union[dict, None]r  Union[str, None]r  )Union[ls_schemas.FeedbackSourceType, str]r  r  r  ls_schemas.Feedbackc       
         C  s  t |tjst|}|tjjkrtj|d}n|tjjkr%tj|d}ntd| |jdur4|jni |_|	durId|jvrIdt	|	i|jd< |jrzd|jv rz|jd }t
|drct|rc| }d|v rut	t|jd d d|d< ||jd< tj|
pt |||||||tjtjjtjtjjd
}| jd	| jd
 |rdnd tj|jddtdi | jddd| jd d|tjfd tjdi | S )a  Create a feedback in the LangSmith API.

        Parameters
        ----------
        run_id : str or UUID
            The ID of the run to provide feedback on.
        key : str
            The name of the metric, tag, 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.
        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.
        eager : bool, default=False
            Whether to skip the write queue when creating the feedback. This means
            that the feedback will be immediately available for reading, but may
            cause the write to fail if the API is under heavy load, since the target
            run_id may have not been created yet.
        stop_after_attempt : int, default=10
            The number of times to retry the request before giving up.
        rx  zUnknown feedback source type N__runr  rQ   z+feedback_source.metadata['__run']['run_id'])
ro  r  r  r  r   r  r  feedback_sourcerm  modified_atPOST	/feedbackz/eagerr  Trm   rA  r  )r  r  r  rC  )r  r  r  r,   )rz   r  r  APIAPIFeedbackSourcer  ModelFeedbackSourcer7   rS   r   r   r   rQ   r   FeedbackCreater5   rq  r{   nowtimezoneutcr/  r0   rk   rx   r`   r   r   r;   r   Feedback)r   r  r  r  r   r  r  r  r  r  r  r  r  r  	_run_metafeedbackr,   r,   r-   r  f
  sl   4




zClient.create_feedback)r  r   r  r  c                C  s   i }|dur
||d< |dur||d< |dur||d< |dur"||d< | j j| jdt|d  i | jdd	itj|td
d}t	| 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.
        Nr  r   r  r  
/feedback/r  r  r  rA  r  )
r   r  r0   r   r   rk   rx   r`   r;   r
  )r   r  r  r   r  r  feedback_updater  r,   r,   r-   update_feedback
  s   zClient.update_feedbackc                 C  s*   |  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.
        r  r  Nr,   )r3  r   r  r  rk   r   r  r  r,   r,   r-   read_feedback
  s   zClient.read_feedback)r  feedback_keyr  r  Optional[Sequence[str]]1Optional[Sequence[ls_schemas.FeedbackSourceType]]Iterator[ls_schemas.Feedback]c                k  sP    d|i|}|dur||d< |dur||d< dd | j d|dD E dH  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.
        **kwargs : Any
            Additional keyword arguments.

        Yields
        ------
        Feedback
            The feedback objects.
        rm  Nr  sourcec                 s       | ]}t jdi |V  qd S Nr,   )r  r  )ra   r  r,   r,   r-   r  4  
    
z'Client.list_feedback.<locals>.<genexpr>r  r4  rY  )r   r  r  r  r  r0  r,   r,   r-   list_feedback  s   zClient.list_feedbackc                 C  r  )zDelete a feedback by ID.

        Parameters
        ----------
        feedback_id : str or UUID
            The ID of the feedback to delete.
        r  r  r  Nr  r  r,   r,   r-   delete_feedback9  r  zClient.delete_feedback)	queue_idsrN  r  r  $Iterator[ls_schemas.AnnotationQueue]c                c  sJ    |d urdd t |D nd ||d}dd | jd|dD E d H  d S )Nc                 S  s"   g | ]\}}t |d | dqS )z
queue_ids[])r   ra   r-  id_r,   r,   r-   rd   R  s   " z1Client.list_annotation_queues.<locals>.<listcomp>)idsrN  r  c                 s  r  r  )r  AnnotationQueue)ra   queuer,   r,   r-   r  Y  r  z0Client.list_annotation_queues.<locals>.<genexpr>/annotation-queuesr4  )	enumerater<  )r   r  rN  r  r0  r,   r,   r-   list_annotation_queuesI  s   
	zClient.list_annotation_queues)rJ  queue_idr  ls_schemas.AnnotationQueuec                C  sV   |||d}|  d| j ddd | D | jd}t| tjdi | S )N)rN  rJ  ro  r=  r  c                 S  r  rp   r,   rf   r,   r,   r-   ri   n  ry  z2Client.create_annotation_queue.<locals>.<dictcomp>rk   r   r,   )	r/  r0   r   r   r;   r
  r  r  rk   )r   rN  rJ  r  r?  r  r,   r,   r-   create_annotation_queue^  s   

zClient.create_annotation_queuec                 C  s   t | j|gdS )N)r  )rF  r  )r   r  r,   r,   r-   read_annotation_queueu  s   zClient.read_annotation_queue)rJ  c                C  s<   |  d| j dt|d ||d| jd}t| d S )Nr  /annotation-queues/r  )rN  rJ  r  )r/  r0   r   r   r;   r
  )r   r  rN  rJ  r  r,   r,   r-   update_annotation_queuey  s   zClient.update_annotation_queuec                 C  s2   | j j| j dt|d | jd}t| d S )Nr  r  r  r  )r   r  r  r,   r,   r-   delete_annotation_queue  s
   zClient.delete_annotation_queueList[ID_TYPE]c                C  sF   |  d| j dt|d ddd t|D | jd}t| d S )Nr=  r  r  r  c                 S  s&   g | ]\}}t t|d | dqS )zrun_ids[r  )r   r   r  r,   r,   r-   rd     r  z7Client.add_runs_to_annotation_queue.<locals>.<listcomp>r  )r/  r0   r   r  r   r;   r
  )r   r  r  r  r,   r,   r-   add_runs_to_annotation_queue  s   
z#Client.add_runs_to_annotation_queue/Iterator[ls_schemas.RunWithAnnotationQueueInfo]c                 c  s<    dt |d d}dd | j|d| jidD E d H  d S )Nr  r  r  c                 s  r  r  )r  RunWithAnnotationQueueInfor  r,   r,   r-   r    r  z9Client.list_runs_from_annotation_queue.<locals>.<genexpr>r   r4  )r   r<  r   )r   r  r9   r,   r,   r-   list_runs_from_annotation_queue  s
   z&Client.list_runs_from_annotation_queue   )
evaluationconcurrency_levelr  project_metadataverbosetagsinput_mapperr  llm_or_chain_factoryr  Optional[Any]r  r  r  r  r  Optional[Callable[[Dict], Any]]c                  sN   zddl m} W n ty   tdw |||| |||||||	|
dI dH S )a  
        Asynchronously run the Chain or language model on a dataset
        and store traces to the specified project name.

        Args:
            dataset_name: Name of the dataset to run the chain on.
            llm_or_chain_factory: Language model or Chain constructor to run
                over the dataset. The Chain constructor is used to permit
                independent calls on each example without carrying over state.
            evaluation: Optional evaluation configuration to use when evaluating
            concurrency_level: The number of async tasks to run concurrently.
            project_name: Name of the project to store the traces in.
                Defaults to {dataset_name}-{chain class name}-{datetime}.
            project_metadata: Optional metadata to store with the project.
            verbose: Whether to print progress.
            tags: Tags to add to each run in the project.
            input_mapper: A function to map to the inputs dictionary from an Example
                to the format expected by the model to be evaluated. This is useful if
                your model needs to deserialize more complex schema or if your dataset
                has inputs with keys that differ from what is expected by your chain
                or agent.
            revision_id: Optional revision identifier to assign this test run to
                track the performance of different versions of your system.

        Returns:
            A dictionary containing the run's project name and the
            resulting model outputs.

        For the synchronous version, see client.run_on_dataset.

        Examples
        --------

        .. code-block:: python

            from langsmith import Client
            from langchain.chat_models import ChatOpenAI
            from langchain.chains import LLMChain
            from langchain.smith import RunEvalConfig

            # Chains may have memory. Passing in a constructor function lets the
            # evaluation framework avoid cross-contamination between runs.
            def construct_chain():
                llm = ChatOpenAI(temperature=0)
                chain = LLMChain.from_string(
                    llm,
                    "What's the answer to {your_input_key}"
                )
                return chain

            # Load off-the-shelf evaluators via config or the EvaluatorType (string or enum)
            evaluation_config = RunEvalConfig(
                evaluators=[
                    "qa",  # "Correctness" against a reference answer
                    "embedding_distance",
                    RunEvalConfig.Criteria("helpfulness"),
                    RunEvalConfig.Criteria({
                        "fifth-grader-score": "Do you have to be smarter than a fifth grader to answer this question?"
                    }),
                ]
            )

            client = Client()
            await client.arun_on_dataset(
                "<my_dataset_name>",
                construct_chain,
                evaluation=evaluation_config,
            )

        You can also create custom evaluators by subclassing the
        :class:`StringEvaluator <langchain.evaluation.schema.StringEvaluator>`
        or LangSmith's `RunEvaluator` classes.

        .. code-block:: python

            from typing import Optional
            from langchain.evaluation import StringEvaluator

            class MyStringEvaluator(StringEvaluator):

                @property
                def requires_input(self) -> bool:
                    return False

                @property
                def requires_reference(self) -> bool:
                    return True

                @property
                def evaluation_name(self) -> str:
                    return "exact_match"

                def _evaluate_strings(self, prediction, reference=None, input=None, **kwargs) -> dict:
                    return {"score": prediction == reference}


            evaluation_config = RunEvalConfig(
                custom_evaluators = [MyStringEvaluator()],
            )

            await client.arun_on_dataset(
                "<my_dataset_name>",
                construct_chain,
                evaluation=evaluation_config,
            )
        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  N)langchain.smithr
  ImportError)r   r  r  r  r  r  r  r  r  r  r  _arun_on_datasetr,   r,   r-   r
    s*   xzClient.arun_on_datasetc                C  sF   zddl m} W n ty   tdw ||||| ||||||	|
dS )a  
        Run the Chain or language model on a dataset and store traces
        to the specified project name.

        Args:
            dataset_name: Name of the dataset to run the chain on.
            llm_or_chain_factory: Language model or Chain constructor to run
                over the dataset. The Chain constructor is used to permit
                independent calls on each example without carrying over state.
            evaluation: Configuration for evaluators to run on the
                results of the chain
            concurrency_level: The number of tasks to execute concurrently.
            project_name: Name of the project to store the traces in.
                Defaults to {dataset_name}-{chain class name}-{datetime}.
            project_metadata: Metadata to store with the project.
            verbose: Whether to print progress.
            tags: Tags to add to each run in the project.
            input_mapper: A function to map to the inputs dictionary from an Example
                to the format expected by the model to be evaluated. This is useful if
                your model needs to deserialize more complex schema or if your dataset
                has inputs with keys that differ from what is expected by your chain
                or agent.
            revision_id: Optional revision identifier to assign this test run to
                track the performance of different versions of your system.

        Returns:
            A dictionary containing the run's project name and the resulting model outputs.


        For the (usually faster) async version of this function, see `client.arun_on_dataset`.

        Examples
        --------

        .. code-block:: python

            from langsmith import Client
            from langchain.chat_models import ChatOpenAI
            from langchain.chains import LLMChain
            from langchain.smith import RunEvalConfig

            # Chains may have memory. Passing in a constructor function lets the
            # evaluation framework avoid cross-contamination between runs.
            def construct_chain():
                llm = ChatOpenAI(temperature=0)
                chain = LLMChain.from_string(
                    llm,
                    "What's the answer to {your_input_key}"
                )
                return chain

            # Load off-the-shelf evaluators via config or the EvaluatorType (string or enum)
            evaluation_config = RunEvalConfig(
                evaluators=[
                    "qa",  # "Correctness" against a reference answer
                    "embedding_distance",
                    RunEvalConfig.Criteria("helpfulness"),
                    RunEvalConfig.Criteria({
                        "fifth-grader-score": "Do you have to be smarter than a fifth grader to answer this question?"
                    }),
                ]
            )

            client = Client()
            client.run_on_dataset(
                "<my_dataset_name>",
                construct_chain,
                evaluation=evaluation_config,
            )

        You can also create custom evaluators by subclassing the
        :class:`StringEvaluator <langchain.evaluation.schema.StringEvaluator>`
        or LangSmith's `RunEvaluator` classes.

        .. code-block:: python

            from typing import Optional
            from langchain.evaluation import StringEvaluator

            class MyStringEvaluator(StringEvaluator):

                @property
                def requires_input(self) -> bool:
                    return False

                @property
                def requires_reference(self) -> bool:
                    return True

                @property
                def evaluation_name(self) -> str:
                    return "exact_match"

                def _evaluate_strings(self, prediction, reference=None, input=None, **kwargs) -> dict:
                    return {"score": prediction == reference}


            evaluation_config = RunEvalConfig(
                custom_evaluators = [MyStringEvaluator()],
            )

            client.run_on_dataset(
                "<my_dataset_name>",
                construct_chain,
                evaluation=evaluation_config,
            )
        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  )r  r  r  )r   r  r  r  r  r  r  r  r  r  r  _run_on_datasetr,   r,   r-   r  5  s(   yzClient.run_on_datasetrp   )r0   r   r   r   r   r   r   r   r   r   r   r   r   r!   r    r   )r    r   )r    r   )r    r  )r   r   r0   r   r   rW   r    r  )rN   NN)r  r   r   r   r  r   r  rW   r  r  r  r  r    r  )r9   r   r0  r1  r    r  )r9   r   r0  r5  r    r6  )
r9   r   r?  r5  r  r   r@  r   r    r6  )rL  rM  rN  r   rO  rP  rQ  rP  rJ  r   rK  rR  r    rS  )rZ  r]  rO  rP  rQ  rP  rN  r   rJ  r   rK  rR  r    rS  )rm  rn  r    rQ   )r>  ru  r    r   )r>  r  r  r!   r    r  )rN  r   r   r   r  r   r  r   r  r  r  r	   r    r   )NN)r  r  r~  r  r  r!   )r  r   r  r  r  r   r   r  r   r  r  r  r  r	   r    r   )rm  r  r    r  )F)r  r   r  r!   r    r  )r  r  r  r   r  r   r  r  r  r   r  r   r  r   r  r  rp  r  r  r  r  r  r  r	   r    r  )rm  r  r  r   r  r  r    r   )r  r   r  r  r    r   )r  r   r    r   )r  r   r    r   )r  r   r    r!   )r  r   r  r  r    r  )r  r  r  r   r    r  )r  r   r    r   )r  r   r    rS  )r  r   r  r  r    r  )
r  r   r  r  rN  r   r  r   r    r  )r  r   rJ  r   rS   r5  r  r!   r  r5  r  r  r    r  )r  r   rN  r   rJ  r   rS   r5  r  r5  r  r  r    r  )r    r   )r  r   r  r   r"  r!   r    r#  )r  r   r  r   r    r!   )r  r  r  r   r    r'  )NNNNNN)r  r  rN  r   r  r   r  r  rD  r   rE  r  r    rF  )r  r   r  r   r    r   )r  r   rJ  r   rK  rJ  r    rS  )r  r   r  r   r    r!   )r  r   r  r  r    rS  )r  r   r  r   r    r   )
rS  r  rK  r   r  r   rT  r   r    rU  )r  r  r  r   r    r   )r]  r   r\  r   r  r   r    r   )r  r   r    rJ  )NNNN)rk  r   rl  r   r  r  r  r   rm  r  r    rn  )ru  rv  rw  rx  r  r  r  r   rm  r  r    rn  )NNN)
rm  r  r  r  r  r   rm  r  r    rn  )r   r  r   r  r  r  r  r   r  r	   r    r   )NNNNN)r   r  r  r  r  r   rm  r  r   r  r(  r  r    rn  )r(  r   r    rn  )NNNT)
r  r  r  r   r  r  r  r!   r    r  )
r(  r   r   r1  r   r  r  r  r    r   )r(  r   r    r   )rm  r  r  r!   r    r  )rB  r  rm  r  r    r  )r>  r  r    r  )rm  r  r   r  r  r1  r  r  r  r!   r    r  )r  r  rm  r  r  r1  r    r  )rm  r  r   r  r  r1  r  r  r  r!   r    r  )r  r   r  r   r  r  r   r  r  r  r  r  r  r1  r  r  r  r  r  r  r  r!   r  rW   r    r  )r  r   r  r  r   r  r  r  r  r  r    r   )r  r   r    r  )
r  r  r  r  r  r  r  r	   r    r  )r  r   r    r   )r  r  rN  r   r  r   r    r  )rN  r   rJ  r   r  r  r    r  )r  r   r    r  )r  r   rN  r   rJ  r   r    r   )r  r   r    r   )r  r   r  r  r    r   )r  r   r    r  )r  r   r  r	   r  r  r  rW   r  r   r  r1  r  r!   r  r  r  r	  r  r   r    r   )_r   r   r   __doc__ro   r   r   r   propertyr   r   r  staticmethodr   r   r  r/  r3  r<  rI  r  rc  rd  r[  rY  rt  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rh  r;   xor_argsr  r&  rC  rH  rI  rL  rN  r  rR  rZ  r[  ri  r   rt  r  r  re  rs  r  r9  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r
  r  r,   r,   r,   r-   r   ?  s   F

|&87NT	bK%S&:1.G:)." @*S4<-'!5 4t() r   r9  r   r   r8  blockList[TracingQueueItem]c                 C  s   g }z6| j |dd }r|| | j |dd }r6|| |r*t||kr*W |S | j |dd }sW |S W |S  tyB   Y |S w )Ng      ?)r  r	  g?)r   r  r:   r   )r   r8  r  
next_batchr   r,   r,   r-   _tracing_thread_drain_queue  s"   

r  r  rA  c              	   C  sr   dd |D }dd |D }z z
| j ||dd W n	 ty"   Y nw W |D ]}|  q&d S |D ]}|  q1w )Nc                 S     g | ]
}|j d kr|jqS )r  r   r   ra   itr,   r,   r-   rd     r*  z0_tracing_thread_handle_batch.<locals>.<listcomp>c                 S  r  )r~  r  r  r,   r,   r-   rd     r*  T)r  r~  r  )r  rB   	task_done)r  r   rA  r  r~  _r,   r,   r-   _tracing_thread_handle_batch  s   

r  r        r  r  ls_schemas.BatchIngestConfigc                 C  sF   t jdtttd}| s|S z
| js|W S | jW S  ty"   | Y S w )Nr9  )
size_limitscale_up_nthreads_limitscale_up_qsize_triggerscale_down_nempty_trigger)r  BatchIngestConfig_AUTO_SCALE_UP_NTHREADS_LIMIT_AUTO_SCALE_UP_QSIZE_TRIGGER_AUTO_SCALE_DOWN_NEMPTY_TRIGGERbatch_ingest_configry   )r  default_configr,   r,   r-   _ensure_ingest_config  s   r-  
client_refweakref.ref[Client]c              
   C  s  |  }|d u r	d S z|j std|j  tjdd W d S W n ty6 } ztd| W Y d }~d S d }~ww |j}|d us@J t|j }|d }|d }|d }g }d}	t	
  rt||	t| kr|D ]}
|
 ss||
 qht||k r| |krt	jtt|fd	}|| |  t||d
 }rt||| t	
  rt||	t| ksft||dd }rt||| t||dd }sd S d S )Nz	no info: T)r_  flush#Error in tracing control thread: %sr#  r$  r%  rD   r   r8  Fr8  r  )r  printsysstderrry   r   r   r   r-  r   main_threadis_alivegetrefcountr:   r  qsizer   _tracing_sub_thread_funcr   r   r  r   r  r  )r.  r  r   r   r+  r#  r$  r%  sub_threadsnum_known_refsthread
new_threadr  r,   r,   r-   r     s^   





r   c              
   C  s  |  }|d u r	d S z|j sW d S W n ty* } ztd| W Y d }~d S d }~ww |j}|d us4J t|j }|dd}d}t 	 rn||d krnt
||d }r^d}t||| n|d7 }t 	 rn||d ksMt
||dd	 }rt||| t
||dd	 }swd S d S )
Nr1  r#  r9  r   r&  r2  rN   Fr3  )r  ry   r   r   r   r-  r   r   r7  r8  r  r  )r.  r  r   r   r+  r#  seen_successive_empty_queuesr  r,   r,   r-   r;  3  sL   




r;  )r   r   r    r!   )r/   r   r0   r   r    r1   )r    r   )r   )r\   r	   r]   rW   r    r	   )r   r   r    r   )r0   r   r   r   r    r   )r    r   )r   r   r    r   )r0   r   r   r   r    r   )r   r   r    r   )r   r   r    r   )r   r   r   r   r    r   )r9  T)r   r   r8  rW   r  r!   r    r  )r  r   r   r   rA  r  r    r   )r  r  r    r"  )r.  r/  r    r   )ar  
__future__r   r  r   r{   r   rR   rU  rk   loggingr   r&  r'   r5  r   r'  r5   r   r   r   r  r   r   r   typingr   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   urllibr   r#   r   r   r   urllib3.utilr   r   r   rz  r   r  r   r;   langsmith.evaluationr   r  r4  r=  	getLoggerr   r   	addFilterFilterPoolFullWarningr.   r@   rC   r6   r   r   r[   rW   r   r!   r}   rv   r`   r   r   r   r   r   r   r   r   r   r   r  r  r)  r(  r*  r-  r   r;  r,   r,   r,   r-   <module>   s    D




 
8






	                       


2