
    _Di~                      % S r SSKJr  SSKrSSKrSSKJr  SSKrSSK	r	SSK
r
SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKJrJrJrJrJr  SSK J!r!  SSK"J#r#  SSK$J%r%  SSKJ&r&J'r'J(r(J)r)J*r*J+r+J,r,J-r-  SS	K.J/r0  SSK1r1SS
K2J3r3  SSK1J4r5  SSK6J7r8  SSK9J:r:J;r;  SSK<J=r=  SSK>J?r?  SSK@r@SSK@JArB  SSK@JCrD  SSK@JErF  SSKGJHrH  SSKIJJrJ  SSKIJKrL  SSKMJNrN  SSKOJPrP  SSKQJRrRJSrSJTrTJUrU  SSKVJWrWJXrXJYrY  SSKZJ[r[J\r\J]r]J^r^J_r_J`r`JaraJbrb  SSKcJdre  SSKfJgrg  SSKhJiriJjrj  SrkSrlSYS  jrmS! rn SS"KoJprp   SS%KrJsrs  \&(       aA  SSKtruSS(KvJwrw  SSK@JCrC   SS)KxJyrz  SS*K{J|r|  SS+K}J~r  SS,KJrJrJr  SS-KJrJrJrJrJrJrJrJr  \GR                  " \5      r\GR                  " S.5      rS/rS0rS1\S2'   S3\!" \=5      GR(                  ;   rS4r  SZ         S[S5 jjrS\S6 jr\,\GR2                  \4   r\*S7   r\
GR:                  " S8S99S]S: j5       rS^S; jrS_S< jrS`S= jr Sa   SbS> jjrScS? jrSaSdS@ jjr\Rv                  SeSA j5       r\Rv                  SBSC.     SfSD jj5       rSESC.SgSF jjr\
GR:                  " S8S99SG 5       r " SH SI\5GRN                  5      r " SJ SK5      r Sa     ShSL jjr Sa     ShSM jjr " SN SO\GRX                  5      rSSP.       SiSQ jjrSjSR jrSkSS jrSlST jrSmSU jrSESV.SnSW jjrSoSX jrg! \q a     " S# S$5      rp GNf = f! \q a     " S& S'5      rs GNf = f! \q a    \(rz\(r| GNf = f)pa  Client for interacting with the LangSmith API.

Use the client to customize API keys / workspace connections, 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 the [LangSmith docs](https://docs.langchain.com/langsmith/home).
    )annotationsN)AsyncIterableIterableIteratorMappingSequence)	signature)Path)PriorityQueue)TYPE_CHECKING	AnnotatedAnyCallableLiteralOptionalUnioncast)parse)Field)adapters)	multipart)	TypeGuardoverload)PoolKey)Retry)env)schemas)utils)_orjson)TracingQueueItem)tracing_control_thread_func)	warn_beta)CompressedTraces)_AUTO_SCALE_UP_NTHREADS_LIMIT_BLOCKSIZE_BYTES	_BOUNDARY_SIZE_LIMIT_BYTES)MultipartPartMultipartPartsAndContext join_multipart_parts_and_context)SerializedFeedbackOperationSerializedRunOperation#combine_serialized_queue_operations$compress_multipart_parts_and_contextserialize_feedback_dictserialize_run_dict<serialized_feedback_operation_to_multipart_parts_and_context7serialized_run_operation_to_multipart_parts_and_context)
dumps_json)uuid7)AttachmentInfoExampleWithRunsOPENAI_API_KEYANTHROPIC_API_KEYc                 .    [         R                  " S5      $ )z3Check if OTEL is enabled and imports are available.OTEL_ENABLED)ls_utilsis_env_var_truish     X/var/www/html/Aiprofessor/professorTrac/lib/python3.13/site-packages/langsmith/client.py_check_otel_enabledr@   h   s    %%n55r>   c                 n     SSK Jn   SSKJn  SSKJn  SSKJn  XX#4$ ! [         a    [        S5      ef = f)z,Dynamically import OTEL modules when needed.r   trace)set_span_in_context)get_otlp_tracer_providerOTELExporterzKTo use OTEL tracing, you must install it with `pip install langsmith[otel]`)	opentelemetryrC   opentelemetry.tracerD   %langsmith._internal.otel._otel_clientrE   'langsmith._internal.otel._otel_exporterrG   ImportError)
otel_tracerD   rE   rG   s       r?   _import_otelrN   m   sC    
5;	
 	I0HVV 
Y
 	

s    4)ZoneInfoc                      \ rS rSrSrSrg)rO      zIntroduced in python 3.9.r=   N__name__
__module____qualname____firstlineno____doc____static_attributes__r=   r>   r?   rO   rO      s    'r>   rO   )TracerProviderc                      \ rS rSrSrSrg)rY      zUsed for optional OTEL tracing.r=   NrR   r=   r>   r?   rY   rY      s    -r>   rY   )RunnablerB   rF   	evaluator)AEVALUATOR_T	ATARGET_TAsyncExperimentResults)COMPARATIVE_EVALUATOR_TDATA_TEVALUATOR_TEXPERIMENT_TSUMMARY_EVALUATOR_TTARGET_TComparativeExperimentResultsExperimentResultszurllib3.connectionpool	x-api-keyr=   ztuple[dict, ...]	EMPTY_SEQkey_blocksizez:How are people using my agent? What are they asking about?c                    [        U [        R                  5      (       d  [        R                  " U 5      (       a  U[        U 5      4$  [
        R                  " [        U 5      5      nUR                  R                  S5      n[        U5      U:  a  XR*    n[        USS9  O[        R                  " SU SU  35      eUR                  S:X  a  SnX4$ UR                  S:X  a  S	nX4$ ! [         a     Nf = f)
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UUIDstr
ValueErrorurllib_parseurlparsepathsplitlen_as_uuidr;   LangSmithUserErrornetloc)url_or_tokenapi_url	num_partskind
parsed_url
path_parts
token_uuids          r?   _parse_token_or_urlr      s    lDII..$))L2I2IC--- 3J &&s<'89J&&s+J
:)#
+
/))OD6~*VWW113  
		8	88!  s   AC) )
C65C6c                     [         R                  " U 5      R                  R                  S5      S   nUS:H  =(       d    UR	                  S5      $ ! [
         a     gf = f)zCheck if the URL is langchain hosted.

Args:
    url (str): The URL to check.

Returns:
    bool: True if the URL is langchain hosted, False otherwise.
:r   zlangchain.comz.langchain.comF)rv   urlsplitr}   ry   endswith	Exception)urlr}   s     r?   _is_langchain_hostedr      sY    &&s+2288=a@(MFOO<L,MM s   AA 
AA)toolchainllm	retriever	embeddingpromptparser   maxsizec            	         [        S/ SQSSSSS9n [        R                  R                  S5      n[	        [        [        UR                  S5      5      5      S	:  nU(       a  S
U S'   [        R                  " S0 U D6$ )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.)r      Nallowed_methodsr=   )
dict	importlibmetadataversiontuplemapintry   r;   LangSmithRetry)retry_paramsurllib3_versionuse_allowed_methodss      r?   _default_retry_configr      s|     2#'L  ((00;OC)>)>s)C DEP*.&'""2\22r>   c                N    [         R                  S5        U R                  5         g)zPClose the session.

Args:
    session (requests.Session): The session to close.
zClosing Client.sessionN)loggerdebugclose)sessions    r?   close_sessionr     s     LL)*MMOr>   c                    U(       dn  [        U 5      (       a]  [        R                  " S5      (       dA  [        R                  " 5       (       a&  [        R
                  " S[        R                  5        ggggg)zVerify API key is provided if url not localhost.

Args:
    api_url (str): The API URL.
    api_key (Optional[str]): The API key.

Returns:
    None

Raises:
    LangSmithUserError: If the API key is not provided when using the hosted service.
r:   z8API key must be provided when using hosted LangSmith APIN)r   r;   r<   tracing_is_enabledwarningswarnLangSmithMissingAPIKeyWarningr   api_keys     r?   _validate_api_key_if_hostedr     s^      ))..~>>++--MMJ66 . ? * r>   c                H    [        U [        5      (       a  [        U S5      $ U $ )zFormat a feedback score by truncating numerical values to 4 decimal places.

Args:
    score: The score to format, can be a number or any other type

Returns:
    The formatted score
   )rq   floatround)scores    r?   _format_feedback_scorer   /  s"     %UALr>   c                    U c  [         R                  " S5      nU(       d  gO[        U 5      n[        U5      nUS:  d  US:  a  [         R                  " SU 35      eU$ )zYGet the tracing sampling rate.

Returns:
    Optional[float]: The tracing sampling rate.
NTRACING_SAMPLING_RATEr   r   zELANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: )r;   get_env_varrt   r   r|   )tracing_sampling_ratesampling_rate_strsampling_rates      r?   _get_tracing_sampling_rater   >  sy     $$001HI  !   56+,MqMA-))"O%
 	
 r>   c                   U =(       d    0 n 0 nU R                  5        H  u  p#UR                  5       nU(       d  [        R                  " S5      eUR                  5       R                  S5      R                  S5      R	                  S5      nUR                  5       R                  S5      R                  S5      n[        XE5        XQU'   M     U$ )Nz&LangSmith runs API URL cannot be empty"'rn   )itemsstripr;   r|   rstripr   )_write_api_urlsprocessed_write_api_urlsr   r   processed_urlprocessed_api_keys         r?   _get_write_api_urlsr   U  s    %+O!'--/		--.VWW%++-33C8>>sCJJ3O#MMO11#6<<SA#ME2C/ 0 $#r>   c                     [        U [        R                  5      (       d  [        R                  " U 5      $ U $ ! [         a,  nU=(       d    Sn[        R
                  " U SU  35      UeS nAff = f)Nvaluez* must be a valid UUID or UUID string. Got )rq   rr   rs   ru   r;   r|   )r   ro   es      r?   r{   r{   e  si    '1%'C'CtyyNN nW))e=eWE
	s   49 9 
A/'A**A/c                    g Nr=   )r   s    r?   _ensure_uuidr   o  s    GJr>   Taccept_nullc                   g r   r=   r   r   s     r?   r   r   s  s     r>   Fc               B    U c  U(       a  g [        5       $ [        U 5      $ r   )r4   r{   r   s     r?   r   r   y  s    }wE?r>   c                n    [         R                  " U 5      nUR                  R                  S5      S   nU$ )Nr   r   )rv   rw   r}   ry   )r   r   hosts      r?   
_parse_urlr     s2    &&s+J""3'*DKr>   c                     ^  \ rS rSr/ SQr\R                  \R                  \R                  \R                  S4           SU 4S jjjr	SU 4S jjr
SrU =r$ )	_LangSmithHttpAdapteri  )max_retriesconfig_pool_connections_pool_maxsize_pool_block
_blocksizei @  c                2   > XPl         [        TU ]	  XX45        g r   )r   super__init__)selfpool_connectionspool_maxsizer   
pool_block	blocksize	__class__s         r?   r   _LangSmithHttpAdapter.__init__  s     $)Qr>   c                \   > [         (       a  U R                  US'   [        TU ]  " XU40 UD6$ )Nr   )URLLIB3_SUPPORTS_BLOCKSIZEr   r   init_poolmanager)r   connectionsr   blockpool_kwargsr   s        r?   r   &_LangSmithHttpAdapter.init_poolmanager  s.    %%'+K$w'eS{SSr>   )r   )r   r   r   r   r   zUnion[Retry, int, None]r   boolr   r   returnNoneF)rS   rT   rU   rV   	__attrs__requests_adaptersDEFAULT_POOLSIZEDEFAULT_RETRIESDEFAULT_POOLBLOCKr   r   rX   __classcell__r   s   @r?   r   r     s    I !2 B B->>/@/P/P,>>	R	R 	R -		R
 	R 	R 
	R 	RT Tr>   r   c                     \ rS rSr% Sr/ SQrS\S'   S\S'   S\S'   S	\S
'   S\S'    GSSSSSSSSSSSSSSSSSSSSSSSSS.                                                 GSS jjjrGSS jrGSS jr	GSS jr
\GSS j5       r\GSS j5       rGSS jrGSS jr\GSS j5       r\R"                  GSS j5       r\GSS j5       r\R"                  GSS j5       r\GSS j5       rGSS jrGSS jrSS SSSS!S".                   GSS# jjrSS$.     GSS% jjrSS&S'S(.         GSS) jjrS\R4                  R6                  S*.             GSS+ jjrSS\R4                  R6                  S,.             GSS- jjr  GS       GSS. jjrGSS/ jrGSS0 jr SS1.     GS S2 jjr!SSSSSS3.                   GS!S4 jjr"SSS5.       GS"S6 jjr#SSS5.     GS#S7 jjr$GS$S8 jr%GS%S9 jr&GS&S: jr'GSS; jr(GS'S< jr)SSS=.       GS(S> jjr*  GS)SS?.       GS*S@ jjjr+SSS=.       GS+SA jjr,SSS=.       GS,SB jjr-  GS)SSSC.         GS-SD jjjr.SESSSF.       GS.SG jjr/SESH.     GS/SI jjr0SSSSSSSSSSSSSSSSJ.                                   GS0SK jjr1SSS5.     GS1SL jjr2SSS5.       GS2SM jjr3GS3GS4SN jjr4GS'SO jr5GS5SP jr6 GS6     GS7SQ jjr7SSSSSSSSSSSSSSSSSR.                                   GS8SS jjr8SSSSSSSSSSSSSSSSST.                                 GS9SU jjr9SSSV.       GS:SW jjr:SSX.GS;SY jjr;GS<SZ jr<GS=S[ jr=GS>S\ jr> GS     GS?S] jjr? GS     GS@S^ jjr@ GSSS_.     GSAS` jjjrA GSSS_.     GSASa jjjrBGSBSb jrC    GSCSc jrDSSSd.       GSDSe jjrESSSSSf.           GSESg jjrFSSSSSSh.             GSFSi jjrGSSSSSSj.             GSGSk jjrHGSHSl jrIGSISm jrJ\KR                  " Sn5      SSSSo.       GSJSp jj5       rMSSq.     GSKSr jjrNSSSn.     GSLSs jjrO          GSM                     GSNSt jjrP\KR                  " SV5      SSSV.     GSOSu jj5       rQS\R4                  R6                  SSSSSv.               GSPSw jjrRSSSx.     GSQSy jjrS\KR                  " Sx5      SSSx.     GSRSz jj5       rT GSSS_.         GSSS{ jjjrU GSSS_.     GSTS| jjjrVSSSSSSS}.             GSUS~ jjrW\KR                  " S5      SSS.     GSVS jj5       rXSSS.         GSWS jjrYSSSSS.         GSXS jjrZSSSSS.         GSYS jjr[SSS.       GSZS jjr\GS[S jr]\KR                  " S5          GS\           GS]S jj5       r^\KR                  " S5          GS\           GS^S jj5       r_   GS_         GS`S jjr`  GS       GSaS jjraSSS.       GSbS jjrbSSS.       GSbS jjrcSSS.       GScS jjrdGSdS jre GSe     GSfS jjrfSSS.       GScS jjrgSSS.     GSgS jjrh\KR                  " S5      SSSSS S.             GShS jj5       riS rjS rk\KR                  " S5                  GSi                         GSjS jj5       rlSS.     GSkS jjrm      GSlSSSSSS.                         GSmS jjjrn\oSS.       GSnS jj5       rp\o      GSoS j5       rq\oSS.           GSpS jj5       rrSSSSSSSS.                 GSqS jjrsSSSSS.           GSrS jjrtGSsS jruSS.     GStS jjrvSSSS.       GSuS jjrwSSSS.           GSvS jjrx      GSwS jry      GSxS jrzSS.     GSyS jjr{SSSS.           GSzS jjr|   GS_SS.           GS{S jjjr}SSSS.           GS|S jjr~  GS}SSSSSS\R                  GR                   SSSSSSSSSS.                                       GS~S jjjrSSSSS.           GSS jjrGSS jrSSSSS.           GSS jjrGSS jr GSSSSSS.             GSS jjjrSSSS.           GSS jjrSSS.         GSS jjrSS.     GSS jjrSSSSS.         GSS jjr    GSS jrSSS.           GSS jjr          GSS jrGSS jrSSSSS.         GSS jjrSSSS.         GSS jjrGSS jrSSS.         GSS jjrGSS jr      GSS jr      GSS jr      GSS jrSSSSSS.               GSS jjrGSS jr      GSS jr GS       GSS jjr      GSS jrGSS jrGSS jrGSS jrGSS jrSSSS\GR@                  GRB                  SSS.               GSS jjrGSS jrSSSSS.           GSS jjrSS.       GSS jjrSSSSSS.             GSS jjrGSS jrSS.     GSS jjrSSSS.         GSS jjrSS.     GSS jjrSSSSSSS.               GSS jjrGS'S jr\           GS                           GSS jj5       r\           GS                           GSS jj5       r            GS                             GSS jjr            GS                             GSS jjr    GS             GSGS  jjr      GS             GSGS jjr\o\SSSSGS.             GSGS jj5       r\oSSSGSGSSGS.             GSGS jj5       rSSSGS.       GSGS	 jjrGSGS
 jrGSrg(  Clienti  z.Client for interacting with the LangSmith API.))__weakref__r   _api_key_workspace_id_headers_custom_headersretry_config
timeout_ms_timeoutr   _get_data_type_cached_web_url
_tenant_idtracing_sample_rate_filtered_post_uuidstracing_queue_anonymizer_hide_inputs_hide_outputs_hide_metadata_omit_traced_runtime_info_process_buffered_run_ops_run_ops_buffer_size_run_ops_buffer_timeout_ms_run_ops_buffer_last_flush_time_infor   	_settings_manual_cleanup_pyo3_clientcompressed_traces_data_available_event_futures_run_ops_buffer_run_ops_buffer_lockotel_exporter_otel_trace_set_span_in_context_max_batch_size_bytes_tracing_error_callback_multipart_disabledOptional[str]r  dict[str, str]r  r  ztuple[float, float]r  r   r$  NTF)r   r  r  web_urlr   auto_batch_tracing
anonymizerhide_inputshide_outputshide_metadataomit_traced_runtime_infoprocess_buffered_run_opsrun_ops_buffer_sizerun_ops_buffer_timeout_msinfoapi_urlsotel_tracer_providerotel_enabledr   workspace_idmax_batch_size_bytesheaderstracing_error_callbackc                  U(       a  U(       a  [         R                  " S5      e[        R                  " S5      (       d  [        R                  " S5      (       a1  [        R                  " S5      (       a  [         R                  " S5      e[	        U5      U l        [        5       U l        [        U5      U l	        [         R                  " U5      U l        U=(       d    0 U l        U R                  (       aB  [        [        U R                  5      5      U l        U R                  U R                     U l        Os[         R"                  " U5      U l        [         R$                  " U5      U l        ['        U R                  U R                   5        U R                  U R                   0U l	        U=(       d
    [)        5       U l        [-        U[.        5      (       a  XD4O
U=(       d    SU l        U R0                  S   S-  U R0                  S	   S-  4U l        XPl        S
U l        U(       a  UO[8        R:                  " 5       nUU l        Ub  [-        U[>        R@                  5      (       a  UO[>        R@                  " S!0 UD6U l!        [D        RF                  " U [H        U R<                  5        [J        RL                  " [H        U5        S
U l'        S
U l(        S
U l)        / U l*        [V        RX                  " 5       U l-        S
U l.        UU l/        SU l0        U(       aL  [c        5       U l2        [V        Rf                  " [h        [D        Rj                  " U 5      4S9Rm                  5         OS
U l2        [o        U R*                  [p        [r        S	-   S9nU R<                  Ru                  SU5        U R<                  Ru                  SU5        [v        Rx                  " SS9" U Rz                  5      U l>        Xl?        U	b  U	O[         R                  " S5      S:H  U lA        U
b  U
O[         R                  " S5      S:H  U lB        Ub  UO[         R                  " S5      S:H  U lC        XlD        XlE        XlF        U=(       d    SU lG        [        R                  " 5       U lI        Ub  Uc  [        S5      eUc  Ub  [        S5      eS
U lK        [         R                  " S5      bF  S
n SS
KLnU(       a8  SnSnSnS	n  UR                  U R                  U R                   UUUU 5      U lK        S
U lS        SU lT        [        5       (       d  U(       a   [        5       u  n!n"n#n$U!R                  " 5       n%U%R                  [        5      n&Uc  [-        U%U!R                  5      (       aJ  [        U&S5      (       a9  [-        [        U!R                  U&5      R                  U!R                  5      (       d  [        [        U%5      nOU#" 5       nU!R                  " U5        U$" US9U l.        U!U lb        U"U lc        OS
U l.        UU lf        g
! [         a*  n[        R                  S[        U5      5         S
nAGNS
nAff = f! [         a*  n[        R                  S[        U5      5         S
nAGN{S
nAff = f! [         a     [        R                  " S 5        S
U l.         Nf = f)"a(  Initialize a `Client` instance.

Args:
    api_url (Optional[str]): URL for the LangSmith API. Defaults to the `LANGCHAIN_ENDPOINT`
        environment variable or `https://api.smith.langchain.com` if not set.
    api_key (Optional[str]): API key for the LangSmith API. Defaults to the `LANGCHAIN_API_KEY`
        environment variable.
    retry_config (Optional[Retry]): Retry configuration for the `HTTPAdapter`.
    timeout_ms (Optional[Union[int, Tuple[int, int]]]): Timeout for the `HTTPAdapter`.

        Can also be a 2-tuple of `(connect timeout, read timeout)` to set them separately.
    web_url (Optional[str]): URL for the LangSmith web app. Default is auto-inferred from
        the `ENDPOINT`.
    session (Optional[requests.Session]): The session to use for requests.

        If `None`, a new session will be created.
    auto_batch_tracing (bool, default=True): Whether to automatically batch tracing.
    anonymizer (Optional[Callable[[dict], dict]]): A function applied for masking serialized run inputs and outputs,
        before sending to the API.
    hide_inputs (Optional[Union[Callable[[dict], dict], bool]]): 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 (Optional[Union[Callable[[dict], dict], bool]]): 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.
    hide_metadata (Optional[Union[Callable[[dict], dict], bool]]): Whether to hide run metadata when tracing with this client.

        If `True`, hides the entire metadata.

        If a function, applied to all run metadata when creating runs.
    omit_traced_runtime_info (bool): Whether to omit runtime information from traced runs.

        If `True`, runtime information (SDK version, platform, Python version, etc.)
        will not be stored in the `extra.runtime` field of runs.

        Defaults to `False`.
    process_buffered_run_ops (Optional[Callable[[Sequence[dict]], Sequence[dict]]]): A function applied to buffered run operations
        that allows for modification of the raw run dicts before they are converted to multipart and compressed.

        Useful specifically for high throughput tracing where you need to apply a rate-limited API or other
        costly process to the runs before they are sent to the API.

        Note that the buffer will only flush automatically when `run_ops_buffer_size` is reached or a new run is added to the
        buffer after `run_ops_buffer_timeout_ms` has elapsed - it will not flush outside of these conditions unless you manually
        call `client.flush()`, so be sure to do this before your code exits.
    run_ops_buffer_size (Optional[int]): Maximum number of run operations to collect in the buffer before applying
        `process_buffered_run_ops` and sending to the API.

        Required when `process_buffered_run_ops` is provided.
    run_ops_buffer_timeout_ms (Optional[int]): Maximum time in milliseconds to wait before flushing the run ops buffer
        when new runs are added.

        Defaults to `5000`.

        Only used when `process_buffered_run_ops` is provided.
    info: 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.
    otel_tracer_provider (Optional[TracerProvider]): Optional tracer provider for OpenTelemetry integration.

        If not provided, a LangSmith-specific tracer provider will be used.
    tracing_sampling_rate (Optional[float]): The sampling rate for tracing.

        If provided, overrides the `LANGCHAIN_TRACING_SAMPLING_RATE` environment variable.

        Should be a float between `0` and `1`, where `1` means trace everything
        and `0` means trace nothing.
    workspace_id (Optional[str]): The workspace ID.

        Required for org-scoped API keys.
    max_batch_size_bytes (Optional[int]): The maximum size of a batch of runs in bytes.

        If not provided, the default is set by the server.
    headers (Optional[Dict[str, str]]): Additional HTTP headers to include in all requests.
        These headers will be merged with the default headers (User-Agent, Accept, x-api-key, etc.).
        Custom headers will not override the default required headers.
    tracing_error_callback (Optional[Callable[[Exception], None]]): Optional callback function to handle errors.

        Called when exceptions occur during tracing operations.

Raises:
    LangSmithUserError: If the API key is not provided when using the hosted service.
    LangSmithUserError: If both `api_url` and `api_urls` are provided.
z-You cannot provide both api_url and api_urls.LANGSMITH_ENDPOINTLANGCHAIN_ENDPOINTLANGSMITH_RUNS_ENDPOINTSz]You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS.)i'  i_ r     r   NF)targetargs)r   r   r   http://https://
   r   HIDE_INPUTStrueHIDE_OUTPUTSHIDE_METADATAi  zOrun_ops_buffer_size must be provided when process_buffered_run_ops is specifiedzOprocess_buffered_run_ops must be provided when run_ops_buffer_size is specifiedUSE_PYO3_CLIENTzaFailed to import `langsmith_pyo3` when PyO3 client was requested, falling back to Python impl: %s@B d   z|Failed to instantiate `langsmith_pyo3.BlockingTracingClient` when PyO3 client was requested, falling back to Python impl: %s_tracer)tracer_providerzuLANGSMITH_OTEL_ENABLED is set but OpenTelemetry packages are not installed: Install with `pip install langsmith[otel]r=   )gr;   r|   osgetenvr   r  setr  r   r   get_workspace_idr  r  nextiterr   r   get_api_urlget_api_keyr   r   r  rq   r   r  r  r  r  requestsSessionr   
ls_schemasLangSmithInfor"  weakreffinalizer   atexitregisterr&  r'  r(  r)  	threadingLockr*  r+  r.  r0  r   r  Thread_tracing_control_thread_funcrefstartr   r%   r$   mount	functools	lru_cache_get_data_typer  r  r   r  r  r  r  r  r  r   timer!  ru   r%  langsmith_pyo3rL   r   warningreprBlockingTracingClientr   r#  r$  r@   rN   get_tracer_provider
get_tracerrS   ProxyTracerProviderhasattrr   ProxyTracerrV  
NoOpTracerrY   set_tracer_providerr,  r-  r   r   r/  )'r   r   r   r  r  r3  r   r4  r5  r6  r7  r8  r9  r:  r;  r<  r=  r>  r?  r@  r   rA  rB  rC  rD  session_adapterrs  r   queue_capacity
batch_sizebatch_timeout_millisworker_threadsrM   rD   rE   rG   existing_providertracers'                                          r?   r   Client.__init__  s
   x x--? 
 II*++ryy9M/N/Nii233--0 
 $>>S#T 47E!<O=
 &66|D&}"T%9%9 :;DL//=DL#//8DL#//8DL'dllC$(LL$,,#?D (C,A,C *c** $0 0 	
 +d2DOOA4F4MN/3%78+;+;+= |z$
0H0HII ))1D1 	

 	}dll;x0=A@D">B79$-NN$4!59%9").  :G/D3 kk$')	
 eg!%D ())& 7:
 	9g.:w/%.%8%8%D&
" & & %%m4> 	 ' %%n5? 	 ( %%o6&@ 	
 *B&)A&$7!*C*Kt'/3yy{, $/4G4Oa  $+0C0Oa 
 ! 12>!N% !* 
'+$!"(6(L(L&",&)D% EI$  L&* !N',  %/$B$B$D!*55h?'/ ##4j6T6TUU#FI66&  * 6 6 & &g&11  04NDU/V,/G/I,"667KL%1BV%W" $. ,?) "&D'=$[  6G . ! NNZQ \  * L &*"	*sC   X3 //Y* C Z! 3
Y'=Y""Y'*
Z4ZZ!'[
[c                &    U R                   nSU S3$ )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     r?   _repr_html_Client._repr_html_   s     ~~4& VWWr>   c                    U R                   (       a   U R                  U5        gg! [         a    [        R                  SSS9   gf = f)zInvoke the background tracing error callback if configured.

Args:
    error: The exception that occurred during background tracing.
z!Error in tracing_error_callback:
Texc_infoN)r/  r   r   error)r   r  s     r?   _invoke_tracing_error_callback%Client._invoke_tracing_error_callback)  sM     '',,U3 (  8!  s   & AAc                "    SU R                    S3$ )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: )r   r   s    r?   __repr__Client.__repr__8  s     #4<<.22r>   c                ,    [        U R                  5      $ r   )r   r   r  s    r?   _hostClient._host@  s    $,,''r>   c                X    [         R                  " U R                  U R                  5      $ )zThe web host url.)r;   get_host_urlr  r   r  s    r?   r  Client._host_urlD  s     $$T]]DLLAAr>   c                    S[         R                   3SS.nUR                  U R                  5        U R                  (       a  U R                  U[
        '   U R                  (       a  U R                  US'   U$ )Nzlangsmith-py/application/json)z
User-AgentAcceptzX-Tenant-Id)	langsmith__version__updater  r   	X_API_KEYr  )r   rC  s     r?   _compute_headersClient._compute_headersI  sd    ))*?*?)@A(

 	t++,<<!%GI%)%7%7GM"r>   c                z    [         R                  XU5        [         R                  U SU R                  5       5        g)z8Set attributes that affect headers and recalculate them.r  N)object__setattr__r  )r   	attr_namer   s      r?   _set_header_affecting_attr!Client._set_header_affecting_attrW  s-    4E24T-B-B-DEr>   c                    U R                   $ )z+Return the API key used for authentication.)r  r  s    r?   r   Client.api_key\  s     }}r>   c                (    U R                  SU5        g )Nr  r  r   r   s     r?   r   r  a  s    ''
E:r>   c                    U R                   $ )z.Return the workspace ID used for API requests.)r  r  s    r?   rA  Client.workspace_ide  s     !!!r>   c                (    U R                  SU5        g )Nr  r  r  s     r?   rA  r  j  s    ''?r>   c           	        U R                   b  U R                   $ [        R                  " S5      =(       a    [        R                  " S5      nU(       a&  [        R                  " 5       U l         U R                   $  U R                  SSSS0U R                  S9n[        R                  " U5        [        R                  " S0 UR                  5       D6U l         U R                   $ ! [         a]  n[        R                  S	U R                   S
[        U5       35        [        R                  " 5       U l          SnAU R                   $ SnAff = f)zGet the information about the LangSmith API.

Returns:
    The information about the LangSmith API, or `None` if the API is not available.
Nr:   	OTEL_ONLYGETz/infor  r  )rC  timeoutzFailed to get info from : r=   )r"  r;   r<   rb  rc  request_with_retriesr  raise_for_status_with_textjsonBaseExceptionr   rt  r   ru  )r   otel_only_moderesponser   s       r?   r=  Client.infon  s    ::!:: "33
 6((5 	 #113DJ::	400!#56	 1 H //9#11DHMMODDJ zz  	4NN*4<<.47)D $113DJJzz	4s   ;AC$ $
E.AEEc                    U R                   cQ  U R                  SS5      n[        R                  " U5        [        R
                  " S0 UR                  5       D6U l         U R                   $ )zbGet the settings for the current tenant.

Returns:
    dict: The settings for the current tenant.
r  z	/settingsr=   )r#  r  r;   r  rb  LangSmithSettingsr  )r   r  s     r?   _get_settingsClient._get_settings  sS     >>!00DH//9'99LHMMOLDN~~r>   c                   Ub  U R                   c  g [        [        R                  U R                   5      nUR                  nU(       d  g U R
                  =(       d    UR                  S5      nUc  g X:  a	  SU SU S3$ g )Nsize_limit_byteszThe content length of z) bytes exceeds the maximum size limit of z bytes.)r"  r   rb  rc  batch_ingest_configr.  get)r   content_lengthr=  bic
size_limits        r?   _content_above_sizeClient._content_above_size  s    !TZZ%7J,,djj9&&//N377;M3N
&((8 9))3G= r>   r    )request_kwargsstop_after_attemptretry_on	to_ignorehandle_response_contextc                 U=(       d    0 nSU R                   0UEU	ES0 U R                  EUR                  S0 5      EU	R                  S0 5      E0EnUS:w  a-  SU;   a'  SU;  a!  US   R                  S5      (       d  SUS   S'   [        R                  " 5       [        R
                  " [        U R                  5      S9/n
/ U=(       d    S	Q[        R                  [        R                  [        R                  4Q7n/ U=(       d    S	Q7nS
n[        U5       Hu  n  [        R                  " [        U
5         U R                  R                  " U[!        U R"                  U5      4SS0UD6nS
S
S
5        [        R$                  " U5        Us  $    [        RL                  " S%U SU S:35      e! , (       d  f       NG= f! [&        R(                  R*                   a`  n[,        R/                  SU5        US-   U:X  a  e SU-  [0        R0                  " 5       S-  -   n[2        R4                  " U5         S
nAGM   S
nAf[&        R6                   GaP  nUGb  Ub"  US-   U:  a  U" XS-   5      nU(       a   S
nAGMa  UR8                  S:X  a*  [        R                  " SU SU S[;        U5       U 35      eUR8                  S:X  a  [        R                  " SU U SU 35      eUR8                  S:X  a'  [        R<                  " SU S[;        U5       U 35      eUR8                  S:X  a'  [        R>                  " SU S[;        U5       U 35      eUR8                  S:X  a'  [        R@                  " SU S[;        U5       U 35      eUR8                  S:X  a'  [        RB                  " SU S[;        U5       U 35      eUR8                  S :X  a~   URE                  5       nUR                  S!S"5      nUS#:X  a  [        RF                  " S$5      eO! [H        [J        4 a     Of = f[        RL                  " S%U SU S[;        U5       35      e[        RL                  " S%U SU S[;        U5       35      e[        RF                  " S%U SU S[;        U5       35      eS
nAf[&        RN                   Ga3  nU R"                  S&:w  a  S'OS(n [Q        UR                  (       a.  [        UR                  RR                  R                  S)5      5      OS"5      nU RU                  U5      nU(       a  UnO! [H         a    S
n Of = fUR                  (       a.  UR                  RR                  R                  S*5      =(       d    S"OS"nUS
S+ US,S
 nnS-[W        S.[Y        U5      S/-
  5      -  nU U U 3n[        R                  " S0U SU SU S[;        U5       S1U S2U U 35      UeS
nAf[Z         a  n[]        UR^                  5      n[Y        U5      S:  a  US   OS"nURa                  S3S45      nU(       aZ  S5Rc                  [        US.   5      /U/-   [Y        U5      S:  a  USS
 O/  Vs/ s H  n[        U5      PM     Os  snf sn-   5      nOUn[        RL                  " S%U SU SU U 35      UeS
nAff = f! U a.  nUb  [,        R/                  SU5        Us S
nAs  $  S
nAGM  S
nAf[        R<                   a    US-   U:X  a  e Ub_   [e        URR                  R                  S6S75      5      n O8! [Z         a+  n[,        Rg                  S8[;        U5      5        S9n  S
nAOS
nAff = fW SU-  -  [0        R0                  " 5       -   n [2        R4                  " U 5         GM  U aC    US-   U:X  a  e SU-  [0        R0                  " 5       S-  -   n[2        R4                  " U5         GM  f = f);a0  Send a request with retries.

Args:
    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 (Optional[Sequence[Type[BaseException]]]): The exceptions to retry on.

        In addition to: `[LangSmithConnectionError, LangSmithAPIError]`.
    to_ignore (Optional[Sequence[Type[BaseException]]]): The exceptions to ignore / pass on.
    handle_response (Optional[Callable[[requests.Response, int], Any]]): A function to handle the response and return whether to continue retrying.
    _context (str, default=""): The context of the request.
    **kwargs (Any): Additional keyword arguments to pass to the request.

Returns:
    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  rC  r  datafilesContent-Typer  )r   r=   NstreamFzPassing on exception %sr      r   i  zServer error caused failure to  z in LangSmith API. r   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 i  r  r  !org_scoped_key_requires_workspacezThis API key is org-scoped and requires workspace specification. Please provide 'workspace_id' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.z
Failed to rp   z'Please confirm your LANGCHAIN_ENDPOINT.z(Please confirm your internet connection.zContent-Lengthrj      *r      z#Connection error caused failure to z
Content-Length: z

API Key: r   zsession (project)
zretry-after30zInvalid retry-after header: %s   z in LangSmith API.)4r  r  r  r;   FilterLangSmithRetryFilterPoolFullWarningrt   r  LangSmithConnectionErrorLangSmithRequestTimeoutLangSmithAPIErrorrangefilter_logs_urllib3_loggerr   request_construct_urlr   r  r`  
exceptionsReadTimeoutr   r   randomrr  sleep	HTTPErrorstatus_coderu  LangSmithRateLimitErrorLangSmithAuthErrorLangSmithNotFoundErrorLangSmithConflictErrorr  r|   ru   KeyErrorLangSmithErrorConnectionErrorr   rC  r  maxrz   r   listrK  replacejoinr   rt  )!r   methodpathnamer  r  r  r  r  r  kwargslogging_filters	retry_on_
to_ignore_r  idxr   
sleep_timeshould_continue
error_data
error_coderecommendationr  size_recr   prefixsuffixfillermasked_api_keyrK  msgargemsgretry_afters!                                    r?   r  Client.request_with_retries  sE   L (-2t}}	
	
 	
  -- $$Y3 **Y+		
 eO.(~-"9-11.AA8JN9%n5))+**DJJ@
6
n"6
 1100**6
	 7Lb6K
+,C]B!--oO#'<<#7#7"*4<<B$ $)$ -	$ P 77A#O -B %%(+=>
 	
} PO  **66 LL!:A>Qw"44!"C6==?S+@!AJJJz*)) ?+*6"Qw);;2A(RSG2T#2$,#//36"*"<"<"A&"#H: .3377)#+*!.#  &11S8"*"B"B"J6(#+*AhZ!9#  &11S8"*"B"B":8*BtAwi#+*!.#  &11S8"*"="="<XJba	#+*!.#  &11S8"*"A"A"9(2d1gY#+*!.#  &11S8"*"A"A"/zDG9XJ O#  &11S8
%-5]]_
-7^^GR-H
#-1T#T*2*E*E)^+& %& $U %/#9 % $%"*"9"9",VHAhZ @))-a	!3# 
 #+"9"9",VHAhZ @))-a	!3#  '99((;NtTUwiX   //    <<+LL BG #

.), yy  		 1 1 5 56F GH!#*
 $(#;#;N#K#-5N% .)-. EFII		))--k:@bSU  &-Ra['"#,FF C3w<!+;$<=F(.xxx%@N";;=fXQxj-n-=DG9,^,<%n%5#*&  ! <D%(Y]$q'C++i1DEC#yy a\N"e$@CD	ADHSU4UW4UCs3x4UWX   #"11$VHAhZ7J4&#*&    $'LL!:A>#O ( 33 (700')&+H,<,<,@,@PT,U&V$ )< G ')) *AsF2V]]_D

;'' 700Vv}}'<=


:&s  G 95F/.G /
F=	9G  Z6AH92Z99Z6"R3Z9:ER>PRP!R P!!A;RZ64W"	A$T.-W".T=:W"<T==B%W""Z6/A9Z1(Y>=4Z11Z66Z99_+?[(_+($_+%\32_+3
](=!]#_+#]((7_+#A_+*_+paramsc             #  D  #    U(       a  UR                  5       O0 nUR                  SS5      nUR                  SS5      US'    XCS'   U R                  SUUS9nUR                  5       nU(       d  gU Sh  vN   [	        U5      US   :  a  gU[	        U5      -  nMZ   N'7f)zGet a paginated list of items.

Args:
    path (str): The path of the request URL.
    params (Optional[dict]): The query parameters.

Yields:
    The items in the paginated list.
offsetr   limitrU  r  r  N)copyr  r  r  rz   )r   rx   r  params_r  r  r   s          r?   _get_paginated_listClient._get_paginated_list  s      $*&++-rXq)";;w4 &H00 1 H
 MMOE5zGG,, c%j F  s   A4B 6B7(B POSTruns)bodyrequest_methoddata_keyc             #  d  #    U(       a  UR                  5       O0 n U R                  UUS[        U5      0S9nUR                  5       nU(       d  gUR	                  U5      (       d  gXt    Sh  vN   UR	                  S5      nU(       d  gUR	                  S5      (       d  gUS   US'   M   N>7f)ac  Get a cursor paginated list of items.

Args:
    path (str): The path of the request URL.
    body (Optional[dict]): The query body.
    request_method (Literal["GET", "POST"], default="POST"): The HTTP request method.
    data_key (str, default="runs"): The key in the response body that contains the items.

Yields:
    The items in the paginated list.
r  r  Ncursorsr\  cursor)r  r  _dumps_jsonr  r  )	r   rx   r   r!  r"  r  r  response_bodyr%  s	            r?   _get_cursor_paginated_list!Client._get_cursor_paginated_list  s     & "&$))+200K0  1 H %MMOM  $$X..$...#''	2G;;v&& 'GH'  /s   A-B0/B.0?B0)description	data_typec          	         [         R                  " 5       nUR                  USS9  UR                  S5        U R	                  SU4UUUUUS9$ )aS  Upload a dataframe as individual examples to the LangSmith API.

Args:
    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 (Optional[str]): The description of the dataset.
    data_type (Optional[DataType]): The data type of the dataset.

Returns:
    Dataset: The uploaded dataset.

Raises:
    ValueError: If the `csv_file` is not a `str` or `tuple`.

Example:
    ```python
    from langsmith import Client
    import os
    import pandas as pd

    client = Client()

    df = pd.read_parquet("path/to/your/myfile.parquet")
    input_keys = ["column1", "column2"]  # replace with your input column names
    output_keys = ["output1", "output2"]  # replace with your output column names

    dataset = client.upload_dataframe(
        df=df,
        input_keys=input_keys,
        output_keys=output_keys,
        name="My Parquet Dataset",
        description="Dataset created from a parquet file",
        data_type="kv",  # The default
    )
    ```
F)indexr   zdata.csv)
input_keysoutput_keysr+  namer,  )ioBytesIOto_csvseek
upload_csv)r   dfr1  r/  r0  r+  r,  csv_files           r?   upload_dataframeClient.upload_dataframe  sY    ` ::<
		(%	(a"!##  
 	
r>   )r1  r+  r,  c                  UUS.nU(       a  XGS'   U(       a  XWS'   U(       a  [         R                  " U5      US'   [        [        R                  " 5       5      US'   [        U[        5      (       a,  [        US5       nSU0n	U R                  SS	UU	S
9n
SSS5        O5[        U[        5      (       a  U R                  SS	USU0S
9n
O[        S5      e[         R                  " W
5        U
R                  5       nSU;   aH  SUS   ;   a?  [        U[        5      (       a  UOUS   nUR                  S5      S   n[        SU S35      e[        R                  " S0 UDU R                  U R!                  5       S.D6$ ! , (       d  f       N= f)a  Upload a CSV file to the LangSmith API.

Args:
    csv_file (Union[str, Tuple[str, io.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 (Optional[str]): The name of the dataset.
    description (Optional[str]): The description of the dataset.
    data_type (Optional[ls_schemas.DataType]): The data type of the dataset.

Returns:
    Dataset: The uploaded dataset.

Raises:
    ValueError: If the `csv_file` is not a string or tuple.

Example:
    ```python
    from langsmith import Client
    import os

    client = Client()

    csv_file = "path/to/your/myfile.csv"
    input_keys = ["column1", "column2"]  # replace with your input column names
    output_keys = ["output1", "output2"]  # replace with your output column names

    dataset = client.upload_csv(
        csv_file=csv_file,
        input_keys=input_keys,
        output_keys=output_keys,
        name="My CSV Dataset",
        description="Dataset created from a CSV file",
        data_type="kv",  # The default
    )
    ```
)r/  r0  r1  r+  r,  idrbfiler  z/datasets/upload)r  r  Nz"csv_file must be a string or tupledetailzalready existsr   rn   Dataset z already existsr  r  r=   )r;   get_enum_valuert   rr   uuid4rq   openr  r   ru   r  r  ry   rb  Datasetr  _get_optional_tenant_id)r   r8  r/  r0  r1  r+  r,  r  ffile_r  result	file_names                r?   r6  Client.upload_csv!  s   j %&
 L"- ( 7 7	 BD&T
h$$h%44&	 5  &% %((00"x(	 1 H ABB++H5v"2fX6F"F$.x$=$=8A;I!,R0Ix	{/BCC!! 

nn335
 	
1 &%s   >E::
Fc                   [        US5      (       a+  [        [        US5      5      (       a  UR                  5       nO[	        [        U5      nSU;  a  [
        R                  " 5       US'   O4[        US   [        5      (       a  [
        R                  " US   5      US'   SU;   a@  US   b:  U(       a  [        R                  " US   5      US'   U R                  US   5      US'   SU;   a@  US   b:  U(       a  [        R                  " US   5      US'   U R                  US   5      US'   SU;   ac  [        US   [        5      (       aK  US   nSU;   a@  US   b:  U(       a  [        R                  " US   5      US'   U R                  US   5      US'   U(       dP  UR                  S5      (       d:  [         R                   R#                  [         R$                  R&                  5      US'   S	U;   aT  UR                  S
5      S;  a  UR)                  S	S5        U$ UR                  S	5      (       a  US	   R)                  SS5        U$ )aZ  Transform the given run object into a dictionary representation.

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

Returns:
    dict: The transformed run object as a dictionary.
r   r<  inputsNoutputsextrar   
start_time
serializedrun_type)r   r   graph)rz  callablegetattrr   r   rr   rD  rq   rt   rs   r;   deepish_copy_hide_run_inputs_hide_run_outputs_hide_run_metadatar  datetimenowtimezoneutcpop)r   runr  r  
run_createrP  s         r?   _run_transformClient._run_transform  s     3HWS&-A$B$B"xxzJdCJz!#zz|Jt
4(#..#yyD)9:Jtz!j&:&F'/'<'<Z=Q'R
8$#'#8#8H9M#NJx 
"z)'<'H(0(=(=j>S(T
9%$($:$::i;P$QJy!j Z
70CT%J%Jw'EU"uZ'8'D(0(=(=eJ>O(PE*%$($;$;E*<M$Nj!jnn\::'/'8'8'<'<X=N=N=R=R'SJ|$ :%~~j)1BB|T2
 	 --<(,,Wd;r>   c           	        U R                   (       a  g [        R                  " 5       nU H  n[        [        UR                  S0 5      5      nUR                  S0 5      n0 UEUEUS'   UR                  S0 5      n[        R                  " 5       nUR                  UR                  5        VV	s0 s H  u  pX;  d  M  X_M     sn	n5        M     g s  sn	nf )NrP  runtimer   )	r  ls_envget_runtime_environmentr   r   
setdefaultget_langchain_env_var_metadatar  r   )
r   r  runtime_envra  	run_extrare  r   langchain_metadatakvs
             r?   _insert_runtime_envClient._insert_runtime_env  s    ))446JT:#8#8"#EFI%00B?G#=k#=W#=Ii &11*bAH!'!F!F!HOO"4":":"<R"<$!@Q"<R  Ss   -C<Cc                b    U R                   c  g[        R                  " 5       U R                   :  $ )NT)r  r  r  s    r?   _should_sampleClient._should_sample  s(    ##+}}!9!999r>   patchc               :   U R                   c  [        U5      $ U(       ac  / nU HY  n[        US   5      nXPR                  ;  a  UR	                  U5        M3  US   U:X  d  M>  U R                  R                  U5        M[     U$ / nU H  nUR                  S5      =(       d    US   nXPR                  ;   a  M1  US   U:X  aE  U R                  5       (       a  UR	                  U5        Mb  U R                  R                  U5        M  UR	                  U5        M     U$ )Ntrace_idr<  )	r  r  r{   r  appendremover  rr  add)r   r  ru  sampledr`  rw  s         r?   _filter_for_samplingClient._filter_for_sampling  s    ##+:G#C
O4#<#<<NN3'Y(*--44X>  NG77:.;#d) 888 t9(**,,s+1155h? NN3'   Nr>   )project_namerevision_iddangerously_allow_filesystemr   r   c               $   U=(       d%    U	R                  S[        R                  " 5       5      n0 U	EUUUUS.En
U R                  U
/5      (       d  gUb
  XZS   S   S'   U R	                  U
SS9n
U R                  U
/5        U
R                  S	5      b]  U
S	   R                  5        HF  n[        U[        5      (       d  M  [        US
   [        5      (       d  M4  U(       a  M=  [        S5      e   U R                  (       ao  U	R                  S5      (       dY  U R                     U R                  R                  SU
45        U R!                  5       (       a  U R#                  5          SSS5        gU R%                  XUS9  g! , (       d  f       g= f)a  Persist a run to the LangSmith API.

Args:
    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.
    project_name (Optional[str]): The project name of the run.
    revision_id (Optional[Union[UUID, str]]): The revision ID of the run.
    api_key (Optional[str]): The API key to use for this specific run.
    api_url (Optional[str]): The API URL to use for this specific run.
    **kwargs (Any): Additional keyword arguments.

Returns:
    None

Raises:
    LangSmithUserError: If the API key is not provided when using the hosted service.

Example:
    ```python
    from langsmith import Client
    import datetime
    from uuid import uuid4

    client = Client()

    run_id = uuid4()
    client.create_run(
        id=run_id,
        project_name=project_name,
        name="test_run",
        run_type="llm",
        inputs={"prompt": "hello world"},
        outputs={"generation": "hi there"},
        start_time=datetime.datetime.now(datetime.timezone.utc),
        end_time=datetime.datetime.now(datetime.timezone.utc),
        hide_inputs=True,
        hide_outputs=True,
    )
    ```
session_name)r  r1  rN  rS  NrP  r   r  Fr  attachmentsr   UMust set dangerously_allow_filesystem=True to allow passing in Paths for attachments.is_run_ops_buffer_flushpostr   r   )r_  r;   get_tracer_projectr|  rb  ro  r  valuesrq   r   r
   ru   r  r*  r)  rx  _should_flush_run_ops_buffer_flush_run_ops_buffer_create_run)r   r1  rN  rS  r~  r  r  r   r   r  ra  
attachments               r?   
create_runClient.create_run  sz   n $ 
vzz'')(



( 

 ((*66"=Hw
+M:((%(@
  *.>>-(4(7>>@
z511":a=$7788$o  A ))&**=V2W2W**$$++VZ,@A4466..0 +* Z'J +*s   #AF
Fr  c                  UR                  S5      Gb  UR                  S5      Gb	  U R                  b  U R                  R                  U5        g U R                  b  Uc  Uc  U R                  c  [        S5      e[        SU5      n[        U5      u  nn[        R                  SSUR                  5        U R                  R                     [        UU R                  [        5      nU(       a9  U R                  =R                  S-  sl        U R                  R                  5         S S S 5        [!        [#        UR%                  5       5      5        g U R&                  b  [        SU5      n[        R                  SSUR(                  UR*                  5        U R,                  bQ  U R&                  R/                  [1        US   UUUU R3                  U R4                  R7                  5       5      S	95        g U R&                  R/                  [1        US   UUUS
95        g U R9                  XUS
9  g U R9                  XUS
9  g ! , (       d  f       GN = f)Nrw  dotted_order@Run compression is enabled but threading event is not configuredr  r  5Adding compressed multipart to queue with context: %sr   /Adding to tracing queue: trace_id=%s, run_id=%sr   r   otel_contextr  )r  r%  r  r&  r'  ru   r0   r2   r   logcontextlockr.   r&   trace_countrZ  _close_filesr  r  r  rw  r<  r+  putr    r-  r,  get_current_span_create_run_non_batch)r   ra  r   r   serialized_opmultipart_formopened_filesenqueueds           r?   r  Client._create_runK  s&    NN:&2~.:  ,!!,,Z8&&2OO--5$Z  !36: F L!"  

K"**
 ++00C&..! H
  ..::a?:22668 1 T,"5"5"789##/ 26: F

E!**!$$	 %%1&&**(&~6)$+$+)-)B)B $ 0 0 A A C*
 &&**(&~6)$+$+	 **:PW*X&&zG&T[ 10s   AI
Ic                  / nUc  Ubr  U=(       d    U R                   nU=(       d    U R                  n0 U R                  E[        U0En U R	                  SU S3[        U5      US.[        R                  4S9  OjU R                  R                  5        HL  u  p0 U R                  E[        U
0En U R	                  SU	 S3[        U5      US.[        R                  4S9  MN     U(       aO  [        U5      S:  a'  [        R                  " US9nU R                  U5        UeU R                  US   5        US   eg ! [         a  nUR                  U5         S nANwS nAff = f! [         a  nUR                  U5         S nAM  S nAff = f)Nr  /runsr  rC  )r  r  r   )r  r   )r   r   r  r  r  r'  r;   r  r   rx  r   r   rz   LangSmithExceptionGroupr  )r   ra  r   r   errorstarget_api_urltarget_api_keyrC  r   write_api_urlwrite_api_keyexception_groups               r?   r  Client._create_run_non_batch  s    '"5$4N$4NBB	>BG!))%&e, +J 7#*$  (>>@ *  150D0D0J0J0L,ET]]EI}E%--(//$/
$;'.( $,#B#B"D .  1M 6{Q"*"B"Bf"U33OD%%33F1I>Qi %  !a  !  ! %MM!$$%s0   
0D< 10E$<
E!EE!$
F
.FF
c                    U R                   SL a  0 $ U R                  (       a0  [        R                  " [	        U5      5      nU R                  U5      $ U R                   SL a  U$ U R                  U5      $ NTF)r  r  r   loadsr'  )r   rN  json_inputss      r?   rX  Client._hide_run_inputs  sf    $I!--F(;<K##K00%M  ((r>   c                    U R                   SL a  0 $ U R                  (       a0  [        R                  " [	        U5      5      nU R                  U5      $ U R                   SL a  U$ U R                  U5      $ r  )r  r  r   r  r'  )r   rO  json_outputss      r?   rY  Client._hide_run_outputs  sf    %I"==W)=>L##L11&N!!'**r>   c                h    U R                   SL a  0 $ U R                   SL a  U$ U R                  U5      $ r  )r  )r   r   s     r?   rZ  Client._hide_run_metadata  s9    $&I%'O""8,,r>   c                   U R                   (       d  gU R                  b$  [        U R                   5      U R                  :  a  gU R                  b5  [        R                  " 5       U R
                  -
  nXR                  S-  :  a  gg)zDCheck if the run ops buffer should be flushed based on size or time.FTrI  )r)  r  rz   r   rr  r!  )r   time_since_last_flushs     r?   r  #Client._should_flush_run_ops_buffer  st    ## %%1D(()T-F-FF **6$(IIK$2V2V$V!$)H)H4)OPr>   c                r   U R                   (       d  g[        U R                   5      nU R                   R                  5         [        R                  " 5       U l        SSKJnJn   UR                  X0U5      nU R                  b  U R                  R                  U5        gg! [         a    U" X5         gf = f)z8Process and flush run ops buffer in a background thread.Nr   )LANGSMITH_CLIENT_THREAD_POOL_process_buffered_run_ops_batch)r)  r  clearrr  r!  &langsmith._internal._background_threadr  r  submitr(  rz  RuntimeError)r   batch_to_processr  r  futures        r?   r  Client._flush_run_ops_buffer  s    ##   4 45""$/3yy{,	

		D188/7GF }}(!!&) ) 	D+DC	Ds   %:B! !B65B6r   c                  / / S.nU GH4  n[        U[        5      (       Ga  [        R                  " UR                  5      nUR
                  (       a#  [        R                  " UR
                  5      US'   UR                  (       a#  [        R                  " UR                  5      US'   UR                  (       a#  [        R                  " UR                  5      US'   UR                  (       a#  [        R                  " UR                  5      US'   UR                  (       a#  [        R                  " UR                  5      US'   UR                  (       a#  [        R                  " UR                  5      US'   UR                  (       a  [        R                  S5        XER                     R!                  S	UR"                   S
UR$                   3[        R&                  " U5      45        GM  [        U[(        5      (       a  [        R                  S5        GM  [        R                  S[+        U5      5        GM7     U R,                  nU R.                  =(       d1    UR0                  =(       d    0 R3                  S5      =(       d    [4        n[6        R8                  " [:        5      n	[6        R8                  " [:        5      n
Sn[=        [:        [>        S      SS/5       GH  n[6        R@                  " XL   5      nU(       d  M%  US:  aw  U[C        US   S   5      -   U:  a_  U RE                  [        R&                  " U	5      SU SSRG                  X   5       3UUS9  SnU	RI                  5         U
RI                  5         URK                  5       u  pU[C        U5      -  nX   R!                  [        R                  " U5      5        X   R!                  U5        U(       a  M  GM     U(       aP  SRG                  S U
RM                  5        5       5      nU RE                  [        R&                  " U	5      SU-   UUS9  g g )N)r  ru  rN  rO  eventsrP  r  rR  zBAttachments 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: %sr  r   r  ru  r   r  r  ; )r  r   r   c              3  R   #    U  H  u  pU S SR                  U5       3v   M     g7f)r  r  N)r  ).0rm  rn  s      r?   	<genexpr>/Client._batch_ingest_run_ops.<locals>.<genexpr>g  s'     WCV411#R		!~ 6CVs   %')'rq   r,   r   r  _nonerN  FragmentrO  r  rP  r  rR  r  r   rt  	operationrx  rw  r<  dumpsr+   typer=  r.  r  r  r'   collectionsdefaultdictr  r   r   dequerz   _post_batch_ingest_runsr  r  popleftr   )r   opsr   r   ids_and_partial_bodyop	curr_dictr=  r  body_chunkscontext_ids	body_sizekey
body_dequecurr_id	curr_bodyr  s                    r?   _batch_ingest_run_opsClient._batch_ingest_run_ops  sW    
 	 B"455#MM"((3	99*1*:*:299*EIh'::+2+;+;BJJ+GIi(99*1*:*:299*EIh'88)0)9)9"(()CIg&88)0)9)9"(()CIg&==.5.>.>r}}.MIl+>>NN# %\\299bkk]$ruug6i8PQ B ;<<Q EtBxP9 > yy&& !((.B334FG!  	 ;F:Q:QRV:W:E:Q:QRV:W	W_568IJC$**+?+DEJ*M!C
1a(8$99<LL00k2#%cU"TYY{7G-H,I!J ' '	 1  !"I%%'%%'%/%7%7%9"S^+	 ''(8(8(CD ''0# * K( iiW;CTCTCVWWG((k*	 )  r>   )pre_sampledc               
   U(       d  U(       d  gU=(       d    [          Vs/ s H  o@R                  USS9PM     nnU=(       d    [          Vs/ s H  nU R                  USSS9PM     nnU HE  nUR                  S5      (       a  UR                  S5      (       a  M1  [        R                  " S5      e   U HE  nUR                  S5      (       a  UR                  S5      (       a  M1  [        R                  " S5      e   U(       d!  U R                  U5      nU R                  USS	9nU(       d  U(       d  gU R                  (       aB  U(       a  [        U R                  U5      5      nU(       a  [        U R                  U5      5      nU R                  XV-   5        [        [        [           [        [        [        R                  " S
 U 5       S U 5       5      5      5      5      nU R                  U5        gs  snf s  snf )a
  Batch ingest/upsert multiple runs in the Langsmith system.

Args:
    create (Optional[Sequence[Union[Run, RunLikeDict]]]):
        A sequence of `Run` objects or equivalent dictionaries representing
        runs to be created / posted.
    update (Optional[Sequence[Union[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, default=False): Whether the runs have already been subject
        to sampling, and therefore should not be sampled again.

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

Returns:
    None

!!! note

    The run objects MUST contain the `dotted_order` and `trace_id` fields
    to be accepted by the API.

Example:
    ```python
    from langsmith import Client
    import datetime
    from uuid import uuid4

    client = Client()
    _session = "__test_batch_ingest_runs"
    trace_id = uuid4()
    trace_id_2 = uuid4()
    run_id_2 = uuid4()
    current_time = datetime.datetime.now(datetime.timezone.utc).strftime(
        "%Y%m%dT%H%M%S%fZ"
    )
    later_time = (
        datetime.datetime.now(datetime.timezone.utc) + timedelta(seconds=1)
    ).strftime("%Y%m%dT%H%M%S%fZ")

    runs_to_create = [
        {
            "id": str(trace_id),
            "session_name": _session,
            "name": "run 1",
            "run_type": "chain",
            "dotted_order": f"{current_time}{str(trace_id)}",
            "trace_id": str(trace_id),
            "inputs": {"input1": 1, "input2": 2},
            "outputs": {"output1": 3, "output2": 4},
        },
        {
            "id": str(trace_id_2),
            "session_name": _session,
            "name": "run 3",
            "run_type": "chain",
            "dotted_order": f"{current_time}{str(trace_id_2)}",
            "trace_id": str(trace_id_2),
            "inputs": {"input1": 1, "input2": 2},
            "error": "error",
        },
        {
            "id": str(run_id_2),
            "session_name": _session,
            "name": "run 2",
            "run_type": "chain",
            "dotted_order": f"{current_time}{str(trace_id)}."
            f"{later_time}{str(run_id_2)}",
            "trace_id": str(trace_id),
            "parent_run_id": str(trace_id),
            "inputs": {"input1": 5, "input2": 6},
        },
    ]
    runs_to_update = [
        {
            "id": str(run_id_2),
            "dotted_order": f"{current_time}{str(trace_id)}."
            f"{later_time}{str(run_id_2)}",
            "trace_id": str(trace_id),
            "parent_run_id": str(trace_id),
            "outputs": {"output1": 4, "output2": 5},
        },
    ]

    client.batch_ingest_runs(create=runs_to_create, update=runs_to_update)
    ```
NFr  T)r  r  rw  r  z:Batch ingest requires trace_id and dotted_order to be set.rt  c              3  :   #    U  H  n[        S U5      v   M     g7fr  Nr0   r  r`  s     r?   r  +Client.batch_ingest_runs.<locals>.<genexpr>  s     QLS+FC88L   c              3  :   #    U  H  n[        S U5      v   M     g7fru  Nr  r  s     r?   r  r    s     R\c+GS99\r  )rk   rb  r  r;   r|   r|  r  r  ro  r   r,   r-   	itertoolsr   r  )r   creater  r  r`  create_dictsupdate_dictsserialized_opss           r?   batch_ingest_runsClient.batch_ingest_runso  s   F f =C<Oi<O
<OS%0<O 	 

 **
* Du=* 	 
  C77:&&cggn.E.E11P   
  C77:&&cggn.E.E11P    44\BL44\4NLL ))#D$B$B<$PQ#D$B$B<$PQ  !<= '(/OOQLQR\R

 	"">2_

s   G;H c          
     |   Ub  Ub  X40nOU R                   nUR                  5        H^  u  pg [        R                  SU SU 35        U R	                  SU S3U0 U R
                  E[        U0ES.[        R                  4SUS9  M`     g ! [         a  n [        R                  " [        U5      U5      n	SR                  U	5      R                  5       n
[        R                  S	U
 35        O1! [         a$    [        R                  S	[!        U5       35         Of = fU R#                  U5         S nAGM  S nAff = f)
Nz Sending batch ingest request to  with context: r  z/runs/batchr  r   )r  r  r  r  r  zFailed to batch ingest runs: )r   r   r   r   r  r  r  r;   r  r   	tracebackformat_exception_onlyr  r  r   rt  ru  r  )r   r   r  r   r   	endpointsr  r  r   exc_desc_linesexc_descs              r?   r  Client._post_batch_ingest_runs  sH    7#6 *I,,I.7oo.?*N76~6FoV^U_` ))%&k2 $$"mm$%~$$  (>>@'(% *  /@&  7N%.%D%DT!Wa%PN!ww~6==?HNN%B8*#MN  NNN%B47)#LMN33A667s7   AB


D;AC-,D6-+DD6DD66D;c                  / n0 nU H  n[        U[        5      (       a2  [        U5      u  nnUR                  U5        UR	                  U5        MJ  [        U[
        5      (       a  UR                  [        U5      5        M{  [        R                  S[        U5      5        M     [        U5      n	U	(       a4   U R                  XUS9  [!        [#        UR%                  5       5      5        g g ! [        R                   aQ    SU l        U Vs/ s H  n[        U[        5      (       d  M  UPM     Os  snf n
nU
(       a  U R                  U
5         Nf = f! [!        [#        UR%                  5       5      5        f = f)Nz+Unknown operation type in tracing queue: %sr   T)rq   r,   r2   rx  r  r+   r1   r   r  r  r*   _send_multipart_reqr;   r  r0  r  r  r  r  )r   r  r   r   partsopened_files_dictr  partr  acc_multipartrun_opss              r?   _multipart_ingest_opsClient._multipart_ingest_ops1  sH    13:<B"455 LBO T"!((6B ;<<PQST JDQSHU  9??((!G )  T"3":":"<=> 
 22 8 ,0((+V"z">T/U2VV..w78 T"3":":"<=>s6   8C, ,ED/(D/. EE EE $E8)r  r  c          	        U(       d  U(       d  gU=(       d    [          Vs/ s H  oPR                  U5      PM     nnU=(       d    [          Vs/ s H  oPR                  USS9PM     nnU(       aL  U HE  nUR                  S5      (       a  UR                  S5      (       a  M1  [        R                  " S5      e   AU(       aL  U HE  nUR                  S5      (       a  UR                  S5      (       a  M1  [        R                  " S5      e   AU(       an  U(       ag  U Vs0 s H  oUS   U_M
     nn/ n	U HG  nUS   U;   a*  UR                  5        H  u  pUc  M
  XUS      U
'   M     M6  U	R                  U5        MI     AU	nU(       d!  U R                  U5      nU R                  USS	9nU(       d  U(       d  gU R                  U5        U R                  U5        [        [        [        R                  " S
 U 5       S U 5       5      5      5      nU H  n[        U[        5      (       d  M  UR                  (       d  M-  UR                  R!                  5        HF  n[        U["        5      (       d  M  [        US   [$        5      (       d  M4  U(       a  M=  ['        S5      e   M     U R)                  U5        gs  snf s  snf s  snf )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, default=False): Whether the runs have already been subject
        to sampling, and therefore should not be sampled again.

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.

Example:
    ```python
    from langsmith import Client
    import datetime
    from uuid import uuid4

    client = Client()
    _session = "__test_batch_ingest_runs"
    trace_id = uuid4()
    trace_id_2 = uuid4()
    run_id_2 = uuid4()
    current_time = datetime.datetime.now(datetime.timezone.utc).strftime(
        "%Y%m%dT%H%M%S%fZ"
    )
    later_time = (
        datetime.datetime.now(datetime.timezone.utc) + timedelta(seconds=1)
    ).strftime("%Y%m%dT%H%M%S%fZ")

    runs_to_create = [
        {
            "id": str(trace_id),
            "session_name": _session,
            "name": "run 1",
            "run_type": "chain",
            "dotted_order": f"{current_time}{str(trace_id)}",
            "trace_id": str(trace_id),
            "inputs": {"input1": 1, "input2": 2},
            "outputs": {"output1": 3, "output2": 4},
        },
        {
            "id": str(trace_id_2),
            "session_name": _session,
            "name": "run 3",
            "run_type": "chain",
            "dotted_order": f"{current_time}{str(trace_id_2)}",
            "trace_id": str(trace_id_2),
            "inputs": {"input1": 1, "input2": 2},
            "error": "error",
        },
        {
            "id": str(run_id_2),
            "session_name": _session,
            "name": "run 2",
            "run_type": "chain",
            "dotted_order": f"{current_time}{str(trace_id)}."
            f"{later_time}{str(run_id_2)}",
            "trace_id": str(trace_id),
            "parent_run_id": str(trace_id),
            "inputs": {"input1": 5, "input2": 6},
        },
    ]
    runs_to_update = [
        {
            "id": str(run_id_2),
            "dotted_order": f"{current_time}{str(trace_id)}."
            f"{later_time}{str(run_id_2)}",
            "trace_id": str(trace_id),
            "parent_run_id": str(trace_id),
            "outputs": {"output1": 4, "output2": 5},
        },
    ]

    client.multipart_ingest(create=runs_to_create, update=runs_to_update)
    ```
NT)r  rw  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.r<  rt  c              3  :   #    U  H  n[        S U5      v   M     g7fr  r  r  s     r?   r  *Client.multipart_ingest.<locals>.<genexpr>  s     M'44r  c              3  :   #    U  H  n[        S U5      v   M     g7fr  r  r  s     r?   r  r	    s     N#'55r  r   r  )rk   rb  r  r;   r|   r   rx  r|  ro  r-   r  r  r   rq   r,   r  r  r   r
   ru   r  )r   r  r  r  r  r`  r  r  create_by_idstandalone_updatesrm  rn  r  r  r  s                  r?   multipart_ingestClient.multipart_ingestY  s   B &<B<Oi<OP<OS++C0<OP=C=Py=P
=PcD1=P 	 
 #wwz**#''.2I2I"556  $ #wwz**#''.2I2I"556  $ L6BClsIsNlLC-/#t9, #		=9:T3A6 !, '--c2 $ -L44\BL44\4NLL  .  . =MMNN
 !B"455"..."$.."7"7"9J":u55&z!}d;; < <(s  #: ! 	"">2M Q
0 Ds   J=K!Kr   )attemptsr   r   c               ^   UR                   nUR                  nUb  Ub  X40nOU R                  nUR                  5        H  u  p[	        SUS-   5       H  n
 [
        R                  " U[        S9nUR                  S::  a  UR                  5       nOUn[        R                  SU SU 35        U R                  SU S3U0 U R                  E[        U	SUR                  0ES	.SUS
9    M     M     g ! [         R"                   a       M  [         R$                  [         R&                  [         R(                  4 aA  nX:X  a0  [        R+                  SU 35        U R-                  U5         S nAGM   S nAGM$  S nAf[.         a  n [0        R2                  " [5        U5      U5      nSR7                  U5      R9                  5       n[        R+                  SU 35        O1! [.         a$    [        R+                  S[;        U5       35         Of = fU R-                  U5         S nA  GM  S nAff = f)Nr   boundary -1zSending multipart request to r  r  /runs/multipartr  r  r  r  r  z!Failed to multipart ingest runs: r  )r   r  r   r   r  rqtb_multipartMultipartEncoderr&   rz   	to_stringr   r   r  r  r  content_typer;   r  r  r  r  rt  r  r   r  r  r  r  r   ru  )r   accr  r   r   r   r  r  r  r  r  encoderr  excr   r  r  s                    r?   r  Client._send_multipart_req	  s    		;; 7#63:2DI,,I.7oo.?*NQ1--,==eiXG{{j0&002&LL77GW_V`a --)*/:$(("&--( )> .0D0D(( ,-!) .  1 . /@4  66 5544.. 	!
 )J3%'PQ;;C@@   	V)2)H)HaRS)T#%77>#:#A#A#C)J8*'UV$ V)J4PQ7)'TUV77:	sJ   BC11H,	2H,;.E77H,AGH'+H	H'
H	H''H,r  c               @   SR                  [        US/ 5      5      nU R                  R                  5        H  u  pVUR	                  S5        [        SUS-   5       H}  n 0 U R                  EUS[         3SU(       a  [        US   5      OSU(       a  [        US   5      OSS.En[        R                  S	U 35        U R                  S
U S3UUS.SUS9    M     M     g! [        R                   a       M  [        R                  [        R                  [        R                   4 aA  n	Xs:X  a0  [        R#                  SU	 35        U R%                  U	5         Sn	A	GM   Sn	A	GM  Sn	A	f[&         a  n
 [(        R*                  " [-        U
5      U
5      nSR                  U5      R/                  5       n[        R#                  SU 35        O1! [&         a$    [        R#                  S[1        U
5       35         Of = fU R%                  U
5         Sn
A
  GM  Sn
A
ff = f)zASend a zstd-compressed multipart form data stream to the backend.r  r  r   r   zmultipart/form-data; boundary=zstdr  )z	X-API-KEYr  zContent-EncodingzX-Pre-Compressed-SizezX-Post-Compressed-Sizez3Sending compressed multipart request with context: r  r  r  r  z,Failed to send compressed multipart ingest: N)r  rV  r   r   r5  r  r  r&   rt   r   r   r  r;   r  r  r  r  rt  r  r   r  r  r  r   ru  )r   data_streamcompressed_traces_infor  r  r   r   r  rC  r  r   r  r  s                r?   _send_compressed_multipart_req%Client._send_compressed_multipart_reqG	  s    		'+y""EF $ 4 4 : : <GQQ1-:--%,*H(T,2  6   6q 9:!#  6   6q 9:!#G  LLMhZX --")?3$/'.( ,-!) . 	 ? . !=F  66 5544.. !
 J3%P ;;C@@   	)2)H)HaRS)T#%77>#:#A#A#CJ8*U % J4PQ7)T 77:sJ    A8C""H:2H,.E((H6AGH+G<	9H;G<	<HH)r1  rS  rQ  end_timer  rN  rO  r  rP  tagsr  r  reference_example_idr   r   c                  [        US5      UUUR                  SS5      UR                  SS5      UR                  SS5      UU
UR                  SS5      UR                  SS5      S.
nUb  UR                  5       US	'   U(       ab  UR                  5        HI  u  nn[	        U[
        5      (       d  M  [	        US
   [        5      (       d  M7  U(       a  M@  [        S5      e   UUS'   U R                  SL=(       d    U R                  SL=(       a    US   SL=(       a    US   SLnU R                  U/SS9(       d  gUb  UR                  5       US'   OH[        R                  R                  [        R                  R                  5      R                  5       US'   Ub  UUS'   Ub  U R                  U5      US'   Ub1  U(       d  [         R"                  " U5      nU R%                  U5      US'   U	b  U	US'   US   (       aD  U R'                  U/5        US   R)                  S5      =n(       a  U R+                  U5      US   S'   Ub  UUS'   U R,                  (       ao  UR)                  S5      (       dY  U R.                     U R0                  R3                  SU45        U R5                  5       (       a  U R7                  5          SSS5        gU R9                  UUUS9  g! , (       d  f       g= f)a5  Update a run in the LangSmith API.

Args:
    run_id (Union[UUID, str]): The ID of the run to update.
    name (Optional[str]): The name of the run.
    run_type (Optional[str]): The type of the run (e.g., llm, chain, tool).
    start_time (Optional[datetime.datetime]): The start time of the run.
    end_time (Optional[datetime.datetime]): The end time of the run.
    error (Optional[str]): The error message of the run.
    inputs (Optional[Dict]): The input values for the run.
    outputs (Optional[Dict]): The output values for the run.
    events (Optional[Sequence[dict]]): The events for the run.
    extra (Optional[Dict]): The extra information for the run.
    tags (Optional[List[str]]): The tags for the run.
    attachments (Optional[Dict[str, Attachment]]): 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.
    reference_example_id (Optional[Union[str, uuid.UUID]]): ID of the example
        that was the source of the run inputs. Used for runs that were part of
        an experiment.
    api_key (Optional[str]): The API key to use for this specific run.
    api_url (Optional[str]): The API URL to use for this specific run.
    **kwargs (Any): Kwargs are ignored.

Returns:
    None

Examples:
    ```python
    from langsmith import Client
    import datetime
    from uuid import uuid4

    client = Client()
    project_name = "__test_update_run"

    start_time = datetime.datetime.now()
    revision_id = uuid4()
    run: dict = dict(
        id=uuid4(),
        name="test_run",
        run_type="llm",
        inputs={"text": "hello world"},
        project_name=project_name,
        api_url=os.getenv("LANGCHAIN_ENDPOINT"),
        start_time=start_time,
        extra={"extra": "extra"},
        revision_id=revision_id,
    )
    # Create the run
    client.create_run(**run)
    run["outputs"] = {"output": ["Hi"]}
    run["extra"]["foo"] = "bar"
    run["name"] = "test_run_updated"
    # Update the run
    client.update_run(run["id"], **run)
    ```
run_idrw  Nparent_run_idr  
session_idr  )
r<  r1  rS  rw  r*  r  r&  rP  r+  r  rQ  r   r  r  Trt  r%  r  rN  rO  r  rP  r   r'  r  ru  r  )r{   r_  	isoformatr   rq   r   r
   ru   r  r&  r|  r[  r\  r]  r^  rX  r;   rW  rY  ro  r  rZ  r  r*  r)  rx  r  r  _update_run)r   r)  r1  rS  rQ  r%  r  rN  rO  r  rP  r&  r  r  r'  r   r   r  r  _r  use_multipartr   s                          r?   
update_runClient.update_run	  s   ^ 68, 

:t4#ZZ>"JJ~t< **\48"JJ~t< 
 !!+!5!5!7D!,!2!2!4:z511":a=$7788$o  "5 #.Dt+Qt/E/ET/Q 1Z ,1 ^$D0	 	 (($t(<'113D'0044X5F5F5J5JKUUWD!DM!226:DN "//8"44W=DO#DN=$$dV,=,,Z88x8,0,C,CH,MWj)++?D'( ))&**=V2W2W**$$++WdO<4466..0 +* T7GD +*s    AK
K-c                  U R                   S L=(       d    U R                  S L=(       a    US   S L=(       a    US   S LnU R                  b  U R                  R                  U5        g U(       Ga  [	        SUS9nU R                  b  Uc  Uc  [        U5      u  nn[        R                  SSUR                  5        U R                  R                     U R                  c  [        S5      e[        UU R                  [        5      nU(       a9  U R                  =R                  S-  sl        U R                  R                  5         S S S 5        [!        [#        UR%                  5       5      5        g U R                   b  [        R                  SS	UR&                  UR(                  5        U R*                  bQ  U R                   R-                  [/        US   UUUU R1                  U R2                  R5                  5       5      S
95        g U R                   R-                  [/        US   UUUS95        g g U R7                  XUS9  g ! , (       d  f       GN= f)Nrw  r  ru  )r  payloadr  r  r  r   r  r  r  )r  r&  r%  r0  r0   r2   r   r  r  r  r'  ru   r.   r&   r  rZ  r  r  r  rw  r<  r+  r  r    r-  r,  r  _update_run_non_batch)	r   
run_updater   r   r/  r  r  r  r  s	            r?   r-  Client._update_run 
  s<    t+Qt/E/ET/Q 7:&d27 >*$6	 	 (((4.*UM&&2OO
 L!"  

K"**
 ++00119(^   D&..! H
  ..::a?:22668 1 T,"5"5"789##/

E!**!$$	 %%1&&**(&~6)$+$+)-)B)B $ 0 0 A A C*
 &&**(&~6)$+$+	) 0: &&zG&TW 10s   A4I
Ic                  Uc  Ubf  U=(       d    U R                   nU=(       d    U R                  n0 U R                  E[        U0EnU R	                  SU SUS    3[        U5      US.S9  g U R                  R                  5        H@  u  px0 U R                  E[        U0EnU R	                  SU SUS    3[        U5      US.S9  MB     g )NPATCH/runs/r<  r  r$  )r   r   r  r  r  r'  r   r   )	r   r5  r   r   r  r  rC  r  r  s	            r?   r4  Client._update_run_non_batchn
  s     '"5$4N$4N-->G
 %%!"&D)9(:;'
3&  &  150D0D0J0J0L,mm}
 ))$oVJt,<+=> +J 7#*$ *  1Mr>   c                   U R                   c  gU R                  c  [        S5      eSSKJnJn  U" U SSS9u  nnUb:  Sn UR                  U R                  UUUS9nU R                  R                  U5        U R                  (       aI  [        U R                  5      n[        R                  " U5      u  pU R                  R                  U5        gg! [         a    U R                  XEUS9   Nwf = f)z3Force flush the currently buffered compressed runs.Nz>Run compression is enabled but request pool futures is not setr   )r  '_tracing_thread_drain_compressed_bufferr   )r  r  r  )r&  r(  ru   r  r  r<  r  r#  rz  r  r  cfwaitdifference_update)
r   r  r  r<  final_data_streamr"  r  futuresdoner.  s
             r?   flush_compressed_tracesClient.flush_compressed_traces
  s    !!)== P 
	
 4Q
	
"
 (F5<<77%*%	 =  !!&) ==4==)Gggg&GDMM++D1	    33% 4 s    7C C/.C/c                @   U R                   (       a6  U R                     U R                  (       a  U R                  5         SSS5        U R                  b  U R                  5         gU R                  b  U R                  R                  5         gg! , (       d  f       NU= f)z;Flush either queue or compressed buffer, depending on mode.N)r  r*  r)  r  r&  rC  r  r  r  s    r?   flushClient.flush
  sv     ))**''..0 + !!-((*+##% , +*s   "B
Bc                   U R                  SUR                  UR                  S9n[        R                  " [
        5      n0 n[        UR                  5      n[        US S9 H  nUR                  c$  [        R                  " SUR                   S35      eUR                  R                  S5       Vs1 s H   nSU;   d  M  UR                  SS	5      S	   iM"     nnXX;   d  M  UR                  UR                  :w  d  M  X6R                     R                  U5        XdUR                  '   M     UR                  UR                  / 5      Ul        UR#                  5        H  u  pXU	   l        M     U$ s  snf )
zLoad child runs for a given run.

Args:
    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.
F)is_rootr+  rw  c                    U R                   $ r   )r  )rs    r?   <lambda>)Client._load_child_runs.<locals>.<lambda>
  s    !..r>   )r  z
Child run z has no parentr   Zr   )	list_runsr+  rw  r  r  r  rt   r<  sortedr*  r;   r  r  ry   rx  r_  
child_runsr   )r   r`  rQ  treemapr  
run_id_str	child_runsegancestor_idsr)  childrens              r?   _load_child_runsClient._load_child_runs
  sU    ^^cnns|| $ 

 ##D) 	 13[
(
I &&.--
9<<..WXX
 %1177<<C#: %		#q!!$<  
 )illcff.D//077	B%.Y\\"
  !SVVR0 'F&.L# !0
s   3
E3E3c                "   U R                  SS[        US5       35      n[        UR                  5       SU R                  S9n[
        R                  " SSU0UR                  5       DSU R                  0D6nU(       a  U R                  U5      nU$ )	a  Read a run from the LangSmith API.

Args:
    run_id (Union[UUID, str]):
        The ID of the run to read.
    load_child_runs (bool, default=False):
        Whether to load nested child runs.

Returns:
    Run: The run read from the LangSmith API.

Examples:
    ```python
    from langsmith import Client

    # Existing run
    run_id = "your-run-id"

    client = Client()
    stored_run = client.read_run(run_id)
    ```
r  r9  r)  s3_urlsattachments_keyr   r  r  r=   )	r  r{   /_convert_stored_attachments_to_attachments_dictr  r   rb  Runr  rX  )r   r)  load_child_runsr  r  r`  s         r?   read_runClient.read_run
  s    2 ,,VHVX678
 FMMOY
 nn 
#
'/}}
BF..
 '',C
r>   )
project_idr~  rS  rw  r'  queryfiltertrace_filtertree_filterrI  r*  rQ  r  run_idsselectr  c             +    #    / n[        U[        R                  [        45      (       a  UR	                  U5        O&[        U[
        5      (       a  UR                  U5        UbQ  [        U[        5      (       a  U/nUR                  U Vs/ s H  nU R                  US9R                  PM     sn5        / SQnU=(       d    UnSU;   a  [        R                  " S[        5        U(       a  UOSUU(       a  U/OSUUUU	U
UU(       a  UR                  5       OSUUUUUS.UEnUR                  5        VVs0 s H  u  nnUc  M  UU_M     nnn[        U R                  SUS95       HS  u  nn[!        US	U R"                  S
9n[$        R&                  " SSU0UDSU R(                  0D6v   Uc  MH  US-   U:  d  MS    g   gs  snf s  snnf 7f)aq  List runs from the LangSmith API.

Args:
    project_id (Optional[Union[UUID, str], Sequence[Union[UUID, str]]]):
        The ID(s) of the project to filter by.
    project_name (Optional[Union[str, Sequence[str]]]): The name(s) of the project to filter by.
    run_type (Optional[str]): The type of the runs to filter by.
    trace_id (Optional[Union[UUID, str]]): The ID of the trace to filter by.
    reference_example_id (Optional[Union[UUID, str]]): The ID of the reference example to filter by.
    query (Optional[str]): The query string to filter by.
    filter (Optional[str]): The filter string to filter by.
    trace_filter (Optional[str]): 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 (Optional[str]): 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 (Optional[bool]): Whether to filter by root runs.
    parent_run_id (Optional[Union[UUID, str]]):
        The ID of the parent run to filter by.
    start_time (Optional[datetime.datetime]):
        The start time to filter by.
    error (Optional[bool]): Whether to filter by error status.
    run_ids (Optional[Sequence[Union[UUID, str]]]):
        The IDs of the runs to filter by.
    select (Optional[Sequence[str]]): The fields to select.
    limit (Optional[int]): The maximum number of runs to return.
    **kwargs (Any): Additional keyword arguments.

Yields:
    The runs.

Examples:
    ```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))',
    )
    ```
Nr~  )app_pathcompletion_costcompletion_tokensr  r%  r  r  rP  feedback_statsfirst_token_timer<  rN  r1  rO  r*  parent_run_idsprompt_costprompt_tokensr'  rS  r+  rQ  statusr&  
total_costtotal_tokensrw  child_run_idszOThe child_run_ids field is deprecated and will be removed in following versions)r   rS  reference_examplerd  re  rf  rg  rI  
parent_runrQ  r  r<  rC   ri  r  /runs/queryr   r[  r\  r  r  r   r=   )rq   rr   rs   rt   rx  r  extendread_projectr<  r   r   DeprecationWarningr,  r   	enumerater)  r^  r   rb  r_  r  )r   rc  r~  rS  rw  r'  rd  re  rf  rg  rI  r*  rQ  r  rh  ri  r  r  project_idsr1  default_select
body_queryrm  rn  ir`  r  s                              r?   rO  Client.list_runs#  s    ^ j499c"233z*
D))z*#,,, ,~EQR\T"""588\R
< )>f$MMa" '2{t *>%&D(&'4>*..0D#&
$ %&

( (2'7'7'9K'9tq!Qdad'9
K++M
+K
FAs JYK .. '+.:>..   QUe^
{ Sx Ls2   B
G#G /BG7
GGA G0G;G)r<  rC   ry  rS  project_namesr  reference_example_idsrQ  r%  r  rd  re  rf  rg  rI  data_source_typec               P   SSK JnJn  U=(       d    / nU(       ar  U" 5        nU Vs/ s H  nUR                  U R                  US9PM     nnU" U5       H,  nUR                  UR                  5       R                  5        M.     SSS5        UUUUUUUU	U
UUUUUUS.nUR                  5        VVs0 s H  u  nnUc  M  UU_M     nnnU R                  SSS[        U5      0S	9n[        R                  " U5        UR                  5       $ s  snf ! , (       d  f       N= fs  snnf )
a	  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[Union[UUID, str]]]): List of run IDs to filter by.
    trace (Optional[Union[UUID, str]]): Trace ID to filter by.
    parent_run (Optional[Union[UUID, str]]): Parent run ID to filter by.
    run_type (Optional[str]): Run type to filter by.
    project_names (Optional[List[str]]): List of project names to filter by.
    project_ids (Optional[List[Union[UUID, str]]]): List of project IDs to filter by.
    reference_example_ids (Optional[List[Union[UUID, str]]]): 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_completedrk  N)r<  rC   ry  rS  r   rx  rQ  r%  r  rd  re  rf  rg  rI  r  r  z/runs/statsr  r$  )concurrent.futuresr  r  r  r}  rx  rJ  r<  r   r  r'  r;   r  r  )r   r<  rC   ry  rS  r  r  r  rQ  r%  r  rd  re  rf  rg  rI  r  r  r  executorr1  rA  r  r3  rm  rn  r  s                              r?   get_run_statsClient.get_run_stats  s;   \ 	H!'R#% !. - OOD$5$5DOI -   +73F&&v}}'9'9: 4 & $ "!6$ (& 0
& %,MMOEODAqq41a4OE,,G, - 
 	++H5}}G &%4 Fs(   D$D:D2
D" D"D
D)r~  rc  c                  [        USS5      =n(       a  O[        USS5      =n(       a  U R                  US9R                  nOQUb  UnOKUb  U R                  US9R                  nO.[        R                  " 5       nU R                  US9R                  n[        US5      nU R                   SU R                  5        SU SUR                   S3$ )	ak  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.

Args:
    run (RunBase): The run.
    project_name (Optional[str]): The name of the project.
    project_id (Optional[Union[UUID, str]]): The ID of the project.

Returns:
    str: The URL for the run.
r+  Nr  rk  z/o/z/projects/p/z/r/z
?poll=true)rV  r}  r<  r;   r  r{   r  _get_tenant_id)r   r`  r~  rc  r+  r  session_id_s          r?   get_run_urlClient.get_run_url=  s    * !lD99:9$S.$??\?***EHHJ##J%***EHHJ#668L***EHHJz<8~~c$"5"5"7!8[M R
$	
r>   )share_idc               6   [        US5      n[        U5      U=(       d    [        [        R                  " 5       5      S.nU R	                  SSU S3U R
                  US9n[        R                  " U5        UR                  5       S   nU R                   SU S	3$ )
a  Get a share link for a run.

Args:
    run_id (Union[UUID, str]): The ID of the run to share.
    share_id (Optional[Union[UUID, str]]): Custom share ID.
        If not provided, a random UUID will be generated.

Returns:
    str: The URL of the shared run.
r)  )r)  share_tokenPUTr9  /sharerC  r  r  /public//r)
r{   rt   rr   rD  r  r  r;   r  r  r  )r   r)  r  run_id_r  r  r  s          r?   	share_runClient.share_runc  s     68,'l#8s4::<'8
 ,,WIV$MM	 - 
 	++H5mmom4..!+b99r>   c                    U R                  SS[        US5       S3U R                  S9n[        R                  " U5        g)ztDelete share link for a run.

Args:
    run_id (Union[UUID, str]): The ID of the run to unshare.

Returns:
    None
DELETEr9  r)  r  rC  Nr  r{   r  r;   r  )r   r)  r  s      r?   unshare_runClient.unshare_run}  sG     ,,Xfh/07MM - 

 	++H5r>   c                    U R                  SS[        US5       S3U R                  S9n[        R                  " U5        UR                  5       nUb  SU;  a  gU R                   SUS    S	3$ )
zRetrieve the shared link for a specific run.

Args:
    run_id (Union[UUID, str]): The ID of the run.

Returns:
    Optional[str]: The shared link for the run, or None if the link is not
    available.
r  r9  r)  r  r  Nr  r  r  )r  r{   r  r;   r  r  r  )r   r)  r  rJ  s       r?   read_run_shared_linkClient.read_run_shared_link  s     ,,Xfh/07MM - 

 	++H5>]&8..!&*?)@CCr>   c                @    U R                  [        US5      5      nUSL$ )zGet share state for a run.

Args:
    run_id (Union[UUID, str]): The ID of the run.

Returns:
    bool: True if the run is shared, False otherwise.
r)  N)r  r{   )r   r)  r  s      r?   run_is_sharedClient.run_is_shared  s&     ((&()CD4r>   c                   [        USSS9u  p4SU S3nUb  US[        US5       3-  nU R                  SUU R                  S	9n[        R
                  " U5        [        R                  " S0 UR                  5       DS
U R                  0D6$ )a  Get shared runs.

Args:
    share_token (Union[UUID, str]): The share token or URL of the shared run.
    run_id (Optional[Union[UUID, str]]): The ID of the specific run to retrieve.
        If not provided, the full shared run will be returned.

Returns:
    Run: The shared run.
r  r`  r   r  /runrn   r)  r  r  r  r=   )
r   r{   r  r  r;   r  rb  r_  r  r  )r   r  r)  r.  r   rx   r  s          r?   read_shared_runClient.read_shared_run  s     ,K%H*T*a2344D,,MM - 

 	++H5~~JJ4>>JJr>   c              #     #    U(       a  SU0O0 n[        USSS9u  pEU R                  SU S3US9 H)  n[        R                  " S
0 UDSU R                  0D6v   M+     g	7f)zGet shared runs.

Args:
    share_token (Union[UUID, str]): The share token or URL of the shared run.
    run_ids (Optional[List[str]]): A list of run IDs to filter the results by.

Yields:
    A shared run.
r<  r  r`  r  r  rz  r{  r  Nr=   )r   r)  rb  r_  r  )r   r  rh  r   r.  r   r`  s          r?   list_shared_runsClient.list_shared_runs  si      #*gr+K%H22zl+.T 3 
C ..A3A$..AA
s   AAdataset_namec               t   Uc  Uc  [        S5      eUc  U R                  US9R                  nU R                  SS[	        US5       S3U R
                  S9n[        R                  " U5        UR                  5       n[        [        R                  0 UESU R                   S	[	        US
   S5       S30E5      $ )a  Retrieve the shared schema of a dataset.

Args:
    dataset_id (Optional[Union[UUID, str]]): 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.
/Either dataset_id or dataset_name must be givenr  r  
/datasets/
dataset_idr  r  r   r  r  zresponse.share_token/d)ru   read_datasetr<  r  r{   r  r;   r  r  r   rb  DatasetShareSchemar  )r   r  r  r  ds        r?   read_dataset_shared_schema!Client.read_dataset_shared_schema  s    ( ,"6NOO***EHHJ,,*l;<FCMM - 

 	++H5MMO))$..)Am,.DEFbJ
 	
r>   c          	     |   Uc  Uc  [        S5      eUc  U R                  US9R                  nS[        U5      0nU R	                  SS[        US5       S3U R                  US9n[        R                  " U5        UR                  5       n[        [        R                  0 UESU R                   S	US
    S30E5      $ )a  Get a share link for a dataset.

Args:
    dataset_id (Optional[Union[UUID, str]]): 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.
r  r  r  r  r  r  r  r   r  r  r  )ru   r  r<  rt   r  r{   r  r;   r  r  r   rb  r  r  )r   r  r  r  r  r  s         r?   share_datasetClient.share_dataset  s    ( ,"6NOO***EHHJ#j/
 ,,*l;<FCMM	 - 
 	++H5--/))IqI%DNN+8Am4D3ERHI
 	
r>   c                    U R                  SS[        US5       S3U R                  S9n[        R                  " U5        g)zDelete share link for a dataset.

Args:
    dataset_id (Union[UUID, str]): The ID of the dataset to unshare.

Returns:
    None
r  r  r  r  r  Nr  )r   r  r  s      r?   unshare_datasetClient.unshare_dataset*  sG     ,,*l;<FCMM - 

 	++H5r>   c                   [        XR                  5      u  p#U R                  SSU S3U R                  S9n[        R
                  " U5        [        R                  " S0 UR                  5       DU R                  SU S3S.D6$ )zGet shared datasets.

Args:
    share_token (Union[UUID, str]): The share token or URL of the shared dataset.

Returns:
    Dataset: The shared dataset.
r  r  	/datasetsr  r  )r  _public_pathr=   )
r   r   r  r  r;   r  rb  rF  r  r  )r   r  r.  r   r  s        r?   read_shared_datasetClient.read_shared_dataset:  s     ,KF,,zl),MM - 

 	++H5!! 
mmo
nn#K=3
 	
r>   )example_idsr  c          	   #  *  #    0 nUb  U Vs/ s H  n[        U5      PM     snUS'   [        U R                  S[        US5       S3US95       H;  u  pg[        R
                  " S	0 UDSU R                  0D6v   Uc  M0  US-   U:  d  M;    g   gs  snf 7f)
ab  Get shared examples.

Args:
    share_token (Union[UUID, str]): The share token or URL of the shared dataset.
    example_ids (Optional[List[UUID, str]], optional): The IDs of the examples to filter by.
    limit (Optional[int]): Maximum number of examples to return, by default None.

Returns:
    List[ls_schemas.Example]: The list of shared examples.
Nr<  r  r  	/examplesr  r  r   r=   )rt   r  r  r{   rb  Exampler  )r   r  r  r  r  r<  r  examples           r?   list_shared_examplesClient.list_shared_examplesS  s     " ".9:kCGk:F4L#$$8K?@	J % 
JA $$IwI$..II QUe^
 ;s   
BBAB>B	
B)r  r1  name_containsr  c             #     #    X#US.n[        US5      n[        U R                  SU S3US95       H;  u  p[        R                  " S	0 U	DSU R
                  0D6v   Uc  M0  US-   U:  d  M;    g   g7f)
a  List shared projects.

Args:
    dataset_share_token (str): The share token of the dataset.
    project_ids (Optional[List[Union[UUID, str]]]): List of project IDs to filter the results, by default None.
    name (Optional[str]): Name of the project to filter the results, by default None.
    name_contains (Optional[str]): Substring to search for in project names, by default None.
    limit (Optional[int]): Maximum number of projects to return, by default None.

Yields:
    The shared projects.
)r<  r1  r  dataset_share_tokenr  z/datasets/sessionsr  r  Nr   r=   )r{   r  r  rb  TracerSessionResultr  )
r   r  r  r1  r  r  r  r  r  projects
             r?   list_shared_projectsClient.list_shared_projectsq  s     * $MR24IJ#$$;-'9: % 
JA 00U7UdnnUU QUe^
s   AA1!A1,A1)r+  r   upsertproject_extrareference_dataset_idc                  U R                    S3nUnU(       a  0 U=(       d    0 ESU0EnUUU[        [        R                  " 5       5      S.n	0 n
U(       a  SU
S'   Ub  XiS'   U R	                  SU0 U R
                  ESS	0E[        U	5      S
9n[        R                  " U5        [        R                  " S0 UR                  5       DSU R                  0D6$ )a3  Create a project on the LangSmith API.

Args:
    project_name (str): The name of the project.
    project_extra (Optional[dict]): Additional project information.
    metadata (Optional[dict]): Additional metadata to associate with the project.
    description (Optional[str]): The description of the project.
    upsert (bool, default=False): Whether to update the project if it already exists.
    reference_dataset_id (Optional[Union[UUID, str]): The ID of the reference dataset to associate with the project.

Returns:
    TracerSession: The created project.
	/sessionsr   )r1  rP  r+  r<  Tr  r  r  r  r  rC  r  r  r=   )r   rt   rr   rD  r  r  r'  r;   r  rb  TracerSessionr  r  )r   r~  r+  r   r  r  r  endpointrP  r   r  r  s               r?   create_projectClient.create_project  s    . ll^9-;;j(;E &djjl#	 
 #F8++?'(,,It}}In6HIT"	 - 
 	++H5''T(--/TT^^TTr>   )r1  r+  r   r  r%  c                  U R                    S[        US5       3nUnU(       a  0 U=(       d    0 ESU0EnUUUU(       a  UR                  5       OSS.n	U R                  SU0 U R                  ESS0E[        U	5      S	9n
[        R                  " U
5        [        R                  " S0 U
R                  5       DS
U R                  0D6$ )a  Update a LangSmith project.

Args:
    project_id (Union[UUID, str]):
        The ID of the project to update.
    name (Optional[str]):
        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 (Optional[str]):
        The new description to give the project.
    metadata (Optional[dict]):
        Additional metadata to associate with the project.
    project_extra (Optional[dict]):
        Additional project information.
    end_time (Optional[datetime.datetime]):
        The time the project was completed.

Returns:
    TracerSession: The updated project.

/sessions/rc  r   N)r1  rP  r+  r%  r8  r  r  r  r  r=   )r   r{   r,  r  r  r'  r;   r  rb  r  r  r  )r   rc  r1  r+  r   r  r%  r  rP  r   r  s              r?   update_projectClient.update_project  s    < ll^:hz<.P-QR;;j(;E&08**,d	 
 ,,It}}In6HIT"	 - 
 	++H5''T(--/TT^^TTr>   c                   U R                   b  U R                   $  U R                  SSSS0S9nUR                  5       n[        U[        5      (       aS  [        U5      S:  aD  [        R                  " S0 US   DSU R                  0D6nUR                  U l         U R                   $ g ! [         a(  n[        R                  S[        U5      S	S
9   S nAg S nAff = f)Nr  r  r  r   r  r   r  z*Failed to get tenant ID from LangSmith: %sTr  r=   )r  r  r  rq   r  rz   rb  r  r  	tenant_idr   r   r   ru  )r   r  rJ  tracer_sessionr   s        r?   rG  Client._get_optional_tenant_id  s    ??&??"	00{GQ< 1 H ]]_F&$''CK!O!+!?!? "Qi"+/>>" #1":":&
 	  	LL<d1gPT   		s   B
B' '
C1CCc                X    U R                  5       nUc  [        R                  " S5      eU$ )NzNo tenant ID found)rG  r;   r  )r   r  s     r?   r  Client._get_tenant_id  s.    002	))*>??r>   )rc  r~  )rc  r~  include_statsc                  SnSS0nUb  US[        US5       3-  nOUb  X%S'   O[        S5      eX5S'   U R                  S	XES
9nUR                  5       n[	        U[
        5      (       aP  [        U5      S:X  a  [        R                  " SU S35      e[        R                  " S0 US   DSU R                  0D6$ [        R                  " S0 UR                  5       DSU R                  0D6$ )a  Read a project from the LangSmith API.

Args:
    project_id (Optional[str]):
        The ID of the project to read.
    project_name (Optional[str]): The name of the project to read.
        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  r   rn   rc  r1  'Must provide project_name or project_idr  r  r  r   zProject 
 not foundr  r=   )r{   ru   r  r  rq   r  rz   r;   r  rb  r  r  )r   rc  r~  r  rx   r  r  rJ  s           r?   r}  Client.read_project  s    * ")1!a\:;<<D%)6NFGG"/,,UD,Hfd##6{a55|nJ7  11XF1IXXX-- 
mmo
)-
 	
r>   rc  c               X     U R                  US9  g! [        R                   a     gf = f)zCheck if a project exists.

Args:
    project_name (str):
        The name of the project to check for.
    project_id (Optional[str]):
        The ID of the project to check for.

Returns:
    bool: Whether the project exists.
rk  FT)r}  r;   r  )r   r~  rc  s      r?   has_projectClient.has_project6  s7    	<8  .. 		    ))c               P  ^  [         R                  " S[        SS9  SSKJnJn  SSKnT R                  UUS/ SQS	9n/ n/ nU 4S
 jn	Sn
SnU" 5        n/ nU GHE  nSUR                  0UR                  R                  5        VVs0 s H  u  nnSU 3U_M     snnEUR                  =(       d    0 R                  5        VVs0 s H  u  nnSU 3U_M     snnEUR                  (       a'  UR                  UR                  -
  R                  5       OSUR                  UR                   S.EnUR"                  (       a  UR%                  UR"                  R                  5        VVs0 s H9  u  nnUS:X  a  UR'                  S5      (       a  M$  SU 3UR'                  S5      _M;     snn5        UR"                  R'                  S5      (       a*  UR"                  S   R'                  S5      =n(       a  UUS'   UR                  (       a  UR)                  UR                  5        O#[*        R-                  SUR                    S35        [/        U5      U
-  S:X  a2  XX-    =n(       a%  UR)                  UR1                  U	U5      5        X-  nUR)                  U5        GMH     XS (       a#  UR)                  UR1                  XUS 5      5        SSS5        UR2                  " U5      R5                  S5      nU" W5       VVs/ s H  nUR7                  5         H  nUPM     M     nnnU(       a2  UR2                  " U5      R5                  S5      nUR9                  USSS9nUR:                  " UR=                  SS95      $ s  snnf s  snnf s  snnf ! , (       d  f       N= fs  snnf )a,  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.

Feedback score values will be returned as an average across all runs for
the experiment. Non-numeric feedback scores will be omitted.

Args:
    project_id (Optional[Union[UUID, str]]): The ID of the project.
    project_name (Optional[str]): The name of the project.

Returns:
    pd.DataFrame: A dataframe containing the test results.
z%Function get_test_results is in beta.r  )
stacklevelr   r  NT)r<  r'  rN  rO  r  ro  rQ  r%  )rc  r~  rI  ri  c                   > TR                  U S9nU VVVs/ s HM  nSUR                  0UR                  =(       d    0 R                  5        VVs0 s H  u  p4SU 3U_M     snnEPMO     snnn$ s  snnf s  snnnf )N)r  
example_idz
reference.)list_examplesr<  rO  r   )batchexamplesr  rm  rn  r   s        r?   fetch_examples/Client.get_test_results.<locals>.fetch_examplesz  s    ))e)<H  (
  (G !'**8?8M27T7T7VW7VtqA3'*7VW  (  Xs   9A6A0"	A60A62   r  zinput.zoutputs.)execution_timer  r<  notecommentsz	feedback.avgnoteszRun z has no reference example ID.)
left_indexright_indexrecords)orient)r   r   UserWarningr  r  r  pandasrO  r'  rN  r   rO  r%  rQ  total_secondsr  r<  ro  r  r  rx  r   rt  rz   r  	DataFrame	set_indexrJ  mergejson_normalizeto_dict)r   rc  r~  r  r  pdr  resultsr  r  r  r&  r  rA  rK  rm  rn  rowr  r  	result_dfr  outputexample_outputs
example_dfs   `                        r?   get_test_resultsClient.get_test_resultsJ  sU   . 	3[Q	
 	H~~!%		  
 !	 
!XG !"8"83488>>3CD3C41as|Q3CD 78iio25L5L5NO5NTQ!~q(5NO :: all2AAC!WW$$ ##JJ )*(8(8(>(>(@(@1$%KAEE*4E :isOQUU5\9(@ ''++F33$%$4$4V$<$@$@$LLL'/G))&&q'='=>NNT!$$/L#MN{#j0A5 +V5H IIuIx~u'MN,s#E J 7#x~67?STUQ "R LL)33LA	!-g!6
!6vV]]_6F_F!6 	 
 o6@@NJ"((tQU(VI   !2!2)!2!DEE[ EO# "!T
sD   3NM?*NNBN$#NN$D(N $N"?N
Nc              #    #    SU	b  [        U	S5      OS0nUb  XS'   Ub  X+S'   Ub  X;S'   Ub  Ub  [        S5      eXKS'   O Ub  U R                  US	9R                  nXKS'   Ub  XkS
'   Ub  X{S'   Ub  XS'   U
b  [        R
                  " U
5      US'   [        U R                  SUS95       H;  u  p[        R                  " S0 UDSU R                  0D6v   U	c  M0  US-   U	:  d  M;    g   g7f)a  List projects from the LangSmith API.

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

Yields:
    The projects.

Raises:
    ValueError: If both reference_dataset_id and reference_dataset_name are given.
r  NrU  r<  r1  r  zGOnly one of reference_dataset_id or reference_dataset_name may be givenreference_datasetr  reference_freer  dataset_versionr   r  r  r  r   r=   )minru   r  r<  r  r  r  r  rb  r  r  )r   r  r1  r  r  reference_dataset_namer  r  r  r  r   r  r  r  s                 r?   list_projectsClient.list_projects  s@    P (9S_s"
 "&4L!6N$&3?#+%1 ;  +?&'#/#'#4#43 $5 $b ! +?&'%'5#$$&3?#&(7$%!%H!5F:#$$[$@
JA 00U7UdnnUU QUe^
s   CC+C+&C+c                   Ub#  [        U R                  US9R                  5      nOUc  [        S5      eU R	                  SS[        US5       3U R                  S9n[        R                  " U5        g)a  Delete a project from LangSmith.

Args:
    project_name (Optional[str]):
        The name of the project to delete.
    project_id (Optional[str]):
        The ID of the project to delete.

Returns:
    None

Raises:
    ValueError: If neither project_name or project_id is provided.
Nrk  r  r  r  rc  r  )	rt   r}  r<  ru   r  r{   r  r;   r  )r   r~  rc  r  s       r?   delete_projectClient.delete_project  s{    $ #T..L.ILLMJFGG,,*l;<=MM - 

 	++H5r>   )r+  r,  inputs_schemaoutputs_schematransformationsr   c               .   S[         R                  " 5       0U=(       d    0 EnUUR                  USS[         R                  " 5       0U=(       d    0 E0S.nUb  X(S'   Ub  XHS'   Ub  XXS'   U R                  SS0 U R                  ES	S
0E[
        R                  " U5      S9n	[        R                  " U	5        U	R                  5       n
U
R                  S5      =(       d    UU
S'   [        R                  " S0 U
DU R                  U R                  5       S.D6$ )a(  Create a dataset in the LangSmith API.

Args:
    dataset_name (str):
        The name of the dataset.
    description (Optional[str]):
        The description of the dataset.
    data_type (DataType, default=DataType.kv):
        The data type of the dataset.
    inputs_schema (Optional[Dict[str, Any]]):
        The schema definition for the inputs of the dataset.
    outputs_schema (Optional[Dict[str, Any]]):
        The schema definition for the outputs of the dataset.
    transformations (Optional[List[DatasetTransformation]]):
        A list of transformations to apply to the dataset.
    metadata (Optional[dict]):
        Additional metadata to associate with the dataset.

Returns:
    Dataset: The created dataset.

Raises:
    requests.HTTPError: If the request to create the dataset fails.
re  r   )r1  r,  r(  rP  r+  inputs_schema_definitionoutputs_schema_definitionr  r  r  r  r  rB  r=   )rf  rg  r   r  r  r   r  r;   r  r  r  rb  rF  r  rG  )r   r  r+  r,  r&  r'  r(  r   datasetr  json_responses              r?   create_datasetClient.create_dataset"  s.   F v==?THNPRT ".v==?~2	
#
 "%0M"$2?./%3A/0,,It}}In6HIw'	 - 
 	++H5 $1$5$5j$A$MXj!!! 

nn335
 	
r>   r  r  c               X     U R                  XS9  g! [        R                   a     gf = f)a  Check whether a dataset exists in your tenant.

Args:
    dataset_name (Optional[str]):
        The name of the dataset to check.
    dataset_id (Optional[Union[UUID, str]]):
        The ID of the dataset to check.

Returns:
    bool: Whether the dataset exists.
r0  TF)r  r;   r  )r   r  r  s      r?   has_datasetClient.has_datasetj  s3    "	<O.. 		r  c                  SnSS0nUb  US[        US5       3-  nOUb  XS'   O[        S5      eU R                  SUUS	9nUR                  5       n[	        U[
        5      (       a_  [        U5      S
:X  a  [        R                  " SU S35      e[        R                  " S0 US
   DU R                  U R                  5       S.D6$ [        R                  " S0 UDU R                  U R                  5       S.D6$ )zRead a dataset from the LangSmith API.

Args:
    dataset_name (Optional[str]):
        The name of the dataset to read.
    dataset_id (Optional[Union[UUID, str]]):
        The ID of the dataset to read.

Returns:
    Dataset: The dataset.
r  r  r   rn   r  r1  'Must provide dataset_name or dataset_idr  r  r   rA  r  rB  r=   )r{   ru   r  r  rq   r  rz   r;   r  rb  rF  r  rG  )r   r  r  rx   r  r  rJ  s          r?   r  Client.read_dataset  s   $ ")1!a\:;<<D%)6NFGG,, - 

 fd##6{a55|nJ7  %% )..779 
 !! 

nn335
 	
r>   c          
        Uc'  Uc  [        S5      eU R                  US9R                  n[        US5      nU R	                  SSU S3U R
                  [        U[        R                  5      (       a  UR                  5       OU[        U[        R                  5      (       a  UR                  5       OUS.S9n[        R                  " U5        [        R                  " S	0 UR                  5       D6$ )
a=  Get the difference between two versions of a dataset.

Args:
    dataset_id (Optional[Union[UUID, str]]):
        The ID of the dataset.
    dataset_name (Optional[str]):
        The name of the dataset.
    from_version (Union[str, datetime.datetime]):
        The starting version for the diff.
    to_version (Union[str, datetime.datetime]):
        The ending version for the diff.

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

Examples:
    ```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,
    )

    # 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,
    )
    ```
&Must provide either dataset name or IDr  r  r  r  z/versions/diff)from_version
to_versionrC  r  r=   )ru   r  r<  r{   r  r  rq   r[  r,  r;   r  rb  DatasetDiffInfor  )r   r  r  r9  r:  dsidr  s          r?   diff_dataset_versionsClient.diff_dataset_versions  s    X # !IJJ***EHHJ
L1,,n-MM ",0A0ABB !**,% "*h.?.?@@ ((*#	 - 
" 	++H5))<HMMO<<r>   c          	     J   SnUb  O(Ub  U R                  US9R                  nO[        S5      eU R                  SU S[	        US5       S35      nUR
                  R                  5       R                  S5       Vs/ s H  n[        R                  " U5      PM     nnU$ s  snf )	a  Download a dataset in OpenAI Jsonl format and load it as a list of dicts.

Args:
    dataset_id (Optional[Union[UUID, str]]):
        The ID of the dataset to download.
    dataset_name (Optional[str]):
        The name of the dataset to download.

Returns:
    list[dict]: The dataset loaded as a list of dicts.

Raises:
    ValueError: If neither dataset_id nor dataset_name is provided.
r  r  r5  r  rn   r  z
/openai_ftr  )
r  r<  ru   r  r{   textr   ry   r  r  )r   r  r  rx   r  liner,  s          r?   read_dataset_openai_finetuning%Client.read_dataset_openai_finetuning  s    ( !%***EHHJFGG,,fAhz<89D
 190C0C0E0K0KD0QR0Q4::d#0QR Ss   < B )dataset_idsr,  r  dataset_name_containsr   r  c             #  p  #    SUb  [        US5      OS0nUb  XS'   Ub  X'S'   Ub  X7S'   Ub  XGS'   Ub  [        R                  " U5      US'   [        U R	                  S	US
95       HJ  u  p[
        R                  " S0 U	DU R                  U R                  5       S.D6v   Uc  M?  US-   U:  d  MJ    g   g7f)a  List the datasets on the LangSmith API.

Args:
    dataset_ids (Optional[List[Union[UUID, str]]]):
        A list of dataset IDs to filter the results by.
    data_type (Optional[str]):
        The data type of the datasets to filter the results by.
    dataset_name (Optional[str]):
        The name of the dataset to filter the results by.
    dataset_name_contains (Optional[str]):
        A substring to search for in the dataset names.
    metadata (Optional[Dict[str, Any]]):
        A dictionary of metadata to filter the results by.
    limit (Optional[int]):
        The maximum number of datasets to return.

Yields:
    The datasets.
r  NrU  r<  r,  r1  r  r   r  r  rB  r   r=   )	r  r  r  r  r  rb  rF  r  rG  )
r   rE  r,  r  rF  r   r  r  r  r,  s
             r?   list_datasetsClient.list_datasets  s     < (9S_s"
 "&4L "+;#)6N ,&;?#!%H!5F:#$$[$@
JA $$ ..779 
  QUe^
s   B B6&B61B6)r  r  c                   Ub  U R                  US9R                  nUc  [        S5      eU R                  SS[	        US5       3U R
                  S9n[        R                  " U5        g)zDelete a dataset from the LangSmith API.

Args:
    dataset_id (Optional[Union[UUID, str]]):
        The ID of the dataset to delete.
    dataset_name (Optional[str]):
        The name of the dataset to delete.

Returns:
    None
Nr  r8  r  r  r  r  )r  r<  ru   r  r{   r  r;   r  )r   r  r  r  s       r?   delete_datasetClient.delete_datasetM  sv    $ #***EHHJEFF,,*l;<=MM - 

 	++H5r>   c                   Ub  U R                  US9R                  nUc  [        S5      eU R                  SS[	        US5       S3U R
                  UR                  5       US.S	9n[        R                  " U5        g)
ay  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.

Args:
    dataset_id (Optional[Union[UUID, str]]):
        The ID of the dataset to update.
    dataset_name (Optional[str]):
        The name 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.

Returns:
    None

Examples:
    ```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  r8  r  r  r  z/tagsas_oftagr  )	r  r<  ru   r  r{   r  r,  r;   r  r   r  r  rO  rP  r  s         r?   update_dataset_tagClient.update_dataset_tagj  s    Z #***EHHJEFF,,*l;<EBMM*	 - 
 	++H5r>   )r  r  searchr  c          	   #    #    Uc  U R                  US9R                  nUUb  [        US5      OSS.n[        U R	                  S[        US5       S3US95       H-  u  pg[        R                  " S
0 UD6v   Uc  M"  US	-   U:  d  M-    g   g7f)a3  List dataset versions.

Args:
    dataset_id (Optional[Union[UUID, str]]): 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.

Yields:
    The dataset versions.
Nr  rU  )rT  r  r  r  z	/versionsr  r   r=   )r  r<  r  r  r  r{   rb  DatasetVersion)r   r  r  rT  r  r  r  r   s           r?   list_dataset_versionsClient.list_dataset_versions  s     & ***EHHJ(-(9S_s
 $$$Xj,?@	J % 
JA ++6g66 QUe^
s   A6B<BB)r  r  rO  rP  c                  Uc  U R                  US9R                  nU(       a  U(       d  Uc  Uc  [        S5      eU R                  SS[	        US5       S3X4S.S9n[
        R                  " S	0 UR                  5       D6$ )
a  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:
    DatasetVersion: The dataset version.

Examples:
    ```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")
    ```
r  z/Exactly one of as_of and tag must be specified.r  r  r  z/versionrN  r  r=   )r  r<  ru   r  r{   rb  rV  r  rQ  s         r?   read_dataset_versionClient.read_dataset_version  s    L ***EHHJcu}NOO,,*l;<HE"/ - 

 ((;8==?;;r>   )source_api_urlr  c          	     \   U=(       d    U R                   n[        X5      u  p$[        USS9nUR                  U5      nU=(       d    UR                  n U R                  US9n[        R                  SU S35        U$ ! [        R                   a     Of = f [        UR                  U5      5      nU R                  UUR                  UR                  =(       d    [        R                   R"                  UR$                  UR&                  UR(                  S9n U R+                  U V	s/ s H  oR,                  PM     Os  sn	f sn	U V	s/ s H  oR.                  PM     Os  sn	f sn	UR0                  S9  O-! [2         a   n	[        R5                  SU S	35        U	eS
n	A	ff = f AU$ ! Af = f)a8  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 (Optional[str]): The URL of the langsmith server where the data is hosted.
        Defaults to the API URL of your current client.
    dataset_name (Optional[str]): The name of the dataset to create in your tenant.
        Defaults to the name of the public dataset.

Returns:
    Dataset: The cloned dataset.
placeholderr   r  rA  z) already exists in your tenant. Skipping.)r  r+  r,  r&  r'  r(  )rN  rO  r  z)An error occurred while creating dataset z . You should delete it manually.N)r   r   r
  r  r1  r  r   r=  r;   r  r  r  r.  r+  r,  rb  DataTypekvr&  r'  r(  create_examplesrN  rO  r<  r  r  )
r   token_or_urlr\  r  r   source_clientdsr  r,  r   s
             r?   clone_public_datasetClient.clone_public_dataset  s   , (74<<%8%V" #!
 ..z:#.rww	"""=BKK<.(QR I.. 			M>>zJKH)))NN,,@**=*=*@*@ ..!00 " 2 2 * G$$.67hHHh70891YY9&zz % 
 ! 
 ?~ N5 5 
"  s[   )A> >BBBF( E7 *E ?E7 E!
 E7 6F( 7
F!FF!!F( (F+c                8    U R                  US9nUR                  $ )N)r  )r  r,  )r   r  r,  s      r?   rq  Client._get_data_typeD  s!    ##z#:   r>   c                0    U R                  SU0SU0UUUS9$ )a  Add an example (row) to an LLM-type dataset.

Args:
    prompt (str):
        The input prompt for the example.
    generation (Optional[str]):
        The output generation for the example.
    dataset_id (Optional[Union[UUID, str]]):
        The ID of the dataset.
    dataset_name (Optional[str]):
        The name of the dataset.
    created_at (Optional[datetime.datetime]):
        The creation timestamp of the example.

Returns:
    Example: The created example
inputr  rN  rO  r  r  
created_at)create_example)r   r   
generationr  r  rl  s         r?   create_llm_exampleClient.create_llm_exampleH  s5    4 ""V$z*!%! # 
 	
r>   c           	         / nU H|  n[         R                  " U5      (       a?  UR                  [         R                  " [	        [
        R                  U5      5      5        M]  UR                  [	        [        U5      5        M~     SnUbZ  [         R                  " U5      (       a/  [         R                  " [	        [
        R                  U5      5      nO[	        [        U5      nU R                  SU0Ub  SU0OSUUUS9$ )a+  Add an example (row) to a Chat-type dataset.

Args:
    messages (List[Union[Mapping[str, Any], BaseMessageLike]]):
        The input messages for the example.
    generations (Optional[Union[Mapping[str, Any], BaseMessageLike]]):
        The output messages for the example.
    dataset_id (Optional[Union[UUID, str]]):
        The ID of the dataset.
    dataset_name (Optional[str]):
        The name of the dataset.
    created_at (Optional[datetime.datetime]):
        The creation timestamp of the example.

Returns:
    Example: The created example
Nrj  r  rk  )	r;   is_base_message_likerx  convert_langchain_messager   rb  BaseMessageLiker   rm  )	r   messagesgenerationsr  r  rl  final_inputmessagefinal_generationss	            r?   create_chat_exampleClient.create_chat_examplej  s    8 G,,W55""66Z77A ""4g#67   !",,[99$,$F$F33[A%! %){$;!""[)1B1N,-TX!%! # 
 	
r>   c                <   Uc  U R                  US9R                  nSnU R                  U5      nU[        R                  R
                  :X  a  UR                  S:w  a  [        SUR                   S35      e [        R                  " UR                  5      nSU0nUR                  (       d  SnGO [        R                  " UR                  5      n	SU	0nOU[        R                  R                  :X  a  UR                  S:w  a  [        SUR                   S35      e S[        R                  " UR                  5      0nUR                  (       d  SnOj S[        R                  " UR                  5      0nOFU[        R                  R                   :X  a  UR                  nUR                  nO[        SU S35      eU R#                  UUUUUS9$ ! [         a&    [        SUR                   SUR                   35      ef = f! [         a&    [        S	UR                   S
UR                   35      ef = f! [         a&    [        SUR                   SUR                   35      ef = f! [         a&    [        SUR                   S
UR                   35      ef = f)af  Add an example (row) to a dataset from a run.

Args:
    run (Run): The run to create an example from.
    dataset_id (Optional[Union[UUID, str]]): The ID of the dataset.
    dataset_name (Optional[str]): The name of the dataset.
    created_at (Optional[datetime.datetime]): The creation timestamp of the example.

Returns:
    Example: The created example
Nr  r   z	Run type z+ is not supported for dataset of type 'LLM'z2Error converting LLM run inputs to prompt for run z with inputs rj  z7Error converting LLM run outputs to generation for run z with outputs r  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.rk  )r  r<  r  rb  r_  r   rS  ru   r;   get_prompt_from_inputsrN  rO  get_llm_generation_from_outputschatget_messages_from_inputs#get_message_generation_from_outputsr`  rm  )
r   r`  r  r  rl  dataset_typer   rN  rO  rn  s
             r?   create_example_from_runClient.create_example_from_run  s   $ ***EHHJL11*=:..222||u$ ~ .1 1 !88D '.v%6F;;48!)!I!I#++!VJ $Z0Z00555||u$ ~ .2 2 !8#D#DSZZ#PQ ;;
 ("N"NKK#G Z00333ZZFkkG }\N:JKLL""!%! # 
 	
g   x}SZZL:  " $FF8>#++@    x}SZZL:  " $$$'FF8>#++H s0   8 G 2 H "H8 "I+ 0H0H580I(+0Jc                   / n0 nU(       a<  [        US   [        R                  5      (       d  [        S5      eUS   R                  nU GH  n[        U[        R
                  5      (       dI  [        U[        R                  5      (       d*  [        U[        R                  5      (       d  [        S5      eUR                  b  [        UR                  5      nO[        [        R                  " 5       5      n[        U[        R                  5      (       a  S n	OUR                  n	[        U[        R
                  5      (       a%  UR                  n
UR                  nUR                  nOSu  pn0 U(       a  SW0O0 EU	b  SU	0O0 EU
(       a  SU
0O0 EU(       a  SU0O0 EU(       a  S	U0O0 EnUR                  b  UR                  US
'   UR                   b  UR                   US'   [#        U5      nUR%                  U S US0 445        UR&                  b/  [#        UR&                  5      nUR%                  U S3S US0 445        UR(                  b/  [#        UR(                  5      nUR%                  U S3S US0 445        UR*                  (       Ga  UR*                  R-                  5        H  u  nn[        U[.        5      (       a  US   nUS   nOUu  nn[        U[0        5      (       a  U(       a|   [2        R4                  R7                  U5      n[9        US5      nUU[        U5      [        [        R                  " 5       5      -   '   UR%                  U SU 3S UU SU 30 445        M  [        S5      eUR%                  U SU 3S UU S[A        U5       30 445        M     [        U[        R                  5      (       d  GM  URB                  (       d  GM  [#        URB                  5      nUR%                  U S3S US0 445        GM     [D        RF                  " U[H        S9nUR@                  S::  a  URK                  5       nOUnUUU4$ ! [:         a    [<        R?                  SUU5         GM  f = f)Nr   zWThe examples must be of type ExampleUpsertWithAttachments if include_dataset_id is Truez[The examples must be of type ExampleCreate or ExampleUpsertWithAttachments or ExampleUpdateNNNr  rl  use_source_run_iouse_source_run_attachmentssource_run_idr   ry   r  z.inputsz.outputs	mime_typer  r=  z,Attachment file not found for example %s: %sz.attachment.z	; length=zMdangerously_allow_filesystem must be True to upload files from the filesystemz.attachments_operationsr  r  )&rq   rb  ExampleUpsertWithAttachmentsru   r  ExampleCreateExampleUpdater<  rt   rr   rD  rl  r  r  r  r   ry   r'  rx  rN  rO  r  r   r   r
   rX  rx   getsizerE  FileNotFoundErrorr   rt  rz   attachments_operationsr  r  r&   r  )r   r  include_dataset_idr  r   r  r  r  r  rl  r  r  r  example_bodyvalbinputsboutputsbr1  r  r  attachment_data	file_sizer>  attachments_operationsbr  r  s                             r?   _prepare_multipart_dataClient._prepare_multipart_data  s    &(:<hqk:+R+RSS 5  "!//JGw
(@(@AA"7J,S,STT"7J,D,DEE ( 
 zz% _
 .
':#;#;<<!
$//
':#;#;<<$+$=$=!-4-O-O* ' 5 5PL!}1CL*-1;1GL*-R
 ) )*;< 2 23MN 8EO]3"L ++2+;+;Z(}}((/W%|,DLL!l*	
 ~~)%gnn5%,g. #.	
 *&w7%,h/ $.	
 """(/(;(;(A(A(C$D*!*d33$.{$;	*4V*<5?2	?!/4887	),.GGOOO,L	'+OT'B !% . #O 4s4::<7H H "LL'1l,tf$E(,(,+4+Yyk(J(*	%&!"
 #- o#  #-,l4& A$($3'0k3;O:P$Q$&	!"
M )Df 7J$<$<==222*5g6T6T*U'%,&=> 3.	
k  B !11%)L;;*$$$&DD///} $5 ) &$R$.$3!"
 !))s   4+Q!Q98Q9)updatesr  c               $    U R                  UUUS9$ )z{Update examples using multipart.

.. deprecated:: 0.3.9

    Use Client.update_examples instead. Will be removed in 0.4.0.
r  r  r  )_update_examples_multipart)r   r  r  r  s       r?   update_examples_multipart Client.update_examples_multipart  %     ..!)E / 
 	
r>   c                  U R                   R                  =(       d    0 R                  SS5      (       d  [        S5      eUc  / nU R	                  USUS9u  pEn U R                  S[        U R                  U5      U0 U R                  ESUR                  0ES.S9n[        R                  " U5        [        [        UR                  5       5      5        UR                  5       $ ! [        [        UR                  5       5      5        f = f)	a  Update examples using multipart.

Args:
    dataset_id (Union[UUID, str]): The ID of the dataset to update.
    updates (Optional[List[ExampleUpdate]]): The updates to apply to the examples.

Raises:
    ValueError: If the multipart examples endpoint is not enabled.
"dataset_examples_multipart_enabledFzYour LangSmith deployment does not allow using the latest examples endpoints, please upgrade your deployment to the latest version or downgrade your SDK to langsmith<0.3.9.r  r  r8  r  r  r$  r=  instance_flagsr  ru   r  r  _dataset_examples_pathr   r  r  r;   r  r  r  r  r  )r   r  r  r  r  r  r  r  s           r?   r  !Client._update_examples_multipart  s     		((.B330%
 
 & 
 ?G+/+G+G$)E ,H ,
((	;00&t||Z@  -- &(<(<   1 
H //9/6689:}} /6689:   AC$ $$D)uploadsr  c               $    U R                  UUUS9$ )z{Upload examples using multipart.

.. deprecated:: 0.3.9

    Use Client.create_examples instead. Will be removed in 0.4.0.
r  r  r  )_upload_examples_multipart)r   r  r  r  s       r?   upload_examples_multipart Client.upload_examples_multipart  r  r>   c                   SnUR                   (       a!  U[        [        UR                   5      5      -  nUR                  (       a!  U[        [        UR                  5      5      -  nUR                  (       a!  U[        [        UR                  5      5      -  nUR
                  (       a  UR
                  R                  5        Hp  u  p4[        U[        5      (       a  US   nOUu  p5[        U[        5      (       a$   U[        R                  R                  U5      -  nOU[        U5      -  nUS-  nMr     U$ ! [        [        4 a    US-  n N"f = f)z?Estimate the size of an example in bytes for batching purposes.rI  r  rT     )rN  rz   r'  rO  r   r  r   rq   r   r
   rX  rx   r  r  OSError)r   r  sizer.  r  r  s         r?   _estimate_example_sizeClient._estimate_example_size  s   >>CGNN344D??CGOO455DCG$4$4566D !(!4!4!:!:!<j$//&0&8O)3&Aot44* @@ C00D "=  .w7 *	)*s   >"D::EEc                d   / n/ nSnU H  nU R                  U5      nXr:  a0  U(       a  UR                  U5        / nSnUR                  U/5        MI  XW-   U:  nU(       a  U(       a  UR                  U5        U/nUnMv  UR                  U5        XW-  nM     U(       a  UR                  U5        U$ )zBatch examples by size limits.r   )r  rx  )	r   r  rB  batchescurrent_batchcurrent_sizer  example_sizesize_exceededs	            r?   _batch_examples_by_sizeClient._batch_examples_by_size.  s     8:G66w?L 2 NN=1$&M#$Ly)(7:NNM }-!(	+$$W-,/  4 NN=)r>   c                  U R                   R                  =(       d    0 R                  SS5      (       d  [        S5      eUc  / nU R	                  USUS9u  pEn U R                  S[        U R                  U5      U0 U R                  ESUR                  0ES.S9n[        R                  " U5        [        [        UR                  5       5      5        UR                  5       $ ! [        [        UR                  5       5      5        f = f)	a  Upload examples using multipart.

Args:
    dataset_id (Union[UUID, str]): The ID of the dataset to upload to.
    uploads (Optional[List[ExampleCreate]]): The examples to upload.
    dangerously_allow_filesystem (bool): Whether to allow uploading files from the filesystem.

Returns:
    ls_schemas.UpsertExamplesResponse: The count and ids of the successfully uploaded examples

Raises:
    ValueError: If the multipart examples endpoint is not enabled.
r  FYour LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.r  r  r  r  r$  r  )r   r  r  r  r  r  r  r  s           r?   r  !Client._upload_examples_multipartW  s   ( 		((.B330%
 
  X  ?G+/+G+G$)E ,H ,
((	;00&t||Z@  -- &(<(<   1 
H //9/6689:}} /6689:r  )upsertsr  c               >   U R                   R                  =(       d    0 R                  SS5      (       d  [        S5      eUc  / nU R	                  USUS9u  p4n U R                  SU R                  SS S	:w  a  U R                  S
S S:w  a  SOSU0 U R                  ESUR                  0ES.S9n[        R                  " U5        [        [        UR                  5       5      5        UR                  5       $ ! [        [        UR                  5       5      5        f = f)zUpsert examples.

.. deprecated:: 0.3.9

    Use Client.create_examples and Client.update_examples instead. Will be
    removed in 0.4.0.
examples_multipart_enabledFr  NTr  r  /v1z/v1/z/v1/platform/examples/multipartz/platform/examples/multipartr  r  r$  )r=  r  r  ru   r  r  r   r  r  r;   r  r  r  r  r  )r   r  r  r  r  r  r  s          r?   upsert_examples_multipart Client.upsert_examples_multipart  s6    		((.B33(%
 
  X  ?G+/+G+G#)E ,H ,
((	;00 ||BC(E1dll236G66Q 67 ! -- &(<(<   1 H //9/6689:}} /6689:s   A,C8 8$D)r  r  r  r  max_concurrencyc               P   SUs=::  a  S::  d  O  [        S5      eU(       a<  U(       a5  SR                  U Vs/ s H	  nSU S3PM     sn5      n[        SU S35      e1 Skn	U(       a9  [        U5      R                  U	5      =n
(       a  [        S	[	        U
5       S
35      eU(       d  U(       d  [        S5      eU(       d  U R                  US9R                  nU(       a?  U Vs/ s H0  n[        U[        5      (       a  [        R                  " S 0 UD6OUPM2     nnGOUR                  S5      nU(       d  [        S5      e[        U5      nUR                  5        H8  u  nnUc  M  [        U5      U:w  d  M  [        SU S[        U5       SU S35      e   [        UUR                  S5      =(       d    S [        U5       5       UR                  S5      =(       d    S [        U5       5       UR                  S5      =(       d    S [        U5       5       UR                  S5      =(       d    S [        U5       5       UR                  S5      =(       d    S [        U5       5       5       VVVVVVs/ s HL  u  nnnnnn[        R                  " S 0 UUUUU=(       d    [!        ["        R$                  " 5       5      US.D6PMN     nnnnnnnU(       d  [        R&                  " / SS9$ U R)                  U5      nU R+                  UX$U5      $ s  snf s  snf s  snnnnnnf )!aH
  Create examples in a dataset.

Args:
    dataset_name (str | None):
        The name of the dataset to create the examples in. Must specify exactly
        one of dataset_name or dataset_id.
    dataset_id (UUID | str | None):
        The ID of the dataset to create the examples in. Must specify exactly
        one of dataset_name or dataset_id
    examples (Sequence[ExampleCreate | dict]):
        The examples to create.
    dangerously_allow_filesystem (bool):
        Whether to allow uploading files from the filesystem.
    **kwargs (Any): Legacy keyword args. Should not be specified if 'examples' is specified.

        - inputs (Sequence[Mapping[str, Any]]): The input values for the examples.
        - outputs (Optional[Sequence[Optional[Mapping[str, Any]]]]): The output values for the examples.
        - metadata (Optional[Sequence[Optional[Mapping[str, Any]]]]): The metadata for the examples.
        - splits (Optional[Sequence[Optional[str | List[str]]]]): The splits for the examples, which are divisions of your dataset such as 'train', 'test', or 'validation'.
        - source_run_ids (Optional[Sequence[Optional[Union[UUID, str]]]]): The IDs of the source runs associated with the examples.
        - ids (Optional[Sequence[Union[UUID, str]]]): The IDs of the examples.

Raises:
    ValueError: If 'examples' and legacy args are both provided.

Returns:
    The LangSmith JSON response. Includes 'count' and 'example_ids'.

!!! warning "Behavior changed in `langsmith` 0.3.11"

    Updated to take argument 'examples', a single list where each
    element is the full example to create. This should be used instead of the
    legacy 'inputs', 'outputs', etc. arguments which split each examples
    attributes across arguments.

    Updated to support creating examples with attachments.

Example:
    ```python
    from langsmith import Client

    client = Client()

    dataset = client.create_dataset("agent-qa")

    examples = [
        {
            "inputs": {"question": "what's an agent"},
            "outputs": {"answer": "an agent is..."},
            "metadata": {"difficulty": "easy"},
        },
        {
            "inputs": {
                "question": "can you explain the agent architecture in this diagram?"
            },
            "outputs": {"answer": "this diagram shows..."},
            "attachments": {"diagram": {"mime_type": "image/png", "data": b"..."}},
            "metadata": {"difficulty": "medium"},
        },
        # more examples...
    ]

    response = client.create_examples(dataset_name="agent-qa", examples=examples)
    # -> {"example_ids": [...
    ```
r   r   z'max_concurrency must be between 1 and 3z, r   zCannot specify z when 'examples' is specified.>   idsrN  splitsrO  r   source_run_idsz(Received unsupported keyword arguments: r   z3Either dataset_id or dataset_name must be provided.r  rN  z+Must specify either 'examples' or 'inputs.'
Length of  (z#) does not match length of inputs (r  rO  c              3  &   #    U  H  nS v   M	     g 7fr   r=   r  r.  s     r?   r  )Client.create_examples.<locals>.<genexpr>C  s     -M<Lqd<L   r   c              3  &   #    U  H  nS v   M	     g 7fr   r=   r  s     r?   r  r  D  s     .N=Mt=Mr  r  c              3  &   #    U  H  nS v   M	     g 7fr   r=   r  s     r?   r  r  E  s     ,L;KaT;Kr  r  c              3  &   #    U  H  nS v   M	     g 7fr   r=   r  s     r?   r  r  F  s     )I8H1$8Hr  r  c              3  &   #    U  H  nS v   M	     g 7fr   r=   r  s     r?   r  r  G  s     4TCSaTCSr  )rN  rO  r   ry   r<  r  r   r  countr=   )ru   r  rZ  
differencer   r  r<  rq   r   rb  r  r  rz   r   zipr  rt   rr   rD  UpsertExamplesResponser  !_upload_examples_batches_parallel)r   r  r  r  r  r  r  rm  
kwarg_keyssupported_kwargsunsupportedxr  rN  	input_lenarg_name	arg_valuein_out_	metadata_split_id_source_run_id_r  s                           r?   ra  Client.create_examples  s   Z O(q(FGGhf#=fas!Hf#=>J!*-KL 
 c&k&<&<=M&NN{N:5;M:NaP  lRSS***EHHJ "!A 2<At1D1D
((-1-!K!  G ZZ)F !NOOFI'-||~#)(S^y-H$$XJbY0@ A..7[;  (6" JMJJy)M-ME)<L-MJJz*N.NU9=M.NJJx(L,L5;K,LJJu%I)Ii8H)IJJ/0T4T5CS4TJ JECy&#~ (( 	"%#'$-!'!6S%6)7	J  * 441MM ..w755Z
 	
K $>0$s   L&7L:ALc           
        / nSnSSK Jn  U" US9 nU V	s/ s H!  n	UR                  U R                  U	UU5      PM#     n
n	[        R
                  " U
5       HH  nUR                  5       nUR                  UR                  S/ 5      5        XlR                  SS5      -  nMJ     S S S 5        [        R                  " XVS9$ s  sn	f ! , (       d  f       N'= f)Nr   )ContextThreadPoolExecutormax_workersr  r  r  )langsmith.utilsr  r  _upload_single_batchr=  r  rJ  r|  r  rb  r  )r   r  r  r  r  all_examples_idstotal_countr  r  r  rA  r  r  s                r?   r  (Client._upload_examples_batches_parallelU  s     =&?Cx % %E --0	 %   //'2!==? '']B(GH||GQ77 3 D" 00(
 	
 DCs   C(B>A$C>C
Cc                   U R                   R                  =(       d    0 R                  SS5      (       aN  U R                  [	        [
        R                  U5      UUS9nUR                  S/ 5      UR                  SS5      S.$ U H/  n[        US5      c  M  S	Ul        [        R                  " S
5        M1     U R                  SS0 U R                  ESS0E[        U Vs/ s H  n0 [        USS9ES[        U5      0EPM     sn5      S9n[         R"                  " U5        UR%                  5       nU Vs/ s H  owS   PM	     sn['        U5      S.$ s  snf s  snf )zIUpload a single batch of examples (used by both sequential and parallel).r  Fr  r  r  r   r  r  Nz7Must upgrade your LangSmith version to use attachments.r  /examples/bulkr  r  Texclude_noner  r  r<  )r=  r  r  r  r   rr   rs   rV  r  r   r   r  r  r'  
dump_modelrt   r;   r  r  rz   )r   r  r  r  r  uploadresponse_datar  s           r?   r  Client._upload_single_batchq  so   II$$*//0%
 
 66		:6-I 7 H  (||M2>!gq1   6=1=)-F&MMQ   00 M4==M.:LM  ',
 ',F	(dC(#j/ ',	 1 H //9$MMOM7DE}tT
}E]+   Fs   #E5Ec                   Uc  U
(       d  [        S5      eUc  U R                  US9R                  n[        R                  " S0 UUUUU	U
UUS.D6nU(       a  XMl        U(       a-  [        U[        5      (       a  [        R                  " U5      OUO[        R                  " 5       Ul        U R                  R                  =(       d    0 R                  SS5      (       a)  U R                  X-/S9  U R                  UR                  S9$ [!        US	5      b  SUl        [$        R&                  " S
5        U R)                  SS0 U R*                  ESS0E[-        0 [/        U5      R1                  5        VVs0 s H  u  pUc  M
  X_M     snnES[        U5      0E5      S9n[2        R4                  " U5        UR7                  5       n[        R8                  " S0 UDU R:                  U R=                  5       S.D6$ s  snnf )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 (Optional[Union[UUID, str]]):
        The ID of the dataset to create the example in.
    dataset_name (Optional[str]):
        The name of the dataset to create the example in.
    created_at (Optional[datetime.datetime]):
        The creation timestamp of the example.
    outputs (Optional[Mapping[str, Any]]):
        The output values for the example.
    metadata (Optional[Mapping[str, Any]]):
        The metadata for the example.
    split (Optional[str | List[str]]):
        The splits for the example, which are divisions
        of your dataset such as 'train', 'test', or 'validation'.
    example_id (Optional[Union[UUID, str]]):
        The ID of the example to create. If not provided, a new
        example will be created.
    source_run_id (Optional[Union[UUID, str]]):
        The ID of the source run associated with this example.
    use_source_run_io (bool):
        Whether to use the inputs, outputs, and attachments from the source run.
    use_source_run_attachments (Optional[List[str]]):
        Which attachments to use from the source run. If use_source_run_io
        is True, all attachments will be used regardless of this param.
    attachments (Optional[Attachments]):
        The attachments for the example.

Returns:
    Example: The created example.
Nz/Must provide either inputs or use_source_run_ior  )rN  rO  r   ry   r  r  r  r  r  F)r  r  )r  r  z6Must upgrade your LangSmith version to use attachmentsr  r  r  r  r  r  rB  r=   )ru   r  r<  rb  r  rl  rq   rt   rr   rs   rD  r=  r  r  r  read_examplerV  r  r   r   r  r  r'  r  r   r;   r  r  r  r  rG  )r   rN  r  r  rl  rO  r   ry   r  r  r  r  r  r  rm  rn  r  rJ  s                     r?   rm  Client.create_example  s   l >"3NOO***EHHJ'' 
 "$!.%6.H*	
 (O  '1S&A&ATYYz"z 	 II$$*//0%
 
 ++z6+R$$$88 t]+7#' VW00M4==M.:LM ,6t,<,B,B,DV,DDA414,DV$c*o	 1 
H //9]]_F%% ..779  Ws   3	G7 G7)rO  c          
        U R                  SS[        US5       3SU(       a  UR                  5       OS0S9nUR                  5       n[	        USU R
                  S9n[        R                  " S
0 UR                  5        VVs0 s H  u  pgUS:w  d  M  Xg_M     snnDUU R                  U R                  5       S	.D6$ s  snnf )a  Read an example from the LangSmith API.

Args:
    example_id (Union[UUID, str]): The ID of the example to read.
    as_of (Optional[datetime.datetime]): The dataset version tag OR
        timestamp to retrieve the example as of.
        Response examples will only be those that were present at the time
        of the tagged (or timestamped) version.

Returns:
    Example: The example.
r  
/examples/r  rO  Nr  attachment_urlsr\  r  r  r  r=   )r  r{   r,  r  r^  r   rb  r  r   r  rG  )r   r  rO  r  r  r  rm  rn  s           r?   r  Client.read_example
  s     ,,*l;<=e* - 
 --/E%6
 !! 
 'J18I3ItqtJ
#nn335	
 	
Js   B<B<r   )r  r  r   re  include_attachmentsc             +    #    0 UEUU[        U[        R                  5      (       a  UR                  5       OUUUUb  [        US5      OSU
S.EnU	b  [	        U	5      US'   Ub  XS'   O"Ub  U R                  US9R                  nXS'   O U(       a  / SQUS'   [        U R                  S	US
95       H  u  p[        USU R                  S9n[        R                  " S0 UR                  5        VVs0 s H  u  nnUS:w  d  M  UU_M     snnDUU R                  U R                  5       S.D6v   Uc  M  US-   U:  d  M    g   gs  snnf 7f)a	  Retrieve the example rows of the specified dataset.

Args:
    dataset_id (Optional[Union[UUID, str]]): The ID of the dataset to filter by.
    dataset_name (Optional[str]): The name of the dataset to filter by.
    example_ids (Optional[Sequence[Union[UUID, str]]): The IDs of the examples to filter by.
    as_of (Optional[Union[datetime.datetime, str]]): 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 (Optional[Sequence[str]]): 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, default=True): Whether to inline S3 URLs.
    offset (int, default=0): The offset to start from. Defaults to 0.
    limit (Optional[int]): The maximum number of examples to return.
    metadata (Optional[dict]): A dictionary of metadata to filter by.
    filter (Optional[str]): A structured filter string to apply to
        the examples.
    include_attachments (bool, default=False): Whether to include the
        attachments in the response.
    **kwargs (Any): Additional keyword arguments are ignored.

Yields:
    The examples.

Examples:
    List all examples for a dataset:

    ```python
    from langsmith import Client

    client = Client()

    # By Dataset ID
    examples = client.list_examples(
        dataset_id="c9ace0d8-a82c-4b6c-13d2-83401d68e9ab"
    )
    # By Dataset Name
    examples = client.list_examples(dataset_name="My Test Dataset")
    ```

    List examples by id

    ```python
    example_ids = [
        "734fc6a0-c187-4266-9721-90b7a025751a",
        "d6b4c1b9-6160-4d63-9b61-b034c585074f",
        "4d31df4e-f9c3-4a6e-8b6c-65701c2fed13",
    ]
    examples = client.list_examples(example_ids=example_ids)
    ```

    List examples by metadata

    ```python
    examples = client.list_examples(
        dataset_name=dataset_name, metadata={"foo": "bar"}
    )
    ```

    List examples by structured filter

    ```python
    examples = client.list_examples(
        dataset_name=dataset_name,
        filter='and(not(has(metadata, \'{"foo": "bar"}\')), exists(metadata, "tenant_id"))',
    )
    ```
NrU  )r  r<  rO  r  inline_s3_urlsr  re  r   r,  r  )r  rO  r   ri  r  r  r  r\  r  r   r=   )rq   r[  r,  r  r'  r  r<  r  r  r^  r   rb  r  r   r  rG  )r   r  r  r  rO  r  r  r  r  r   re  r  r  r  r  r  r  rm  rn  s                      r?   r  Client.list_examples-  sj    l"
"
%/x7H7H%I%I!u,(-(9S_s"
 !,X!6F:! *9%***EHHJ *9IF8#$$[$@
JA J):DLLK $$ $+MMONODAqq<M7M41a4ON'..779	   QUe^
 Os$   C.E	0EE'E	3E	>E	latest)rP  c          	         [        US5      nU R                  SSU S3U R                  [        R                  " SU0UE5      S9n[
        R                  " U5        g)a  Enable dataset indexing. Examples are indexed by their inputs.

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

Args:
    dataset_id (Union[UUID, str]): The ID of the dataset to index.
    tag (Optional[str]): 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.
    **kwargs (Any): Additional keyword arguments to pass as part of request body.

Returns:
    None
r  r  r  z/indexrP  r  Nr{   r  r  r  r  r;   r  )r   r  rP  r  resps        r?   index_datasetClient.index_dataset  sa    . j,7
((F+MMUC2623	 ) 
 	++D1r>   c          	         [        US5      nU R                  SSU S3U R                  [        R                  " 0 UE5      S9n[
        R                  " U5        g)zSync dataset index.

This already happens automatically every 5 minutes, but you can call this to
force a sync.

Args:
    dataset_id (Union[UUID, str]): The ID of the dataset to sync.

Returns:
    None
r  r  r  z/index/syncr  Nr  )r   r  r  r  s       r?   sync_indexed_datasetClient.sync_indexed_dataset  s[    $ j,7
((K0MMJvJ'	 ) 
 	++D1r>   )re  c         	     X   [        US5      nUUS.UEnUb  XFS'   U R                  SSU S3U R                  [        R                  " U5      S9n[
        R                  " U5        / nUR                  5       S    H,  n	UR                  [        R                  " S	0 U	DSU0D65        M.     U$ )
a  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 (Union[UUID, str]): The ID of the dataset to search over.
    filter (Optional[str]): 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.

        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: Additional keyword arguments to pass as part of request body.

Returns:
    list[ExampleSearch]: List of ExampleSearch objects.

Examples:
    ```python
    from langsmith import Client

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

    ```python
    [
        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  )rN  r  re  r  r  z/searchr  r  r=   )
r{   r  r  r  r  r;   r  rx  rb  ExampleSearch)
r   rN  r  r  re  r  reqr  r  exs
             r?   similar_examplesClient.similar_examples  s    ^ j,7

 

 "M((G,MMC	 ) 
 	++D1))+j)BOOJ44QrQjQR *r>   )rN  rO  r   ry   r  r  r  c               J   Ub?  U R                   R                  =(       d    0 R                  SS5      (       d  [        S5      e[	        UUUUUUUS9n	[
        R                  " S0 U	R                  5        V
Vs0 s H  u  pUc  M
  X_M     snn
D6nUc  U R                  U5      R                  nU R                   R                  =(       d    0 R                  SS5      (       a  [	        U R                  Xl/S95      $ U R                  SS[        US5       30 U R                  ES	S
0E[        0 [        U5      R                  5        V
Vs0 s H  u  pUc  M
  X_M     snn
ES[!        U5      0E5      S9n["        R$                  " U5        UR'                  5       $ s  snn
f s  snn
f )a  Update a specific example.

Args:
    example_id (Union[UUID, str]):
        The ID of the example to update.
    inputs (Optional[Dict[str, Any]]):
        The input values to update.
    outputs (Optional[Mapping[str, Any]]):
        The output values to update.
    metadata (Optional[Dict]):
        The metadata to update.
    split (Optional[str | List[str]]):
        The dataset split to update, such as
        'train', 'test', or 'validation'.
    dataset_id (Optional[Union[UUID, str]]):
        The ID of the dataset to update.
    attachments_operations (Optional[AttachmentsOperations]):
        The attachments operations to perform.
    attachments (Optional[Attachments]):
        The attachments to add to the example.

Returns:
    Dict[str, Any]: The updated example.
r  FYour LangSmith deployment does not allow using the attachment operations, please upgrade your deployment to the latest version.)rN  rO  r<  r   ry   r  r  )r  r  r8  r  r  r  r  r  r  r=   )r=  r  r  ru   r   rb  r  r   r  r  r  r  r{   r  r'  r  rt   r;   r  r  )r   r  rN  rO  r   ry   r  r  r  example_dictrm  rn  r  r  s                 r?   update_exampleClient.update_exampleJ  s   H "-II,,2774e  ! V  #9#
 ** 
 , 2 2 4F 4tqt 4F
 **:6AAJII$$*//0%
 
 //)9 0   00Xj,?@AM4==M.:LM  )37(;(A(A(C(C  !AD(C %c*o		 1 H //9==?"A G,s   7	FF	FF)r  r  r  r  c               b	   U(       a  U(       a  [        S[        U5       S35      eU(       d  U(       d  [        S5      eU(       a  U(       a  [        S5      eU(       a  U R                  US9R                  nU(       av  U Vs/ s H0  n[	        U[
        5      (       a  [        R                  " S-0 UD6OUPM2     nnU(       d0  US   R                  (       a  US   R                  nGO[        S5      eGOUR                  SS	5      nU(       d  [        S
5      eU(       dk  SU;  a  U R                  US   5      R                  nOF[        [        US   5      5      S:  a  [        S5      eUS   S   (       d  [        S5      eUS   S   nU R                  R                  =(       d    0 R                  S5      n	U	(       d6  UR                  S5      =(       d    UR                  S5       b  [        S5      e[        U5      n
UR                  5        H7  u  pUc  M
  [        U5      U
:w  d  M  [        SU S[        U5       SU
 S35      e   [!        UUR                  SS [#        U
5       5       5      UR                  SS [#        U
5       5       5      UR                  SS [#        U
5       5       5      UR                  SS [#        U
5       5       5      UR                  SS [#        U
5       5       5      UR                  SS  [#        U
5       5       5      UR                  SS! [#        U
5       5       5      5       VVVVVVVVs	/ s H*  u  pnnnnnn[        R                  " S-0 UUUUUUUUS".D6PM,     nnnnnnnnnS	nU R                  R                  =(       d    0 R                  SS#5      (       aB  U R%                  ['        [(        R*                  U5      UUS$9nS%UR                  S&S5       S'30UE$ U R-                  S(S)0 U R.                  ES*S+0E[1        U VVVs/ s H8  n[3        U5      R                  5        VVs0 s H  u  nnUc  M  UU_M     snnPM:     snnn5      S,9n[4        R6                  " U5        UR9                  5       $ s  snf s  s	nnnnnnnnf s  snnf s  snnnf ).a  Update multiple examples.

Examples are expected to all be part of the same dataset.

Args:
    dataset_name (str | None):
        The name of the dataset to update. Should specify exactly one of
        'dataset_name' or 'dataset_id'.
    dataset_id (UUID | str | None):
        The ID of the dataset to update. Should specify exactly one of
        'dataset_name' or 'dataset_id'.
    updates (Sequence[ExampleUpdate | dict] | None):
        The example updates. Overwrites any specified fields and does not
        update any unspecified fields.
    dangerously_allow_filesystem (bool):
        Whether to allow using filesystem paths as attachments.
    **kwargs (Any):
        Legacy keyword args. Should not be specified if 'updates' is specified.

        - example_ids (Sequence[UUID | str]): The IDs of the examples to update.
        - inputs (Sequence[dict | None] | None): The input values for the examples.
        - outputs (Sequence[dict | None] | None): The output values for the examples.
        - metadata (Sequence[dict | None] | None): The metadata for the examples.
        - splits (Sequence[str | list[str] | None] | None): The splits for the examples, which are divisions of your dataset such as 'train', 'test', or 'validation'.
        - attachments_operations (Sequence[AttachmentsOperations | None] | None): The operations to perform on the attachments.
        - dataset_ids (Sequence[UUID | str] | None): The IDs of the datasets to move the examples to.

Returns:
    The LangSmith JSON response. Includes 'message', 'count', and 'example_ids'.

!!! warning "Behavior changed in `langsmith` 0.3.9"

    Updated to ...

Example:
    ```python
    from langsmith import Client

    client = Client()

    dataset = client.create_dataset("agent-qa")

    examples = [
        {
            "inputs": {"question": "what's an agent"},
            "outputs": {"answer": "an agent is..."},
            "metadata": {"difficulty": "easy"},
        },
        {
            "inputs": {
                "question": "can you explain the agent architecture in this diagram?"
            },
            "outputs": {"answer": "this diagram shows..."},
            "attachments": {"diagram": {"mime_type": "image/png", "data": b"..."}},
            "metadata": {"difficulty": "medium"},
        },
        # more examples...
    ]

    response = client.create_examples(dataset_name="agent-qa", examples=examples)
    example_ids = response["example_ids"]

    updates = [
        {
            "id": example_ids[0],
            "inputs": {"question": "what isn't an agent"},
            "outputs": {"answer": "an agent is not..."},
        },
        {
            "id": example_ids[1],
            "attachments_operations": [
                {"rename": {"diagram": "agent_diagram"}, "retain": []}
            ],
        },
    ]
    response = client.update_examples(dataset_name="agent-qa", updates=updates)
    # -> {"example_ids": [...
    ```
z&Must pass in either 'updates' or args z, not both.z6Please pass in a non-empty sequence for arg 'updates'.z;Must pass in exactly one of 'dataset_name' or 'dataset_id'.r  r   z=Must pass in (exactly) one of 'dataset_name' or 'dataset_id'.r  Nz9Must pass in (exactly) one of 'updates' or 'example_ids'.rE  r   z-Dataset IDs must be the same for all examplesz+If specified, dataset_ids must be non-null.r  r  r  r  r  r  z%) does not match length of examples (r  rN  c              3  &   #    U  H  nS v   M	     g 7fr   r=   r  s     r?   r  )Client.update_examples.<locals>.<genexpr>J       )L8K1$8Kr  rO  c              3  &   #    U  H  nS v   M	     g 7fr   r=   r  s     r?   r  r  K  s     *M9LA49Lr  r   c              3  &   #    U  H  nS v   M	     g 7fr   r=   r  s     r?   r  r  L  s     +N:MQD:Mr  r  c              3  &   #    U  H  nS v   M	     g 7fr   r=   r  s     r?   r  r  M  r   r  c              3  &   #    U  H  nS v   M	     g 7fr   r=   r  s     r?   r  r  N       .Q=Pt=Pr  c              3  &   #    U  H  nS v   M	     g 7fr   r=   r  s     r?   r  r  O  r%  r  c              3  &   #    U  H  nS v   M	     g 7fr   r=   r  s     r?   r  r  Q  s     2UATA4ATr  )r<  rN  rO  r  r   ry   r  r  Fr  rx  r  z examples updatedr8  r  r  r  r  r=   )ru   r   r  r<  rq   r   rb  r  r  r  r  rz   rZ  r=  r  r   r  r  r  r   rr   rs   r  r  r'  r  r;   r  r  )r   r  r  r  r  r  r  updates_objr  multipart_enabledexamples_lenr  r  r  r  r  r  r  dataset_id_attachments_attachments_operations_r  r  rm  rn  s                            r?   update_examplesClient.update_examples  s   p g8v{S  'UVVJM  ***EHHJ ! A 2<At1D1D
((-1-!K   
 q>,,!,Q!:!:J$W 	  !**]D9K O   .!%!2!2;q>!B!M!MJVM234q8$%TUU.q1$%RSS!'!6q!9J!%!9!9!?R D D4! &ZZ 89VVZZ=V !X 
 {+L'-||~#(S^|-K$$XJbY0@ A00<~Q@  (6& nqJJx)Ll8K)LMJJy*M|9L*MNJJz+N%:M+NOJJx)Ll8K)LMJJ}.QU<=P.QRJJ}.QU<=P.QRJJ02U|AT2Un niCdIv{LRi (( !"%#'&1$-!''32I	n  6 II$$*//0%
 
 66		:6#-I 7 H hll7A677HI  00 M4==M.:LM ,7 ,7 -7w,?,E,E,G,GDAq#$ !%1,G
 ,7	 1 H" //9==?"af ds*   7R1R#"R*
R$R$R*$R*c                    U R                  SS[        US5       3U R                  S9n[        R                  " U5        g)zDelete an example by ID.

Args:
    example_id (Union[UUID, str]):
        The ID of the example to delete.

Returns:
    None
r  r  r  r  Nr  )r   r  r  s      r?   delete_exampleClient.delete_examplez  sE     ,,*l;<=MM - 

 	++H5r>   )hard_deletec               Z   U(       a  [        U5       VVs/ s H  u  p4[        [        USU S35      5      PM      snnSS.n[        U R                  S5      n[        U R                  U5      nU R                  R                  SU0 U R                  ESS0E[        U5      U R                  S	9nO[S
[        U5       VVs/ s H  u  p4[        [        USU S35      5      PM      snn0n	U R                  SS0 U R                  ESS0EU	S9n[        R                  " U5        gs  snnf s  snnf )zDelete multiple examples by ID.

Parameters
----------
example_ids : Sequence[ID_TYPE]
    The IDs of the examples to delete.
hard_delete : bool, default=False
    If True, permanently delete the examples. If False, soft delete them.
example_ids[]T)r  r3  zdatasets/examples/deleter  r  r  )rC  r  r  r  r  r  r;  N)r  rt   r{   _platform_pathr   r  r   r  r  r'  r  r  r;   r  )
r   r  r3  r  r  r   rx   full_urlr  r  s
             r?   delete_examplesClient.delete_examples  sB     #,K"8 "8 QCq&9:;"8   $D "$,,0JKD%dllD9H||++M4==M.:LM & , H "+K"8 "8 QCq&9:;"8 &F 00M4==M.:LM	 1 H 	++H5= & s   %D!>%D')r  r  rO  c               R   Uc'  Uc  [        S5      eU R                  US9R                  n0 nUb4  [        U[        R                  5      (       a  UR                  5       OUUS'   U R                  SS[        US5       S3US9n[        R                  " U5        UR                  5       $ )	a  Get the splits for a dataset.

Args:
    dataset_id (Optional[Union[UUID, str]]): The ID of the dataset.
    dataset_name (Optional[str]): The name of the dataset.
    as_of (Optional[Union[str, datetime.datetime]]): 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 splits.
Must provide dataset name or IDr  rO  r  r  r  /splitsr  )ru   r  r<  rq   r[  r,  r  r{   r;   r  r  )r   r  r  rO  r  r  s         r?   list_dataset_splitsClient.list_dataset_splits  s    & # !BCC***EHHJ%/x7H7H%I%I!u 7O ,,*l;<GD - 

 	++H5}}r>   )r  r  ry  c               D   Uc'  Uc  [        S5      eU R                  US9R                  nU[        U5       VVs/ s H  u  pg[	        [        USU S35      5      PM      snnUS.nU R                  SS[        US	5       S
3US9n	[        R                  " U	5        gs  snnf )a  Update the splits for a dataset.

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

Returns:
    None
Nr<  r  r5  r6  )
split_namer  ry  r  r  r  r=  r  )	ru   r  r<  r  rt   r{   r  r;   r  )
r   r  r  rA  r  ry  r  r  r  r  s
             r?   update_dataset_splitsClient.update_dataset_splits  s    . # !BCC***EHHJ$ (44FA HSL1"5674 
 ,,Z\ BC7KRV - 
 	++H5s   %Bc                    [        U[        [        R                  45      (       a  U R	                  XS9nU$ [        [        R                  U5      nU$ )zResolve the run ID.

Args:
    run (Union[Run, RunBase, str, 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`  )rq   rt   rr   rs   ra  r   rb  r_  )r   r`  r`  run_s       r?   _resolve_run_idClient._resolve_run_id
  sH    & cC+,,===FD  
,Dr>   c                   [        U[        [        R                  45      (       a  U R	                  U5      nU$ [        U[
        R                  5      (       a  UnU$ [        U[        5      (       a5  [
        R                  " S0 UDU R                  U R                  5       S.D6nU$ UR                  b  U R	                  UR                  5      nU$ SnU$ )zResolve the example ID.

Args:
    example (Optional[Union[Example, str, UUID, dict]]):
        The example to resolve.
    run (Run):
        The run associated with the example.

Returns:
    Optional[Example]: The resolved example.
rB  Nr=   )rq   rt   rr   rs   r  rb  r  r   r  rG  r'  )r   r  r`  reference_example_s       r?   _resolve_example_idClient._resolve_example_id#  s      gTYY/00!%!2!27!; "! !3!344!( "! &&!+!3!3 ""..779" "!	 %%1!%!2!233K3K!L "! "&!!r>   )fn_namec               ^  ^^ SSK Jm      SUU4S jjnS	S jn[        UTR                  5      (       a  U/nU$ U" U5      (       a  US    Vs/ s H
  oc" U5      PM     nnU$ [        U[        5      (       a  U" [        [        U5      5      /nU$ [        S[        U5       S35      es  snf )
Nr   r]   c                ~   > [        U [        5      (       a&  TR                  " S0 TU R                  S5      S.U ED6$ U $ )N	reasoning)r  commentr=   )rq   r   EvaluationResultr  )single_resultrN  ls_evaluators    r?   _cast_result1Client._select_eval_results.<locals>._cast_resultM  sR     -..#44 &#0#4#4[#A (  ! r>   r  c                :    [        U [        5      =(       a    SU ;   $ )Nr  )rq   r   )r  s    r?   _is_eval_results5Client._select_eval_results.<locals>._is_eval_resultsZ  s    gt,Eg1EEr>   z!Invalid evaluation results type: z.. Must be EvaluationResult, EvaluationResults.)rT  z*Union[ls_evaluator.EvaluationResult, dict]r   ls_evaluator.EvaluationResult)r  r   r   z)TypeGuard[ls_evaluator.EvaluationResults])langsmith.evaluationr^   rq   rS  r   r   ru   r  )r   r  rN  rV  rY  results_rK  rU  s     `    @r?   _select_eval_resultsClient._select_eval_resultsC  s     	C	!E	!*	! 	!	F g|<<==yH  g&&181CD1CAQ1CHD  &&$T$%89:H 	 3DM? C@ @ 	 Es   B*)source_inforx  r`  c                   U R                  XS9nU R                  XF5      nUR                  UUS9nU R                  UUUS9n	U	S   $ )a  Evaluate a run.

Args:
    run (Union[Run, RunBase, str, UUID]):
        The run to evaluate.
    evaluator (RunEvaluator):
        The evaluator to use.
    source_info (Optional[Dict[str, Any]]):
        Additional information about the source of the evaluation to log
        as feedback metadata.
    reference_example (Optional[Union[Example, str, dict, UUID]]):
        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.
rF  r  r`  r   )rH  rL  evaluate_run_log_evaluation_feedback
r   r`  r^   r`  rx  r`  rG  rK  evaluator_responser  s
             r?   rd  Client.evaluate_runj  sq    < ##C#I!556GN&33& 4 
 //# 0 
 qzr>   )	_executorc                 ^ ^ T R                  U5      nUU 4S jnU GH7  nU=(       d    0 n	UR                  (       a  0 UR                  EU	En	S n
UR                  (       a  UR                  n
OUb  UR                  n
UR                  b  UR                  R                  SS 5      OS nU" U
UR                  UR                  UR                  UR                  UR                  U	UR                  [        [        [        R                     UR                   5      [        R"                  R$                  UUR                  U(       a  UR&                  OS US9  GM:     U$ )Nc                 t   > T(       a  TR                   " TR                  40 U D6  g TR                  " S0 U D6  g )Nr=   )r  create_feedback)r  ri  r   s    r?   _submit_feedback9Client._log_evaluation_feedback.<locals>._submit_feedback  s0      !5!5@@$$.v.r>   r  )r)  r  r   r   rR  
correctionr`  r  feedback_configfeedback_source_typerc  rP  rw  r  )r^  evaluator_infotarget_run_idr<  rP  r  r  r   r   rR  ro  r  r   r   rb  FeedbackConfigrp  FeedbackSourceTypeMODELrw  )r   rg  r`  r`  rc  ri  r  rm  ressource_info_r  r  s   `    `      r?   re  Client._log_evaluation_feedback  s    ++,>?	/ C&,"L!!E#"4"4EEG  ++&&47II4ICIIMM'40tEGGiiii>>(!// $Z6679L9L! &0%B%B%H%H%ii),$! : r>   c                  #    U R                  XS9nU R                  XF5      nUR                  UUS9I Sh  vN nU R                  UUUS9n	U	S   $  N7f)a  Evaluate a run asynchronously.

Args:
    run (Union[Run, str, UUID]):
        The run to evaluate.
    evaluator (RunEvaluator):
        The evaluator to use.
    source_info (Optional[Dict[str, Any]]):
        Additional information about the source of the evaluation to log
        as feedback metadata.
    reference_example (Optional[Union[Example, str, dict, UUID]]):
        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.
rF  rb  Nrc  r   )rH  rL  aevaluate_runre  rf  s
             r?   r{  Client.aevaluate_run  s~     < ##C#I!556GN#,#:#:& $; $
 

 //# 0 

 qz
s   4AAArN  )r   r   rw  ro  rR  r`  rq  r  feedback_idrp  r  rc  comparative_experiment_idfeedback_group_idrP  r  c          
     x
   U=(       d    UnUc  Uc  [        S5      eUb  Ub  [        S5      eU(       a'  [        R                  " S[        U5       3[        5         [        U	[        R                  5      (       d  [        R                  " U	5      n	U	[        R                  R                  :X  a  [        R                  " US9nOAU	[        R                  R                  :X  a  [        R                  " US9nO[        SU	 35      eUR                  b  UR                  O0 Ul        U
b*  SUR                  ;  a  S[        U
5      0UR                  S'   UR                  (       a  SUR                  ;   a}  UR                  S   n[        US	5      (       a   [        U5      (       a  UR!                  5       nSU;   a(  [        [#        UR                  S   S   S
5      5      US'   UUR                  S'   [        R$                  " S'0 S['        U5      _S['        USS9_S['        USS9_SU_S[)        U5      _SU_SU_SU_SU_S[*        R*                  R-                  [*        R.                  R0                  5      _S[*        R*                  R-                  [*        R.                  R0                  5      _SU_S['        USS9_S['        USS9_S['        USS9_SU_SU_6nU R2                  (       + =(       a/    U R4                  R6                  =(       d    0 R9                  SS5      nU(       Gax  U R4                  R:                  (       Ga\  [<        R>                  " U R4                  R:                  S5      (       Ga+  U R@                  c  U RB                  Gb  URD                  Gb  U RF                  c  [I        U5      nU RB                  b  [K        U5      nU RB                  RL                     [O        UU RB                  [P        5      nU(       aJ  U RB                  =RR                  S-  sl)        U RT                  (       a  U RT                  RW                  5         SSS5        OU R@                  b8  U R@                  RY                  [[        [        UR\                  5      U5      5        O<[_        UR!                  SS 95      nU Ra                  S!S"S#U0U[<        Rb                  4S$9  [        Rd                  " S'0 UR!                  5       D6$ ! , (       d  f       N2= f! [f         a  n[h        Rk                  S%SS&9  UeSnAff = f)(a:  Create feedback for a run.

!!! note

    To enable feedback to be batch uploaded in the background you must
    specify `trace_id`. *We highly encourage this for latency-sensitive environments.*

Args:
    key (str):
        The name of the feedback metric.
    score (Optional[Union[float, int, bool]]):
        The score to rate this run on the metric or aspect.
    value (Optional[Union[float, int, bool, str, dict]]):
        The display value or non-numeric value for this feedback.
    run_id (Optional[Union[UUID, str]]):
        The ID of the run to provide feedback for. At least one of run_id,
        trace_id, or project_id must be specified.
    trace_id (Optional[Union[UUID, str]]):
        The ID of the trace (i.e. root parent run) of the run to provide
        feedback for (specified by run_id). If run_id and trace_id are the
        same, only trace_id needs to be specified. **NOTE**: trace_id is
        required feedback ingestion to be batched and backgrounded.
    correction (Optional[dict]):
        The proper ground truth for this run.
    comment (Optional[str]):
        A comment about this feedback, such as a justification for the score or
        chain-of-thought trajectory for an LLM judge.
    source_info (Optional[Dict[str, Any]]):
        Information about the source of this feedback.
    feedback_source_type (Union[FeedbackSourceType, str]):
        The type of feedback source, such as model (for model-generated feedback)
        or API.
    source_run_id (Optional[Union[UUID, str]]):
        The ID of the run that generated this feedback, if a "model" type.
    feedback_id (Optional[Union[UUID, str]]):
        The ID of the feedback to create. If not provided, a random UUID will be
        generated.
    feedback_config (Optional[FeedbackConfig]):
        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 (Optional[Union[UUID, str]]):
        The ID of the project (or experiment) to provide feedback on. This is
        used for creating summary metrics for experiments. Cannot specify
        run_id or trace_id if project_id is specified, and vice versa.
    comparative_experiment_id (Optional[Union[UUID, str]]):
        If this feedback was logged as a part of a comparative experiment, this
        associates the feedback with that experiment.
    feedback_group_id (Optional[Union[UUID, str]]):
        When logging preferences, ranking runs, or other comparative feedback,
        this is used to group feedback together.
    extra (Optional[Dict]):
        Metadata for the feedback.
    **kwargs (Any):
        Additional keyword arguments.

Returns:
    Feedback: The created feedback object.

Example:
    ```python
    from langsmith import trace, traceable, Client


    @traceable
    def foo(x):
        return {"y": x * 2}


    @traceable
    def bar(y):
        return {"z": y - 1}


    client = Client()

    inputs = {"x": 1}
    with trace(name="foobar", inputs=inputs) as root_run:
        result = foo(**inputs)
        result = bar(**result)
        root_run.outputs = result
        trace_id = root_run.id
        child_runs = root_run.child_runs

    # Provide feedback for a trace (a.k.a. a root run)
    client.create_feedback(
        key="user_feedback",
        score=1,
        trace_id=trace_id,
    )

    # Provide feedback for a child run
    foo_run_id = [run for run in child_runs if run.name == "foo"][0].id
    client.create_feedback(
        key="correctness",
        score=0,
        run_id=foo_run_id,
        # trace_id= is optional but recommended to enable batched and backgrounded
        # feedback ingestion.
        trace_id=trace_id,
    )
    ```
Nz8One of run_id, trace_id, or project_id  must be providedz?project_id cannot be provided if run_id or trace_id is 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   rw  r  r   r   ro  rR  feedback_sourcerl  modified_atrp  r+  r~  r  rP  r  use_multipart_endpointz0.8.10r   r  r  	/feedbackr  )r  r  r  zError creating feedbackr  r=   )6ru   r   r   rP  r~  rq   rb  ru  APIAPIFeedbackSourcerv  ModelFeedbackSourcer   rt   rz  rU  r   r{   FeedbackCreater   r   r[  r\  r]  r^  r0  r=  r  r  r   r;   is_version_greater_or_equalr  r&  rw  r+  r/   r1   r  r.   r&   r  r'  rZ  r  r    r<  r'  r  r  Feedbackr   r   r  )r   r)  r  r   r   rw  ro  rR  r`  rq  r  r}  rp  r  rc  r~  r  rP  r  r  r  	_run_metafeedbackr/  r  r  r  feedback_blockr   s                                r?   rl  Client.create_feedback  s   F #8>j0WXX*"8Q  MM$Vn-/"
i	2J4Q4QRR'1'D'D(($ $z'D'D'H'HH00+F   &)F)F)L)LL","@"@+"V #@AU@V!WXX,;,D,D,P((VX $ (WO<T<T-T5=s=?Q4R((1''G7O7O,O />.F.Fw.O	9f--(92E2E ) 0Iy(*- +44W=hGI+Ih' 5>((1!00 , $F=	
 &hDA  -U3  &   !0 $,,001B1B1F1FG %--11(2C2C2G2GH !0 (
E  +7-4+!& #//@d"S'( )* +H0 !% 8 88 2		--3c*D1 
 II%%%889J9JHUU&&2d6L6L6X%%1&&. 7 A))5T) #
 //44#G* 22%$
 $ 22>>!C>#99 $ : : > > @ 54 ''3&&**(X[[)9=I "-X]]]-M!N))$ (:&==? *  &&9993 544  	LL2TLBG	s3   N
T 'A-TB.T 
TT 
T9T44T9)r   r   ro  rR  c                   0 nUb  [        U5      US'   Ub  X6S'   Ub  XFS'   Ub  XVS'   U R                  SS[        US5       30 U R                  ES	S
0E[	        U5      S9n[
        R                  " U5        g)a  Update a feedback in the LangSmith API.

Args:
    feedback_id (Union[UUID, str]):
        The ID of the feedback to update.
    score (Optional[Union[float, int, bool]]):
        The score to update the feedback with.
    value (Optional[Union[float, int, bool, str, dict]]):
        The value to update the feedback with.
    correction (Optional[dict]):
        The correction to update the feedback with.
    comment (Optional[str]):
        The comment to update the feedback with.

Returns:
    None
Nr   r   ro  rR  r8  
/feedback/r}  r  r  r  )r   r  r{   r  r'  r;   r  )r   r}  r   r   ro  rR  feedback_updater  s           r?   update_feedbackClient.update_feedback  s    4 +-'=e'DOG$',G$!,6L))0I&,,+}=>?It}}In6HI_-	 - 
 	++H5r>   c                    U R                  SS[        US5       35      n[        R                  " S0 UR	                  5       D6$ )zRead a feedback from the LangSmith API.

Args:
    feedback_id (Union[UUID, str]):
        The ID of the feedback to read.

Returns:
    Feedback: The feedback.
r  r  r}  r=   )r  r{   rb  r  r  r   r}  r  s      r?   read_feedbackClient.read_feedback  sE     ,,+}=>?
 ""5X]]_55r>   )rh  feedback_keyrq  r  c             +     #    UUb  [        US5      OSS.UEnUb  X&S'   Ub  X6S'   [        U R                  SUS95       H-  u  px[        R                  " S	0 UD6v   Uc  M"  US-   U:  d  M-    g   g7f)
ad  List the feedback objects on the LangSmith API.

Args:
    run_ids (Optional[Sequence[Union[UUID, str]]]):
        The IDs of the runs to filter by.
    feedback_key (Optional[Sequence[str]]):
        The feedback key(s) to filter by. Examples: 'correctness'
        The query performs a union of all feedback keys.
    feedback_source_type (Optional[Sequence[FeedbackSourceType]]):
        The type of feedback source, such as model or API.
    limit (Optional[int]):
        The maximum number of feedback to return.
    **kwargs (Any):
        Additional keyword arguments.

Yields:
    The feedback objects.
NrU  )r`  r  r  sourcer  r  r   r=   )r  r  r  rb  r  )	r   rh  r  rq  r  r  r  r  r  s	            r?   list_feedbackClient.list_feedback*  s     8 (-(9S_s
 

 #(5M+38$$$[$@
KA %%111 QUe^
s   AA2"A2-A2c                    U R                  SS[        US5       3U R                  S9n[        R                  " U5        g)zDelete a feedback by ID.

Args:
    feedback_id (Union[UUID, str]):
        The ID of the feedback to delete.

Returns:
    None
r  r  r}  r  Nr  r  s      r?   delete_feedbackClient.delete_feedbackU  sE     ,,+}=>?MM - 

 	++H5r>   )r   ro  rR  r   c                  [        XR                  SS9u  pxXpR                  :w  a  [        SU 35      eU R                  SS[	        U5       3[        UUUUUS.5      U R                  S9n	[        R                  " U	5        g)	aM  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 (Optional[Union[float, int, bool]]): The score of the feedback.
    value (Optional[Union[float, int, bool, str, dict]]): The value of the
        feedback.
    correction (Optional[dict]): The correction of the feedback.
    comment (Optional[str]): The comment of the feedback.
    metadata (Optional[dict]): Additional metadata for the feedback.

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

Returns:
    None
r   )r   zInvalid source API URL. r  z/feedback/tokens/)r   r   ro  rR  r   r  N)	r   r   ru   r  r{   r'  r  r;   r  )
r   rb  r   r   ro  rR  r   r\  r   r  s
             r?   create_feedback_from_token!Client.create_feedback_from_tokenf  s    8 &9,,!&
" \\)77GHII,, 456""",& (	 MM - 
 	++H5r>   )
expirationrp  r}  c                  UUUU=(       d    [        [        R                  " 5       5      S.nUc  [        R                  " SSSS9US'   O[        U[        R                  5      (       a  UR                  5       US'   Ow[        U[        R                  5      (       aA  [        R                  " UR                  UR                  S-  UR                  S-  S-  S9US'   O[        S	[        U5       35      eU R                  S
S[        U5      S9n[        R                   " U5        [        R"                  " S0 UR%                  5       D6$ )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 (Union[UUID, str]):
        The ID of the run.
    feedback_key (str):
        The key of the feedback to create.
    expiration (Optional[datetime.datetime | datetime.timedelta]): The expiration time of the pre-signed URL.
        Either a datetime or a timedelta offset from now.
        Default to 3 hours.
    feedback_config (Optional[FeedbackConfig]):
        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 (Optional[Union[UUID, str]): The ID of the feedback to create. If not provided, a new
        feedback will be created.

Returns:
    FeedbackIngestToken: The pre-signed URL for uploading feedback data.
)r)  r  rp  r<  r   r   dayshoursminutes
expires_in
expires_at  <   Unknown expiration type: r  /feedback/tokens)r  r=   )rt   rr   rD  rb  TimeDeltaInputrq   r[  r,  	timedeltar  secondsru   r  r  r'  r;   r  FeedbackIngestTokenr  )r   r)  r  r  rp  r}  r   r  s           r?   create_presigned_feedback_token&Client.create_presigned_feedback_token  s.   F (.2TZZ\!2	 
 !+!:!:"D
 
H$5$566!+!5!5!7D
H$6$677!+!:!:__ ((D0#++r1R7"D 8j9I8JKLL,,T" - 

 	++H5--@@@r>   )r  feedback_configsc               b  ^ ^ Ub#  [        U5      [        U5      :w  a  [        S5      eU(       d  S/[        U5      -  nSu  pVUc  [        R                  " SSSS9nO[	        U[
        R
                  5      (       a  UR                  5       nOt[	        U[
        R                  5      (       a>  [        R                  " UR                  UR                  S-  UR                  S-  S-  S9nO[        S	[        U5       35      e[        [        X$5       VVs/ s H  u  pxUUUUUS
.PM     snn5      mSUU 4S jjn	/ n
[        R                  " [        T R                  5      S9 nT R                  R!                  5        VVs/ s H  u  pUR#                  XU5      PM     nnn[        R$                  " U5       HI  nUR'                  5       nU
R)                  U Vs/ s H  n[        R*                  " S0 UD6PM     sn5        MK     SSS5        U
$ s  snnf s  snnf s  snf ! , (       d  f       U
$ = f)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 (Union[UUID, str]):
        The ID of the run.
    feedback_keys (Sequence[str]):
        The key of the feedback to create.
    expiration (Optional[datetime.datetime | datetime.timedelta]): The expiration time of the pre-signed URL.
        Either a datetime or a timedelta offset from now.
        Default to 3 hours.
    feedback_configs (Optional[Sequence[Optional[FeedbackConfig]]]):
        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:
    Sequence[FeedbackIngestToken]: The pre-signed URL for uploading feedback data.
NzBThe length of feedback_keys and feedback_configs must be the same.NNr   r   r  r  r  r  )r)  r  rp  r  r  c           	        > TR                  SU  S3T0 TR                  E[        U=(       d    TR                  0ES.S9n[        R
                  " U5        UR                  5       $ )Nr  r  r  r$  )r  r  r  r   r;   r  r  )r   r   r  r   r   s      r?   r  4Client.create_presigned_feedback_tokens.<locals>.req#  sn    00)+,  -- !7#:dll   1 
H //9==?"r>   r  )r   rt   r   r1  r   r  r=   )rz   ru   rb  r  rq   r[  r,  r  r  r  r  r'  r  r=  r  r   r   r  r  rJ  r|  r  )r   r)  feedback_keysr  r  r  r  r  rp  r  tokensr  r   r   futsfutr  r  r   s   `                 @r?    create_presigned_feedback_tokens'Client.create_presigned_feedback_tokens  s"   D 'C,>#FVBW,WT    $vM(::!+
#22J
 
H$5$566#--/J
H$6$677#22__ ((D0#++r1R7J 8j9I8JKLL 69!661L %$0'6",",6
	# 	# ""s43G3G/HIX )-(<(<(B(B(D(D$G g6(D   t,::<HPQZ33;d;Q - J Q> R JI s0   H
"H H;H H9HH
H.)r  c             #     #    [        US5      Ub  [        US5      OSS.n[        U R                  SUS95       H-  u  pE[        R
                  " S0 UD6v   Uc  M"  US-   U:  d  M-    g   g7f)	zList the feedback ingest tokens for a run.

Args:
    run_id (Union[UUID, str]): The ID of the run to filter by.
    limit (Optional[int]): The maximum number of tokens to return.

Yields:
    The feedback ingest tokens.
r)  NrU  )r)  r  r  r  r   r=   )r{   r  r  r  rb  r  )r   r)  r  r  r  tokens         r?   list_presigned_feedback_tokens%Client.list_presigned_feedback_tokens?  sx       vx0(-(9S_s
 "$$%7$G
HA 009599 QUe^
s   AA,A,'A,r  r+  r  r  c             #    #    Ub  [        US5      OSUb  [        US5      OSUb  [        US5      OSUS.n[        U R                  SUS95       H-  u  pg[        R
                  " S	0 UD6v   Uc  M"  US-   U:  d  M-    g   g7f)
a  List feedback formulas.

Args:
    dataset_id (Optional[Union[UUID, str]]):
        The ID of the dataset to filter by.
    session_id (Optional[Union[UUID, str]]):
        The ID of the session to filter by.
    limit (Optional[int]):
        The maximum number of feedback formulas to return.
    offset (int):
        The starting offset for pagination.

Yields:
    The feedback formulas.
Nr  r+  rU  r  /feedback/formulasr  r   r=   )r{   r  r  r  rb  FeedbackFormula)r   r  r+  r  r  r  r  feedback_formulas           r?   list_feedback_formulasClient.list_feedback_formulasY  s     2 7A6L\2RV 7A6L\2RV(-(9S_s	"
 $-$$%9&$I$
A ,,@/?@@ QUe^$
s   A,B2B=Bc                    U R                  SS[        US5       35      n[        R                  " U5        [        R
                  " S0 UR                  5       D6$ )zGet a feedback formula by ID.

Args:
    feedback_formula_id (Union[UUID, str]):
        The ID of the feedback formula to retrieve.

Returns:
    The requested feedback formula.
r  /feedback/formulas/feedback_formula_idr=   )r  r{   r;   r  rb  r  r  r   r  r  s      r?   get_feedback_formula_by_id!Client.get_feedback_formula_by_id  sU     ,,!(+>@U"V!WX
 	++H5))<HMMO<<r>   )r  r+  c                  U Vs/ s H:  n[        U[        R                  5      (       a  UO[        R                  " S0 UD6PM<     nn[        R                  " UUUUb  [	        US5      OSUb  [	        US5      OSS9nU R                  SSS[        UR                  SS	95      0S
9n	[        R                  " U	5        [        R                  " S0 U	R                  5       D6$ s  snf )a.  Create a feedback formula.

Args:
    feedback_key (str):
        The feedback key for the formula.
    aggregation_type (Literal["sum", "avg"]):
        The aggregation type to use when combining parts.
    formula_parts (Sequence[FeedbackFormulaWeightedVariable | dict]):
        The weighted feedback keys included in the formula.
    dataset_id (Optional[Union[UUID, str]]):
        The dataset to scope the formula to.
    session_id (Optional[Union[UUID, str]]):
        The session to scope the formula to.

Returns:
    The created feedback formula.
Nr  r+  )r  aggregation_typeformula_partsr  r+  r  r  r  Tr  r$  r=   )rq   rb  FeedbackFormulaWeightedVariableFeedbackFormulaCreater{   r  r'  r   r;   r  r  r  )
r   r  r  r  r  r+  r  typed_partsr3  r  s
             r?   create_feedback_formulaClient.create_feedback_formula  s    @ &	I
 & $
 J JKK ;;CdCD &	 	 I
 22%-%6@6L\2RV 7A6L\2RV

 ,, GLLdL$CD - 
 	++H5))<HMMO<<3I
s   AC!c                  U Vs/ s H:  n[        U[        R                  5      (       a  UO[        R                  " S	0 UD6PM<     nn[        R                  " UUUS9nU R	                  SS[        US5       3S[        UR                  SS95      0S9n[        R                  " U5        [        R                  " S	0 UR                  5       D6$ s  snf )
a  Update a feedback formula.

Args:
    feedback_formula_id (Union[UUID, str]):
        The ID of the feedback formula to update.
    feedback_key (str):
        The feedback key for the formula.
    aggregation_type (Literal["sum", "avg"]):
        The aggregation type to use when combining parts.
    formula_parts (Sequence[FeedbackFormulaWeightedVariable | dict]):
        The weighted feedback keys included in the formula.

Returns:
    The updated feedback formula.
)r  r  r  r  r  r  r  Tr  r$  r=   )rq   rb  r  FeedbackFormulaUpdater  r{   r'  r   r;   r  r  r  )	r   r  r  r  r  r  r  r3  r  s	            r?   update_feedback_formulaClient.update_feedback_formula  s    : &	I
 & $
 J JKK ;;CdCD &	 	 I
 22%-%

 ,,!(+>@U"V!WXGLLdL$CD - 
 	++H5))<HMMO<<'I
s   ACc                n    U R                  SS[        US5       35      n[        R                  " U5        g)zDelete a feedback formula by ID.

Args:
    feedback_formula_id (Union[UUID, str]):
        The ID of the feedback formula to delete.
r  r  r  Nr  r{   r;   r  r  s      r?   delete_feedback_formulaClient.delete_feedback_formula  s;     ,,!(+>@U"V!WX
 	++H5r>   )	queue_idsr1  r  r  c          
   #  :  #    Ub.  [        U5       VVs/ s H  u  pV[        USU S35      PM     snnOSUUUb  [        US5      OSS.n[        U R                  SUS95       H-  u  pX[        R
                  " S	0 UD6v   Uc  M"  US-   U:  d  M-    g   gs  snnf 7f)
a  List the annotation queues on the LangSmith API.

Args:
    queue_ids (Optional[List[Union[UUID, str]]]):
        The IDs of the queues to filter by.
    name (Optional[str]):
        The name of the queue to filter by.
    name_contains (Optional[str]):
        The substring that the queue name should contain.
    limit (Optional[int]):
        The maximum number of queues to return.

Yields:
    The annotation queues.
Nz
queue_ids[r6  rU  )r  r1  r  r  /annotation-queuesr  r   r=   )r  r{   r  r  rb  AnnotationQueue)	r   r  r1  r  r  r  r  r  queues	            r?   list_annotation_queuesClient.list_annotation_queues  s     4 ( AJ)@TU@Tfa#A3a01@TU*(-(9S_s	
 "$$%9&$I
HA ,,    QUe^
 Vs   BBABBB)r+  queue_idrubric_instructionsc          
     V   UUUb  [        U5      O[        [        R                  " 5       5      US.nU R                  SSUR	                  5        VVs0 s H  u  pgUc  M
  Xg_M     snnS9n[
        R                  " U5        [        R                  " S0 UR                  5       D6$ s  snnf )a  Create an annotation queue on the LangSmith API.

Args:
    name (str):
        The name of the annotation queue.
    description (Optional[str]):
        The description of the annotation queue.
    queue_id (Optional[Union[UUID, str]]):
        The ID of the annotation queue.
    rubric_instructions (Optional[str]):
        The rubric instructions for the annotation queue.

Returns:
    AnnotationQueue: The created annotation queue object.
)r1  r+  r<  r  r  r  rB  r=   )
rt   rr   rD  r  r   r;   r  rb  AnnotationQueueWithDetailsr  )	r   r1  r+  r  r  r   rm  rn  r  s	            r?   create_annotation_queueClient.create_annotation_queue2  s    0 &#+#7#h-S=N#6	
 ,, #'::<A<411$!$<A - 

 	++H544 
mmo
 	
 Bs   	B%B%c                    S[        US5       3nU R                  SU U R                  S9n[        R                  " U5        [
        R                  " S0 UR                  5       D6$ )zRead an annotation queue with the specified `queue_id`.

Args:
    queue_id (Union[UUID, str]): The ID of the annotation queue to read.

Returns:
    AnnotationQueue: The annotation queue object.
/annotation-queues/r  r  r  r=   )r{   r  r  r;   r  rb  r  r  )r   r  base_urlr  s       r?   read_annotation_queueClient.read_annotation_queueY  sf     )(J)G(HI,,jMM - 

 	++H544Gx}}GGr>   )r+  r  c               t    U R                  SS[        US5       3UUUS.S9n[        R                  " U5        g)a  Update an annotation queue with the specified `queue_id`.

Args:
    queue_id (Union[UUID, str]): The ID of the annotation queue to update.
    name (str): The new name for the annotation queue.
    description (Optional[str]): The new description for the
        annotation queue.
    rubric_instructions (Optional[str]): The new rubric instructions for the
        annotation queue.

Returns:
    None
r8  r  r  )r1  r+  r  rB  Nr  )r   r  r1  r+  r  r  s         r?   update_annotation_queueClient.update_annotation_queuek  sL    * ,,!(8Z"@!AB*': - 
 	++H5r>   c                    U R                  SS[        US5       3SS0U R                  ES9n[        R                  " U5        g)zDelete an annotation queue with the specified `queue_id`.

Args:
    queue_id (Union[UUID, str]): The ID of the annotation queue to delete.

Returns:
    None
r  r  r  r  r  r  Nr  )r   r  r  s      r?   delete_annotation_queueClient.delete_annotation_queue  sP     ,,!(8Z"@!AB1CT]]C - 

 	++H5r>   c                   U R                  SS[        US5       S3[        U5       VVs/ s H  u  p4[        [        USU S35      5      PM      snnS9n[        R
                  " U5        gs  snnf )	a  Add runs to an annotation queue with the specified `queue_id`.

Args:
    queue_id (Union[UUID, str]): The ID of the annotation queue.
    run_ids (List[Union[UUID, str]]): The IDs of the runs to be added to the annotation
        queue.

Returns:
    None
r  r  r  r  zrun_ids[r6  rB  N)r  r{   r  rt   r;   r  )r   r  rh  r  r  r  s         r?   add_runs_to_annotation_queue#Client.add_runs_to_annotation_queue  su     ,,!(8Z"@!AGDMgDVWDV&!#hshqcO45DVW - 

 	++H5 Xs   %A,c          
         U R                  SS[        US5       S[        US5       35      n[        R                  " U5        g)a  Delete a run from an annotation queue with the specified `queue_id` and `run_id`.

Args:
    queue_id (Union[UUID, str]): The ID of the annotation queue.
    run_id (Union[UUID, str]): The ID of the run to be added to the annotation
        queue.

Returns:
    None
r  r  r  r9  r)  Nr  )r   r  r)  r  s       r?    delete_run_from_annotation_queue'Client.delete_run_from_annotation_queue  sI     ,,!(8Z"@!AQWYaHbGcd
 	++H5r>   c                   S[        US5       S3nU R                  SU SU 3U R                  S9n[        R                  " U5        [
        R                  " S0 UR                  5       D6$ )a  Get a run from an annotation queue at the specified index.

Args:
    queue_id (Union[UUID, str]): The ID of the annotation queue.
    index (int): The index of the run to retrieve.

Returns:
    RunWithAnnotationQueueInfo: The run at the specified index.

Raises:
    LangSmithNotFoundError: If the run is not found at the given index.
    LangSmithError: For other API-related errors.
r  r  r  r  rn   r  r=   )r{   r  r  r;   r  rb  RunWithAnnotationQueueInfor  )r   r  r.  r  r  s        r?   get_run_from_annotation_queue$Client.get_run_from_annotation_queue  sq      )(J)G(HM,,j%!MM - 

 	++H544Gx}}GGr>   )r  r+  rl  r   r<  c               |   U(       d  [        S5      eUc  U R                  US   S9R                  nU(       d  [        S5      eU=(       d    [        [        R
                  " 5       5      UUUUU=(       d7    [        R                  R                  [        R                  R                  5      0 S.nUb  XhS   S'   [        UR                  5        V	V
s0 s H  u  pX_M	     sn
n	5      nU R                  SS	S
U0S9n[        R                  " U5        UR                  5       n[         R"                  " S0 UD6$ s  sn
n	f )a-  Create a comparative experiment on the LangSmith API.

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

Args:
    name (str): The name of the comparative experiment.
    experiments (Sequence[Union[UUID, str]]): The IDs of the experiments to compare.
    reference_dataset (Optional[Union[UUID, str]]): The ID of the dataset these experiments are compared on.
    description (Optional[str]): The description of the comparative experiment.
    created_at (Optional[datetime.datetime]): The creation time of the comparative experiment.
    metadata (Optional[Dict[str, Any]]): Additional metadata for the comparative experiment.
    id (Optional[Union[UUID, str]]): The ID of the comparative experiment.

Returns:
    ComparativeExperiment: The created comparative experiment object.
z$At least one experiment is required.r   r  z A reference dataset is required.)r<  r1  experiment_idsr  r+  rl  rP  rP  r   r  z/datasets/comparativer  r$  r=   )ru   r}  r  rt   rr   rD  r[  r\  r]  r^  r'  r   r  r;   r  r  rb  ComparativeExperiment)r   r1  experimentsr  r+  rl  r   r<  r   rm  rn  serr  
response_ds                 r?   create_comparative_experiment$Client.create_comparative_experiment  s-   6 CDD$ $ 1 1&q> !2 !""  !?@@)DJJL))$5&$T(9(9(=(=h>O>O>S>S(T 
 (0M*%DJJL9LDA14L9:,,# - 
 	++H5]]_
//=*== :s   D8
c                X    U R                  5       nUS:H  =(       d    UR                  U:H  $ )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.
-)r  tenant_handle)r   ownersettingss      r?   _current_tenant_is_ownerClient._current_tenant_is_owner  s,     %%'|>x55>>r>   c                p    [         R                  " SU SU R                  5       R                   SU 35      $ )NzCannot z% for another tenant.
Current tenant: z,
Requested tenant: )r;   r|   r  r  )r   actionr  s      r?   _owner_conflict_errorClient._owner_conflict_error"  sH     **fX #113AAB C!!&)
 	
r>   c                x    U R                  SSU S3X#S.S9nUR                  5       S   nU(       a  US   S   $ S	$ )
ag  Get the latest commit hash for a prompt.

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

Returns:
    Optional[str]: The latest commit hash, or None if no commits are found.
r  	/commits/rn   )r  r  r  commitsr   commit_hashN)r  r  )r   prompt_owner_and_namer  r  r  r  s         r?   _get_latest_commit_hashClient._get_latest_commit_hash+  sX     ,,-.a0"5 - 

 --/),,3wqz-(==r>   c                    [         R                  " U5      u  p4nU R                  SSU SU 3SU0S9nUR                  5         UR	                  5       $ )aR  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/rn   likerB  )r;   parse_prompt_identifierr  raise_for_statusr  )r   prompt_identifierr  r  prompt_namer.  r  s          r?   _like_or_unlike_promptClient._like_or_unlike_prompt@  sa      !) @ @AR SA,,geWAk]364. - 
 	!!#}}r>   c           	         [         R                  " U5      u  p#nU R                  U5      (       d  U R                   SU SU SUSS  3$ U R	                  5       nU R                   SU SUSS  SUR
                   3$ )zGet a URL for a prompt.

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

Returns:
    str: The URL for the prompt.

z/hub/rn   r   N   z	/prompts/z?organizationId=)r;   r   r  r  r  r<  )r   r"  r  r#  r  r  s         r?   _get_prompt_urlClient._get_prompt_urlW  s     +3*J*J+
'K ,,U33nn%U5';-qRa@QRR%%'~~i}Ak"1o5Fx{{m-	
r>   c                :    U R                  U5      nU(       a  S$ 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"  r   s      r?   _prompt_existsClient._prompt_existsn  s      !23t(5(r>   c                "    U R                  USS9$ )zLike a prompt.

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

Returns:
    Dict[str, int]: A dictionary with the key 'likes' and the count of likes as the value.

Tr  r$  r   r"  s     r?   like_promptClient.like_promptz  s     **+<4*HHr>   c                "    U R                  USS9$ )zUnlike a prompt.

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

Returns:
    Dict[str, int]: A dictionary with the key 'likes' and the count of likes as the value.

Fr/  r0  r1  s     r?   unlike_promptClient.unlike_prompt  s     **+<5*IIr>   rU  desc)r  r  	is_publicis_archived
sort_fieldsort_directionrd  c          	         UUU(       a  SOUb  SOSU(       a  SOSUUUU(       a  SOSS.nU R                  SSUS9n	[        R                  " S0 U	R                  5       D6$ )	a  List prompts with pagination.

Args:
    limit (int, default=100): The maximum number of prompts to return. Defaults to 100.
    offset (int, default=0): 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 (PromptSortField): The field to sort by.
        Defaults to "updated_at".
    sort_direction (Literal["desc", "asc"], default="desc"): The order to sort by.
        Defaults to "desc".
    query (Optional[str]): Filter prompts by a search query.

Returns:
    ListPromptsResponse: A response object containing
    the list of prompts.
rP  Nfalse)r  r  r8  r9  r:  r;  rd  match_prefixr  /repos/r  r=   )r  rb  ListPromptsResponser  )
r   r  r  r8  r9  r:  r;  rd  r  r  s
             r?   list_promptsClient.list_prompts  si    : #I4It%06g$,&+F
 ,,UIf,M--@@@r>   c                    [         R                  " U5      u  p#n U R                  SSU SU 35      n[        R                  " S0 UR                  5       S   D6$ ! [         R                   a     gf = f)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[Prompt]: The prompt object.

Raises:
    requests.exceptions.HTTPError: If the prompt is not found or
        another error occurs.
r  r?  rn   repoNr=   )r;   r   r  rb  Promptr  r  r   r"  r  r#  r.  r  s         r?   r+  Client.get_prompt  su     !) @ @AR SA	00'%+8WXH$$?x}}v'>??.. 		s   >A A10A1r+  readmer&  r8  c                  U R                  5       nU(       a'  UR                  (       d  [        R                  " S5      e[        R                  " U5      u  pxn	U R                  US9(       d  U R                  SU5      eUU=(       d    SU=(       d    SU=(       d    / US.n
U R                  SSU
S9nUR                  5         [        R                  " S
0 UR                  5       S	   D6$ )a  Create a new prompt.

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

Args:
    prompt_identifier (str): The identifier of the prompt.
        The identifier should be in the formatof owner/name:hash, name:hash, owner/name, or name
    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.

Returns:
    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+  rI  r&  r8  r  r?  rB  rD  r=   )r  r  r;   r|   r   r  r  r  r!  rb  rE  r  )r   r"  r+  rI  r&  r8  r  r  r#  r.  r  r  s               r?   create_promptClient.create_prompt  s    8 %%'X33--6  !) @ @AR SA,,5,9,,->FF '&,"lJB"<
 ,,VYT,J!!#  ;8==?6#:;;r>   parent_commit_hashc                  U R                  U5      (       d  [        R                  " S5      e SSKJn  U" [        U5      5      n[        R                  " U5      n[        R                  " U5      u  pxn	U SU 3n
US:X  d  Uc  U R                  U
5      nX6S.nU R                  SS	U
 3US
9nUR                  5       S   S   nU R                  U
 SU 35      $ ! [
         a    [        S5      ef = f)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   )r  vThe client.create_commit function requires the langchain-corepackage to run.
Install with `pip install langchain-core`rn   r	  )parent_commitmanifestr  r  rB  commitr  r   )r,  r;   r  langchain_core.loadr  rL   prep_obj_for_pushr  r  r   r  r  r(  )r   r"  r  rP  r  json_objectmanifest_dictr  r#  r.  r  request_dictr  r  s                 r?   create_commitClient.create_commit  s!   , ""#45511B 	1 -f56

;/ ( @ @AR SA#(';- 8)-?-G!%!=!=>S!T);W,,i 567l - 
 mmoh/>##'<&=Q{m$LMM+  	M 	s   C C/)r+  rI  r&  r8  r9  c               R   U R                  5       nU(       a  UR                  (       d  [        S5      e0 nUb  X(S'   Ub  X8S'   Ub  XXS'   Ub  XhS'   Ub  XHS'   [        R                  " U5      u  pnU R                  SSU	 S	U
 3US
9nUR                  5         UR                  5       $ )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.
rK  r+  rI  r8  r9  r&  r8  r?  rn   rB  )r  r  ru   r;   r   r  r!  r  )r   r"  r+  rI  r&  r8  r9  r  r  r  r#  r.  r  s                r?   update_promptClient.update_prompt<  s    : %%'X336  <>""-#N  )""-L ( @ @AR SA,,wugQ{m44 - 
 	!!#}}r>   c                    [         R                  " U5      u  p#nU R                  U5      (       d  U R                  SU5      eU R	                  SSU SU 35      nUR                  5         g)zDelete 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?  rn   N)r;   r   r  r  r  r!  rF  s         r?   delete_promptClient.delete_promptv  sj     !) @ @AR SA,,U33,,->FF,,Xq7VW!!#r>   include_modelc          
         [         R                  " U5      u  p4nU R                  SSU SU SU U(       a  SOS 35      n[        R                  " S0 X4S.UR                  5       ED6$ )zPull a prompt object from the LangSmith API.

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

Returns:
    PromptCommit: The prompt object.

Raises:
    ValueError: If no commits are found for the prompt.
r  r  rn   z?include_model=truer  r  rD  r=   )r;   r   r  rb  PromptCommitr  )r   r"  rd  r  r#  r  r  s          r?   pull_prompt_commitClient.pull_prompt_commit  s    " +3*J*J+
'K ,,E7!K=+,9(rBD
 && 
FhmmoF
 	
r>   r  r  rd  c             #  |  #    [         R                  " U5      u  pVnUb  [        SU5      OUUUS.nSn	 X8S'   U R                  SSU SU S3US	9n
U
R	                  5       nUS
   nUS   nU(       d  gU H.  nUb  X:  a    g[
        R                  " S0 XVS.UED6v   U	S-  n	M0     U[        U5      -  nX=:  a  gM  7f)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]): The maximum number of commits to return. If None, returns all commits.
    offset (int, default=0): The number of commits to skip before starting to return results.
    include_model (bool, default=False): Whether to include the model information in the commit data.

Yields:
    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.
NrU  rj  r   r  r  r  rn   r  r  r   rf  r   r=   )r;   r   r  r  r  rb  ListedPromptCommitrz   )r   r"  r  r  rd  r  r#  r.  r  r  r  valr   r   its                  r?   list_prompt_commitsClient.list_prompt_commits  s    0 !) @ @AR SA ).(9Se_u*

 %800E7!K=2 1 H
 --/C	NELE$ 33  %AbA  Q  c%j F/ s   B:B<c          	     t    SSK Jn  SSKJn  SSKJn  SSKJn  SSKJ	n  SSK
JnJn	   SS	KJn
  U R%                  XS9nU
" 5          U" [&        R(                  " UR*                  5      5      nSSS5        [-        WU5      (       d+  [-        X5      (       a  [-        UR.                  U5      (       a  [-        X5      (       a  UO8[-        X5      (       a'  [-        UR.                  U5      (       a  UR.                  OSnUc  [0        R2                  " S5      eUR4                  c  0 Ul        UR4                  R7                  UR8                  UR:                  UR<                  S.5        U(       Gay  [-        X5      (       Gah  [-        UR.                  U5      (       GaL  [?        UR@                  5      S:X  Ga2  [-        URB                  U5      (       Gd  [-        URB                  U5      (       a  [-        URB                  RD                  U5      (       a  [G        XR.                  URB                  RD                  -  5      n[?        UR@                  5      S:X  aU  UR@                  S   nU	" UR.                  URH                  " S0 0 URB                  RJ                  ED6URB                  5      nU$ Un U$ [-        URB                  U5      (       a  UR.                  URB                  -  nU$  U$ ! [         a    [        S5      ef = f! [         a    [         R"                  S
 5       n
 GNf = f! , (       d  f       GN= f)aZ  Pull a prompt and return it as a LangChain `PromptTemplate`.

This method requires [`langchain-core`](https://pypi.org/project/langchain-core).

Args:
    prompt_identifier: The identifier of the prompt.
    include_model: Whether to include the model information in the prompt data.

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     #    S v   g 7fr   r=   r=   r>   r?   rz  ;Client.pull_prompt.<locals>.suppress_langchain_beta_warning  s     s   rc  Nz-Prompt object is not a valid prompt template.)lc_hub_ownerlc_hub_repolc_hub_commit_hashr  r   r   r=   )&#langchain_core.language_models.baserr  langchain_core.load.loadr  langchain_core.output_parsersrs  langchain_core.promptsrt  !langchain_core.prompts.structuredrv  langchain_core.runnables.baserx  ry  rL   langchain_core._apirz  
contextlibcontextmanagerrh  r  r  rT  rq   firstr;   r  r   r  r  rD  r  rz   stepslastboundr   bindr  )r   r"  rd  rr  r  rs  rt  rv  rx  ry  rz  prompt_objectr   prompt_templateseqrebound_llms                   r?   pull_promptClient.pull_prompt  s   	M6FAJW	K // 0 
 -.4::m&<&<=>F / v122&336<<);<< f99  "&;;"6<<1CDD LL   &--C  ''/+-($$++$1$7$7#0#5#5*7*C*C 6446<<)9:: FLL!Q&z&++GW/X/X &++77J!!#4= = +\\FKK<M<M-MNsyy>Q&"%))A,K-#((B+Afkk.@.@+ABF  !F  FKK):;;+1<<&+++E  _  	M 	  	&& '	 /.s(   &K( L 'L((K> L%$L%(
L7)r  rP  r8  r+  rI  r&  c                  U R                  U5      (       a-  [        S XEXg4 5       5      (       a  U R                  UUUUUS9  OU R                  UUb  UOSUUUS9  Uc  U R	                  US9$ U R                  UUUS9nU$ )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  (   #    U  H  oS Lv   M
     g 7fr   r=   )r  params     r?   r  %Client.push_prompt.<locals>.<genexpr>n  s      /UeT!/Us   rH  F)r8  r+  rI  r&  )r"  rO  )r,  anyr^  rM  r(  r[  )	r   r"  r  rP  r8  r+  rI  r&  r   s	            r?   push_promptClient.push_promptG  s    L 011 09/U   ""% +!' #  !'0'<)%'   >'':K'LL   1 ! 

 
r>   c                    SU l         g)z2Manually trigger cleanup of the background thread.TN)r$  r  s    r?   cleanupClient.cleanup  s
    #r>   c                   g r   r=   r   rJ  r  
evaluatorssummary_evaluatorsr   experiment_prefixr+  r  num_repetitionsblocking
experimentupload_resultsr  s                 r?   evaluateClient.evaluate  s    "  r>   c                   g r   r=   r  s                 r?   r  r    s    " (+r>   c               <    SSK Jn  U" U4UUUUUUUU	U U
UUUS.UD6$ )a6  Evaluate a target system on a given dataset.

Args:
    target (Union[TARGET_T, Runnable, EXPERIMENT_T, Tuple[EXPERIMENT_T, EXPERIMENT_T]]):
        The target system or experiment(s) to evaluate.

        Can be a function that takes a `dict` and returns a `dict`, a langchain `Runnable`, an
        existing experiment ID, or a two-tuple of experiment IDs.
    data (DATA_T): The dataset to evaluate on.

        Can be a dataset name, a list of examples, or a generator of examples.
    evaluators (Optional[Union[Sequence[EVALUATOR_T], Sequence[COMPARATIVE_EVALUATOR_T]]]):
        A list of evaluators to run on each example. The evaluator signature
        depends on the target type. Default to None.
    summary_evaluators (Optional[Sequence[SUMMARY_EVALUATOR_T]]): A list of summary
        evaluators to run on the entire dataset. Should not be specified if
        comparing two existing experiments.
    metadata (Optional[dict]): Metadata to attach to the experiment.
    experiment_prefix (Optional[str]): A prefix to provide for your experiment name.
    description (Optional[str]): A free-form text description for the experiment.
    max_concurrency (Optional[int], default=0): The maximum number of concurrent
        evaluations to run.

        If `None` then no limit is set. If `0` then no concurrency.
    blocking (bool, default=True): Whether to block until the evaluation is complete.
    num_repetitions (int, default=1): The number of times to run the evaluation.
        Each item in the dataset will be run and evaluated this many times.
        Defaults to 1.
    experiment (Optional[EXPERIMENT_T]): An existing experiment to
        extend.

        If provided, `experiment_prefix` is ignored.

        For advanced usage only. Should not be specified if target is an existing experiment or
        two-tuple fo experiments.
    upload_results (bool, default=True): Whether to upload the results to LangSmith.
    error_handling (str, default="log"): How to handle individual run errors.

        `'log'` will trace the runs with the error message as part of the
        experiment, `'ignore'` will not count the run as part of the experiment at
        all.
    **kwargs (Any): Additional keyword arguments to pass to the evaluator.

Returns:
    ExperimentResults: If target is a function, Runnable, or existing experiment.
    ComparativeExperimentResults: If target is a two-tuple of existing experiments.

Examples:
    Prepare the dataset:

    ```python
    from langsmith import Client

    client = Client()
    dataset = client.clone_public_dataset(
        "https://smith.langchain.com/public/419dcab2-1d66-4b94-8901-0357ead390df/d"
    )
    dataset_name = "Evaluate Examples"
    ```

    Basic usage:

    ```python
    def accuracy(outputs: dict, reference_outputs: dict) -> dict:
        # Row-level evaluator for accuracy.
        pred = outputs["response"]
        expected = reference_outputs["answer"]
        return {"score": expected.lower() == pred.lower()}
    ```

    ```python
    def precision(outputs: list[dict], reference_outputs: list[dict]) -> dict:
        # Experiment-level evaluator for precision.
        # TP / (TP + FP)
        predictions = [out["response"].lower() for out in outputs]
        expected = [ref["answer"].lower() for ref in reference_outputs]
        # yes and no are the only possible answers
        tp = sum([p == e for p, e in zip(predictions, expected) if p == "yes"])
        fp = sum([p == "yes" and e == "no" for p, e in zip(predictions, expected)])
        return {"score": tp / (tp + fp)}


    def predict(inputs: dict) -> dict:
        # This can be any function or just an API call to your app.
        return {"response": "Yes"}


    results = client.evaluate(
        predict,
        data=dataset_name,
        evaluators=[accuracy],
        summary_evaluators=[precision],
        experiment_prefix="My Experiment",
        description="Evaluating the accuracy of a simple prediction model.",
        metadata={
            "my-prompt-version": "abcd-1234",
        },
    )
    ```

    Evaluating over only a subset of the examples

    ```python
    experiment_name = results.experiment_name
    examples = client.list_examples(dataset_name=dataset_name, limit=5)
    results = client.evaluate(
        predict,
        data=examples,
        evaluators=[accuracy],
        summary_evaluators=[precision],
        experiment_prefix="My Experiment",
        description="Just testing a subset synchronously.",
    )
    ```

    Streaming each prediction to more easily + eagerly debug.

    ```python
    results = client.evaluate(
        predict,
        data=dataset_name,
        evaluators=[accuracy],
        summary_evaluators=[precision],
        description="I don't even have to block!",
        blocking=False,
    )
    for i, result in enumerate(results):  # doctest: +ELLIPSIS
        pass
    ```


    View the evaluation results for experiment:...
    Evaluating a LangChain object:

    ```python
    from langchain_core.runnables import chain as as_runnable


    @as_runnable
    def nested_predict(inputs):
        return {"response": "Yes"}


    @as_runnable
    def lc_predict(inputs):
        return nested_predict.invoke(inputs)


    results = client.evaluate(
        lc_predict,
        data=dataset_name,
        evaluators=[accuracy],
        description="This time we're evaluating a LangChain object.",
        summary_evaluators=[precision],
    )
    ```

    Comparative evaluation:

    ```python
    results = client.evaluate(
        # The target is a tuple of the experiment IDs to compare
        target=(
            "12345678-1234-1234-1234-123456789012",
            "98765432-1234-1234-1234-123456789012",
        ),
        evaluators=[accuracy],
        summary_evaluators=[precision],
    )
    ```

    Evaluate an existing experiment:

    ```python
    results = client.evaluate(
        # The target is the ID of the experiment we are evaluating
        target="12345678-1234-1234-1234-123456789012",
        evaluators=[accuracy],
        summary_evaluators=[precision],
    )
    ```

!!! version-added "Added in `langsmith` 0.2.0"
r   )r  r  r  r  r   r  r+  r  r  clientr  r  r  error_handling)langsmith.evaluation._runnerr  )r   rJ  r  r  r  r   r  r+  r  r  r  r  r  r  r  	evaluate_s                   r?   r  r    sQ    \ 	G 
!1/#++!))
 
 	
r>   c               X   #    SSK Jn  U" U4UUUUUUUU	U U
UUUS.UD6I Sh  vN $  N7f)aY  Evaluate an async target system on a given dataset.

Args:
    target (Union[ATARGET_T, AsyncIterable[dict], Runnable, str, uuid.UUID, TracerSession]):
        The target system or experiment(s) to evaluate.

        Can be an async function that takes a `dict` and returns a `dict`, a langchain `Runnable`, an
        existing experiment ID, or a two-tuple of experiment IDs.
    data (Union[DATA_T, AsyncIterable[Example]]): The dataset to evaluate on.

        Can be a dataset name, a list of examples, an async generator of examples, or an async iterable of examples.
    evaluators (Optional[Sequence[EVALUATOR_T]]): A list of evaluators to run
        on each example.
    summary_evaluators (Optional[Sequence[SUMMARY_EVALUATOR_T]]): A list of summary
        evaluators to run on the entire dataset.
    metadata (Optional[dict]): Metadata to attach to the experiment.
    experiment_prefix (Optional[str]): A prefix to provide for your experiment name.
    description (Optional[str]): A description of the experiment.
    max_concurrency (Optional[int], default=0): The maximum number of concurrent
        evaluations to run.

        If `None` then no limit is set. If `0` then no concurrency.
    num_repetitions (int, default=1): The number of times to run the evaluation.
        Each item in the dataset will be run and evaluated this many times.
        Defaults to 1.
    blocking (bool, default=True): Whether to block until the evaluation is complete.
    experiment (Optional[TracerSession]): An existing experiment to
        extend.

        If provided, `experiment_prefix` is ignored.

        For advanced usage only.
    upload_results (bool, default=True): Whether to upload the results to LangSmith.
    error_handling (str, default="log"): How to handle individual run errors.

        `'log'` will trace the runs with the error message as part of the
        experiment, `'ignore'` will not count the run as part of the experiment at
        all.
    **kwargs (Any): Additional keyword arguments to pass to the evaluator.

Returns:
    An async iterator over the experiment results.

Environment:
    - `LANGSMITH_TEST_CACHE`: If set, API calls will be cached to disk to save time and
        cost during testing.

        Recommended to commit the cache files to your repository for faster CI/CD runs.

        Requires the `'langsmith[vcr]'` package to be installed.

Examples:
    Prepare the dataset:

    ```python
    import asyncio
    from langsmith import Client

    client = Client()
    dataset = client.clone_public_dataset(
        "https://smith.langchain.com/public/419dcab2-1d66-4b94-8901-0357ead390df/d"
    )
    dataset_name = "Evaluate Examples"
    ```

    Basic usage:

    ```python
    def accuracy(outputs: dict, reference_outputs: dict) -> dict:
        # Row-level evaluator for accuracy.
        pred = outputs["resposen"]
        expected = reference_outputs["answer"]
        return {"score": expected.lower() == pred.lower()}


    def precision(outputs: list[dict], reference_outputs: list[dict]) -> dict:
        # Experiment-level evaluator for precision.
        # TP / (TP + FP)
        predictions = [out["response"].lower() for out in outputs]
        expected = [ref["answer"].lower() for ref in reference_outputs]
        # yes and no are the only possible answers
        tp = sum([p == e for p, e in zip(predictions, expected) if p == "yes"])
        fp = sum([p == "yes" and e == "no" for p, e in zip(predictions, expected)])
        return {"score": tp / (tp + fp)}


    async def apredict(inputs: dict) -> dict:
        # This can be any async function or just an API call to your app.
        await asyncio.sleep(0.1)
        return {"response": "Yes"}


    results = asyncio.run(
        client.aevaluate(
            apredict,
            data=dataset_name,
            evaluators=[accuracy],
            summary_evaluators=[precision],
            experiment_prefix="My Experiment",
            description="Evaluate the accuracy of the model asynchronously.",
            metadata={
                "my-prompt-version": "abcd-1234",
            },
        )
    )
    ```

    Evaluating over only a subset of the examples using an async generator:

    ```python
    async def example_generator():
        examples = client.list_examples(dataset_name=dataset_name, limit=5)
        for example in examples:
            yield example


    results = asyncio.run(
        client.aevaluate(
            apredict,
            data=example_generator(),
            evaluators=[accuracy],
            summary_evaluators=[precision],
            experiment_prefix="My Subset Experiment",
            description="Evaluate a subset of examples asynchronously.",
        )
    )
    ```

    Streaming each prediction to more easily + eagerly debug.

    ```python
    results = asyncio.run(
        client.aevaluate(
            apredict,
            data=dataset_name,
            evaluators=[accuracy],
            summary_evaluators=[precision],
            experiment_prefix="My Streaming Experiment",
            description="Streaming predictions for debugging.",
            blocking=False,
        )
    )


    async def aenumerate(iterable):
        async for elem in iterable:
            print(elem)


    asyncio.run(aenumerate(results))
    ```

    Running without concurrency:

    ```python
    results = asyncio.run(
        client.aevaluate(
            apredict,
            data=dataset_name,
            evaluators=[accuracy],
            summary_evaluators=[precision],
            experiment_prefix="My Experiment Without Concurrency",
            description="This was run without concurrency.",
            max_concurrency=0,
        )
    )
    ```

    Using Async evaluators:

    ```python
    async def helpfulness(outputs: dict) -> dict:
        # Row-level evaluator for helpfulness.
        await asyncio.sleep(5)  # Replace with your LLM API call
        return {"score": outputs["output"] == "Yes"}


    results = asyncio.run(
        client.aevaluate(
            apredict,
            data=dataset_name,
            evaluators=[helpfulness],
            summary_evaluators=[precision],
            experiment_prefix="My Helpful Experiment",
            description="Applying async evaluators example.",
        )
    )
    ```

    Evaluate an existing experiment:

    ```python
    results = asyncio.run(
        client.aevaluate(
            # The target is the ID of the experiment we are evaluating
            target="419dcab2-1d66-4b94-8901-0357ead390df",
            evaluators=[accuracy, helpfulness],
            summary_evaluators=[precision],
        )
    )
    ```

!!! version-added "Added in `langsmith` 0.2.0"
r   )	aevaluater  N)langsmith.evaluation._arunnerr  )r   rJ  r  r  r  r   r  r+  r  r  r  r  r  r  r  
aevaluate_s                   r?   r  Client.aevaluate   s\     N 	J
!1/#++!))
 
 
 	
 
s   !*(*c              #    #    SnSn U(       a  Xh-
  OSn	U	(       a  [        SU	5      OSn
U/UU
UUUS.nU R                  SSU S3S[        U5      0S	9nUR                  5       nU(       d  gU Vs/ s H  n[        R
                  " S
0 UD6PM     nnUv   U[        U5      -  n[        U5      U
:  d  U(       a  X:  a  gU[        U5      -  nM  s  snf 7f)a  Paginate through examples with runs and yield batches.

Args:
    dataset_id: Dataset UUID to fetch examples with runs
    session_id: Session UUID to filter runs by, same as project_id
    preview: Whether to return preview data only
    comparative_experiment_id: Optional comparative experiment UUID
    filters: Optional filters to apply
    limit: Maximum total number of results to return

Yields:
    Batches of run results as lists of ExampleWithRuns instances
r   NrU  )session_idsr  r  previewr~  filtersr  r  r  r  r$  r=   )r  r  r'  r  rb  r6   rz   )r   r  r+  r  r~  r  r  r  results_count	remainingbatch_limitr   r  r  rJ  examples_batchs                   r?   _paginate_examples_with_runs#Client._paginate_examples_with_runs!  s     , 38.dI1:#c9-K !+| $"-F"D 00ZL. &D(9: 1 H MMOE RWWQVvj88B6BQVNW  SZ'M5zK'Em6Lc%j F? 0 Xs   A.C0 CACc                8  ^ ^^^^^
 T R                  XSS9m
T
(       d  [        SU S35      eUUUUU
U 4S jnT
R                  T
R                  T
R                  T
R
                  T
R                  T
R                  T
R                  T
R                  T
R                  T
R                  T
R                  T
R                  T
R                  T
R                  S.n0 T
R                   =(       d    0 ET
R"                  =(       d    0 En	[$        R&                  " U	UU" 5       S9$ )a  Get results for an experiment, including experiment session aggregated stats and experiment runs for each dataset example.

Experiment results may not be available immediately after the experiment is created.

Args:
    name: The experiment name.
    project_id: Experiment's tracing project id, also called session_id, can be found in the url of the LS experiment page
    preview: Whether to return lightweight preview data only. When True,
        fetches inputs_preview/outputs_preview summaries instead of full inputs/outputs from S3 storage.
        Faster and less bandwidth.
    comparative_experiment_id: Optional comparative experiment UUID for pairwise comparison experiment results.
    filters: Optional filters to apply to results
    limit: Maximum number of results to return

Returns:
    ExperimentResults with:
        - feedback_stats: Combined feedback statistics including session-level feedback
        - run_stats: Aggregated run statistics (latency, tokens, cost, etc.)
        - examples_with_runs: Iterator of ExampleWithRuns

Raises:
    ValueError: If project not found for the given session_id

Example:
    ```python
    client = Client()
    results = client.get_experiment_results(
        project_id="037ae90f-f297-4926-b93c-37d8abf6899f",
    )
    for example_with_runs in results["examples_with_runs"]:
        print(example_with_runs.dict())

    # Access aggregated experiment statistics
    print(f"Total runs: {results['run_stats']['run_count']}")
    print(f"Total cost: {results['run_stats']['total_cost']}")
    print(f"P50 latency: {results['run_stats']['latency_p50']}")

    # Access feedback statistics
    print(f"Feedback stats: {results['feedback_stats']}")
    ```
T)r~  rc  r  z&No experiment found with project_id: 'r   c            	   3     >#    TR                  TR                  TR                  TTTTS9 H  n U  Sh  vN   M     g N	7f)z2Yield examples with corresponding experiment runs.)r  r+  r  r~  r  r  N)r  r  r<  )r  r~  r  r  r  r  r   s    r?    _get_examples_with_runs_iteratorGClient.get_experiment_results.<locals>._get_examples_with_runs_iterator"  sL     ::"77"::*C ;  !   !s   1A >
A )	run_countlatency_p50latency_p99rv  rs  rn  last_run_start_time
run_facetsru  rr  rm  first_token_p50first_token_p99
error_rate)ro  	run_statsexamples_with_runs)r}  ru   r  r  r  rv  rs  rn  r  r  ru  rr  rm  r  r  r  ro  session_feedback_statsrb  ri   )r   r1  rc  r  r~  r  r  r  r  ro  r  s   `  ````   @r?   get_experiment_resultsClient.get_experiment_results!  s   d ##D $ 
 Ej\QRSTT
	! 
	! !**".."..#00$22!(!:!:#*#>#>!,,!,,"..&66&66&66!,,4
	 
%%+
--3
 ++)?A
 	
r>   )instructionsr1  modelopenai_api_keyanthropic_api_keyc                  U R                  UUUS9nU R                  X5      nUSUS.SUS.nU R                  SSUR                   S3US	9n	[        R
                  " U	5        U	R                  5       n
[        R                  " S0 U
DUR                  U R                  5       U R                  S
.D6n[        SUR                   35        U$ )aj  Generate Insights over your agent chat histories.

!!! note

    - Only available to Plus and higher tier LangSmith users.
    - Insights Agent uses user's model API key. The cost of the report
        grows linearly with the number of chat histories you upload and the
        size of each history. For more see [insights](https://docs.langchain.com/langsmith/insights).
    - This method will upload your chat histories as traces to LangSmith.
    - If you pass in a model API key this will be set as a workspace secret
        meaning it will be usedin for evaluators and the playground.

Args:
    chat_histories: A list of chat histories. Each chat history should be a
        list of messages. We recommend formatting these as OpenAI messages with
        a "role" and "content" key. Max length 1000 items.
    instructions: Instructions for the Insights agent. Should focus on what
        your agent does and what types of insights you
        want to generate.
    name: Name for the generated Insights report.
    model: Whether to use OpenAI or Anthropic models. This will impact the
        cost of generating the Insights Report.
    openai_api_key: OpenAI API key to use. Only needed if you have not already
        stored this in LangSmith as a workspace secret.
    anthropic_api_key: Anthropic API key to use. Only needed if you have not
        already stored this in LangSmith as a workspace secret.

Example:
    ```python
    import os
    from langsmith import Client

    client = client()

    chat_histories = [
        [
            {"role": "user", "content": "how are you"},
            {"role": "assistant", "content": "good!"},
        ],
        [
            {"role": "user", "content": "do you like art"},
            {"role": "assistant", "content": "only Tarkovsky"},
        ],
    ]

    report = client.generate_insights(
        chat_histories=chat_histories,
        name="Conversation Topics",
        instructions="What are the high-level topics of conversations users are having with the assistant?",
        openai_api_key=os.environ["OPENAI_API_KEY"],
    )

    # client.poll_insights(report=report)
    ```
r  r  r  zxThe run.outputs.messages field contains a chat history between the user and the agent. This is all the context you need.)z%How are your agent traces structured?z.What would you like to learn about your agent?r   )r1  user_contextlast_n_hoursr  r  r  z	/insightsrB  rc  r  host_urlzThe Insights Agent is running! This can take up to 30 minutes to complete. Once the report is completed, you'll be able to see results here: r=   )_ensure_insights_api_key_ingest_insights_runsr  r<  r;   r  r  rb  InsightsReportr  r  printr  )r   chat_historiesr  r1  r  r  r  r  r   r  rw  reports               r?   generate_insightsClient.generate_insights."  s    D --)/ . 

 ,,^B :tBN 
 ,,jI6V - 
 	++H5mmo** 

zz))+^^	
 	R{{m	

 r>   r  i  )r  r<  rc  rater  verbosec          	        U(       a  U(       d  U(       d  [        S5      eU(       d  U(       a  U(       a  [        S5      eU(       a  UR                  nUR                  n[        SXT-  5      n[	        U5       H  nU R                  SSU SU 35      n	[        R                  " U	5        U	R                  5       n
U
S   S:X  aN  [        R                  " S0 U
DUU R                  5       U R                  S	.D6n[        S
UR                  5        Us  $ U
S   S:X  a  [        SU
S    35      eU(       a  [        SX-   35        [        R                   " U5        M     [#        S5      e)zPoll the status of an Insights report.

Args:
    report: THe InsightsReport.
    id: The Insights report ID. Should only specify if 'report' is not specified.
    project_id: The Tracing project ID. Should only specify if 'report' is not specified.
z1Must specify ('id' and 'project_id') or 'report'.z@Must specify exactly one of ('id' and 'project_id') or 'report'.r   r  r  z
/insights/rt  successr  z1Insights report completed! View the results at %sr  zFailed to generate insights: zPolling time: zInsights still pendingr=   )ru   r<  rc  r  r  r  r;   r  r  rb  r  r  r  r  r  rr  r  TimeoutError)r   r  r<  rc  r  r  r  	max_triesr  r  	resp_jsonjobs               r?   poll_insightsClient.poll_insights"  sP   $ 
vPQQJFR  B**J7?+	y!A00J<z">H //9 I"i/ // )"113!^^	 GHH 
8$/ #@7AS@T!UVVqxj12JJt- ". 344r>   r  c                  U R                  SS5      n[        R                  " U5        UR                  5        Vs1 s H  oUR	                  S5      iM     nn[        5       nUS;   a  UR                  [        5        US;   a  UR                  [        5        UR                  U5      =n(       a  [        U;   a  S$ S$ US:X  a	  Un	[        n
OGUS:X  a	  Un	[        n
O8U(       d  U(       a  U=(       d    Un	U(       a  [        O[        n
O[        S5      eU R                  S	SXS
./S9n[        R                  " U5        U
[        :X  a  S$ S$ s  snf )Nr  z/workspaces/current/secretsr  )Nopenai)N	anthropicr  r  z1Must specify openai_api_key or anthropic_api_key.r  )r  r   rB  )r  r;   r  r  r  rZ  rz  _OPENAI_API_KEY_ANTHROPIC_API_KEYintersectionru   )r   r  r  r  r  sworkspace_keystarget_keysexisting_keysr   api_vars              r?   r  Client._ensure_insights_api_key"  s6    ,,U4QR++H508@1%%,@e$$OOO,''OO./*77DD=D.-?8P[Ph$G%Gk!'G(G0$9(9G)7o=OGPQQ,,)!45 - 

 	++H5"o5xF;F5 As   Ec                   [        U5      S:  a  [        R                  " S5        US S n[        R                  R	                  [        R
                  R                  5      nU R                  U=(       d0    S[        R                  R	                  5       R                  S5      -   5      n[        [        U5      5       Vs/ s H!  n[        [        R                  " 5       5      PM#     nn[        Xa5       VVs/ s HT  u  pxSUS S 0SU0UUUR                  S5       [        U5       3U[        R                  " SS9-
  US	UR                  S
S.
PMV     n	nnU R!                  U	S9  U R#                  5         U$ s  snf s  snnf )NrI  zDCan only generate insights over 1000 data. Truncating to first 1000.z	insights z%Y-%m-%d %H:%M:%Sru  r   z%Y%m%dT%H%M%S%fZ)r  r   rC   )
rN  rO  r<  rw  r  rQ  r%  rS  r+  r1  )r  )rz   r   r   r[  r\  r]  r^  r  strftimer  rt   rr   rD  r  r  r<  r  rF  )
r   r  r1  r\  r  r.  rh  r)  r  r  s
             r?   r  Client._ingest_insights_runs"  sh   t9tMMV ;D##H$5$5$9$9:%% Uh//335>>?RSS
 /4CI.>?.>3tzz|$.>? !/
 0	 &q!u-&?"#&<<0B#C"DS[M R!H$6$6q$AA#%jj 0 	 
 	d+

% @
s    (E78AE<)'r  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   r&  r+  r  r   r  r  r  r   )2r   r1  r   r1  r  zOptional[Retry]r  z%Optional[Union[int, tuple[int, int]]]r3  r1  r   zOptional[requests.Session]r4  r   r5  z Optional[Callable[[dict], dict]]r6  -Optional[Union[Callable[[dict], dict], bool]]r7  r  r8  r  r9  r   r:  z4Optional[Callable[[Sequence[dict]], Sequence[dict]]]r;  Optional[int]r<  Optional[float]r=  z/Optional[Union[dict, ls_schemas.LangSmithInfo]]r>  Optional[dict[str, str]]r?  zOptional[TracerProvider]r@  Optional[bool]r   r  rA  r1  rB  r  rC  r  rD  z%Optional[Callable[[Exception], None]]r   r   )r   rt   )r  r   r   r   )r   r2  )r  rt   r   r   r   r   )r   r1  )r   r1  r   r   )r   zls_schemas.LangSmithInfo)r   zls_schemas.LangSmithSettings)r  r  r   r1  )r  z0Literal['GET', 'POST', 'PUT', 'PATCH', 'DELETE']r   rt   r  zOptional[Mapping]r  r   r  'Optional[Sequence[type[BaseException]]]r  r   r  z1Optional[Callable[[requests.Response, int], Any]]r  rt   r  r   r   zrequests.Response)rx   rt   r  Optional[dict]r   Iterator[dict])
rx   rt   r   r  r!  zLiteral['GET', 'POST']r"  rt   r   r  )r7  pd.DataFramer1  rt   r/  Sequence[str]r0  r  r+  r1  r,  Optional[ls_schemas.DataType]r   ls_schemas.Dataset)r8  z"Union[str, tuple[str, io.BytesIO]]r/  r  r0  r  r1  r1  r+  r1  r,  r  r   r  )FF)r`  z3Union[ls_schemas.Run, dict, ls_schemas.RunLikeDict]r  r   r  r   r   r   )r  zSequence[dict]r   r   r   r   )r  zIterable[dict]ru  r   r   z
list[dict])r1  rt   rN  dict[str, Any]rS  
RUN_TYPE_Tr~  r1  r  r1  r  r   r   r1  r   r1  r  r   r   r   )ra  r   r   r1  r   r1  r   r   )ra  r   r   r1  r   r1  )rN  r   )rO  r   )r   r   r   r   )r   r   )r  zlist[SerializedRunOperation]r   r1  r   r1  r   r   r  )r  GOptional[Sequence[Union[ls_schemas.Run, ls_schemas.RunLikeDict, dict]]]r  r
  r  r   r   r   )r   bytesr  rt   r   r1  r   r1  )r  z@list[Union[SerializedRunOperation, SerializedFeedbackOperation]]r   r1  r   r1  r   r   )
r  r
  r  r
  r  r   r  r   r   r   )r  r)   r  r   r   r1  r   r1  )r!  z
io.BytesIOr"  zOptional[tuple[int, int]]r  r   )$r)  ID_TYPEr1  r1  rS  zOptional[RUN_TYPE_T]rQ  Optional[datetime.datetime]r%  r  r  r1  rN  r  rO  r  r  zOptional[Sequence[dict]]rP  r  r&  Optional[list[str]]r   Optional[ls_schemas.Attachments]r  r   r'  str | uuid.UUID | Noner   r1  r   r1  r  r   r   r   )r5  r   r   r1  r   r1  )r5  r   r   r1  r   r1  r   r   )r   )r  r   r   r   )r`  ls_schemas.Runr   r  r  )r)  r  r`  r   r   r  )$rc  z+Optional[Union[ID_TYPE, Sequence[ID_TYPE]]]r~  z#Optional[Union[str, Sequence[str]]]rS  r1  rw  Optional[ID_TYPE]r'  r  rd  r1  re  r1  rf  r1  rg  r1  rI  r  r*  r  rQ  r  r  r  rh  Optional[Sequence[ID_TYPE]]ri  Optional[Sequence[str]]r  r  r  r   r   Iterator[ls_schemas.Run])"r<  Optional[list[ID_TYPE]]rC   r  ry  r  rS  r1  r  r  r  r  r  r  rQ  r1  r%  r1  r  r  rd  r1  re  r1  rf  r1  rg  r1  rI  r  r  r1  r   r  )r`  zls_schemas.RunBaser~  r1  rc  r  r   rt   )r)  r  r  r  r   rt   )r)  r  r   r   )r)  r  r   r1  )r)  r  r   r   )r  Union[ID_TYPE, str]r)  r  r   r  )r  r  rh  r  r   r  )r  r  r  r1  r   zls_schemas.DatasetShareSchema)r  r  r   r   )r  rt   r   r  )r  rt   r  r  r  r  r   Iterator[ls_schemas.Example])r  rt   r  r  r1  r1  r  r1  r  r  r   (Iterator[ls_schemas.TracerSessionResult])r~  rt   r+  r1  r   r  r  r   r  r  r  r  r   ls_schemas.TracerSession)rc  r  r1  r1  r+  r1  r   r  r  r  r%  r  r   r  )r   Optional[uuid.UUID])r   	uuid.UUID)rc  r1  r~  r1  r  r   r   zls_schemas.TracerSessionResult)r~  rt   rc  r1  r   r   )rc  r  r~  r1  r   r  )
NNNNNNNNNN)r  r  r1  r1  r  r1  r  r  r   r1  r  r  r  r  r  r1  r  r  r   Optional[dict[str, Any]]r   r  )r~  r1  rc  r1  r   r   )r  rt   r+  r1  r,  ls_schemas.DataTyper&  r  r'  r  r(  z0Optional[list[ls_schemas.DatasetTransformation]]r   r  r   r  )r  r1  r  r  r   r   )r  r1  r  r  r   r  )
r  r  r  r1  r9  Union[str, datetime.datetime]r:  r  r   zls_schemas.DatasetDiffInfo)r  r  r  r1  r   r  )rE  r  r,  r1  r  r1  rF  r1  r   r  r  r  r   zIterator[ls_schemas.Dataset])r  r  r  r1  r   r   )
r  r  r  r1  rO  zdatetime.datetimerP  rt   r   r   )
r  r  r  r1  rT  r1  r  r  r   z#Iterator[ls_schemas.DatasetVersion])
r  r  r  r1  rO  r  rP  r1  r   zls_schemas.DatasetVersion)rb  rt   r\  r1  r  r1  r   r  )r  r  r   r  )NNNN)r   rt   rn  r1  r  r  r  r1  rl  r  r   ls_schemas.Example)ru  z:list[Union[Mapping[str, Any], ls_schemas.BaseMessageLike]]rv  z>Optional[Union[Mapping[str, Any], ls_schemas.BaseMessageLike]]r  r  r  r1  rl  r  r   r   r  )
r`  r  r  r  r  r1  rl  r  r   r   )r  zwUnion[list[ls_schemas.ExampleCreate] | list[ls_schemas.ExampleUpsertWithAttachments] | list[ls_schemas.ExampleUpdate],]r  r   r  r   r   z/tuple[Any, bytes, dict[str, io.BufferedReader]])r  r  r  z(Optional[list[ls_schemas.ExampleUpdate]]r  r   r   !ls_schemas.UpsertExamplesResponse)r  r  r  z(Optional[list[ls_schemas.ExampleCreate]]r  r   r   r!  )r  zls_schemas.ExampleCreater   r   )r  )r  zlist[ls_schemas.ExampleCreate]rB  r   r   z$list[list[ls_schemas.ExampleCreate]])r  z7Optional[list[ls_schemas.ExampleUpsertWithAttachments]]r  r   r   r!  )r  r1  r  r  r  z3Optional[Sequence[ls_schemas.ExampleCreate | dict]]r  r   r  z!Annotated[int, Field(ge=1, le=3)]r  r   r   z2ls_schemas.UpsertExamplesResponse | dict[str, Any])NNNNNNNNNFNN)rN  Optional[Mapping[str, Any]]r  r  r  r1  rl  r  rO  r"  r   r"  ry   Optional[str | list[str]]r  r  r  r  r  r   r  r  r  r  r   r   )r  r  rO  r  r   r   )NNNNNT)r  r  r  r1  r  r  rO  z'Optional[Union[datetime.datetime, str]]r  r  r  r   r  r   r  r  r   r  re  r1  r  r   r  r   r   r  )r  r  rP  rt   r  r   r   r   )r  r  r  r   r   r   )rN  r   r  r   r  r  re  r1  r  r   r   zlist[ls_schemas.ExampleSearch])r  r  rN  r  rO  r"  r   r  ry   r#  r  r  r  z*Optional[ls_schemas.AttachmentsOperations]r  r  r   r  )r  
str | Noner  zID_TYPE | Noner  z3Optional[Sequence[ls_schemas.ExampleUpdate | dict]]r  r   r  r   r   r  )r  r  r   r   )r  Sequence[ID_TYPE]r3  r   r   r   )r  r  r  r1  rO  z'Optional[Union[str, datetime.datetime]]r   z	list[str])r  r  r  r1  rA  rt   r  list[ID_TYPE]ry  r   r   r   )r`  9Union[ls_schemas.Run, ls_schemas.RunBase, str, uuid.UUID]r`  r   r   r  )r  z5Union[ls_schemas.Example, str, uuid.UUID, dict, None]r`  r  r   zOptional[ls_schemas.Example])r  JUnion[ls_evaluator.EvaluationResult, ls_evaluator.EvaluationResults, dict]rN  r1  r   #list[ls_evaluator.EvaluationResult])r`  r'  r^   ls_evaluator.RunEvaluatorr`  r  rx  9Optional[Union[ls_schemas.Example, str, dict, uuid.UUID]]r`  r   r   r[  )rg  r(  r`  zOptional[ls_schemas.Run]r`  r  rc  r  ri  zOptional[cf.ThreadPoolExecutor]r   r)  )r`  z%Union[ls_schemas.Run, str, uuid.UUID]r^   r*  r`  r  rx  r+  r`  r   r   r[  )Nunnamed)(r)  r  r  rt   r   Union[float, int, bool, None]r   zUnion[str, dict, None]rw  r  ro  Union[dict, None]rR  Union[str, None]r`  r  rq  z)Union[ls_schemas.FeedbackSourceType, str]r  r  r}  r  rp  #Optional[ls_schemas.FeedbackConfig]r  r   rc  r  r~  r  r  r  rP  r  r  r  r  r   r   ls_schemas.Feedback)r}  r  r   r-  r   (Union[float, int, bool, str, dict, None]ro  r.  rR  r/  r   r   )r}  r  r   r1  )rh  r  r  r  rq  z1Optional[Sequence[ls_schemas.FeedbackSourceType]]r  r  r  r   r   zIterator[ls_schemas.Feedback])r}  r  r   r   )rb  Union[str, uuid.UUID]r   r-  r   r2  ro  r.  rR  r/  r   r  r   r   )r)  r  r  rt   r  0Optional[datetime.datetime | datetime.timedelta]rp  r0  r}  r  r   zls_schemas.FeedbackIngestToken)
r)  r  r  r  r  r4  r  z7Optional[Sequence[Optional[ls_schemas.FeedbackConfig]]]r   z(Sequence[ls_schemas.FeedbackIngestToken])r)  r  r  r  r   z(Iterator[ls_schemas.FeedbackIngestToken])
r  r  r+  r  r  r  r  r   r   z$Iterator[ls_schemas.FeedbackFormula])r  r  r   ls_schemas.FeedbackFormula)r  rt   r  Literal['sum', 'avg']r  ASequence[Union[ls_schemas.FeedbackFormulaWeightedVariable, dict]]r  r  r+  r  r   r5  )
r  r  r  rt   r  r6  r  r7  r   r5  )r  r  r   r   )
r  r  r1  r1  r  r1  r  r  r   z$Iterator[ls_schemas.AnnotationQueue])
r1  rt   r+  r1  r  r  r  r1  r   z%ls_schemas.AnnotationQueueWithDetails)r  r  r   zls_schemas.AnnotationQueue)
r  r  r1  rt   r+  r1  r  r1  r   r   )r  r  r   r   )r  r  rh  r&  r   r   )r  r  r)  r  r   r   )r  r  r.  r   r   z%ls_schemas.RunWithAnnotationQueueInfo)r1  rt   r  r%  r  r  r+  r1  rl  r  r   r  r<  r  r   z ls_schemas.ComparativeExperiment)r  rt   r   r   )r  rt   r  rt   r   zls_utils.LangSmithUserError)r   r   )r  rt   r  r   r  r   r   r1  )r"  rt   r  r   r   dict[str, int])r"  rt   r   rt   )r"  rt   r   r   )r"  rt   r   r8  )r  r   r  r   r8  r  r9  r  r:  zls_schemas.PromptSortFieldr;  zLiteral['desc', 'asc']rd  r1  r   zls_schemas.ListPromptsResponse)r"  rt   r   zOptional[ls_schemas.Prompt])r"  rt   r+  r1  rI  r1  r&  r  r8  r   r   zls_schemas.Prompt)r"  rt   r  r   rP  r1  r   rt   )r"  rt   r+  r1  rI  r1  r&  r  r8  r  r9  r  r   r  )r"  rt   r   r   )r"  rt   rd  r  r   zls_schemas.PromptCommit)
r"  rt   r  r  r  r   rd  r   r   z'Iterator[ls_schemas.ListedPromptCommit])r"  rt   rd  r  r   r   )r"  rt   r  zOptional[Any]rP  rt   r8  r  r+  r1  rI  r1  r&  r  r   rt   )NNNNNNr   r   TNT)r  Optional[DATA_T]r  zOptional[Sequence[EVALUATOR_T]]r  'Optional[Sequence[SUMMARY_EVALUATOR_T]]r   r  r  r1  r+  r1  r  r  r  r   r  r   r  Optional[EXPERIMENT_T]r  r   rJ  z'Union[TARGET_T, Runnable, EXPERIMENT_T]r  r   r   ri   )r  r9  r  z+Optional[Sequence[COMPARATIVE_EVALUATOR_T]]r  r:  r   r  r  r1  r+  r1  r  r  r  r   r  r   r  r;  r  r   rJ  z(Union[tuple[EXPERIMENT_T, EXPERIMENT_T]]r  r   r   rh   )NNNNNNr   r   TNTr  )r  r9  r  zIOptional[Union[Sequence[EVALUATOR_T], Sequence[COMPARATIVE_EVALUATOR_T]]]r  r:  r   r  r  r1  r+  r1  r  r  r  r   r  r   r  r;  r  r   r  Literal['log', 'ignore']rJ  zJUnion[TARGET_T, Runnable, EXPERIMENT_T, tuple[EXPERIMENT_T, EXPERIMENT_T]]r  r   r   z6Union[ExperimentResults, ComparativeExperimentResults])r  zNUnion[DATA_T, AsyncIterable[schemas.Example], Iterable[schemas.Example], None]r  z4Optional[Sequence[Union[EVALUATOR_T, AEVALUATOR_T]]]r  r:  r   r  r  r1  r+  r1  r  r  r  r   r  r   r  z6Optional[Union[schemas.TracerSession, str, uuid.UUID]]r  r   r  r<  rJ  zVUnion[ATARGET_T, AsyncIterable[dict], Runnable, str, uuid.UUID, schemas.TracerSession]r  r   r   ra   )FNNN)r  r  r+  r  r  r   r~  r  r  !dict[uuid.UUID, list[str]] | Noner  r  r   zIterator[list[ExampleWithRuns]])NNFNNN)r1  r1  rc  r  r  r   r~  r  r  r=  r  r  r   zls_schemas.ExperimentResults)r  zlist[list[dict]]r  rt   r1  r$  r  %Literal['openai', 'anthropic'] | Noner  r$  r  r$  r   ls_schemas.InsightsReport)r  z ls_schemas.InsightsReport | Noner<  r  rc  r  r  r   r  r   r  r   r   r?  )r  r$  r  r$  r  r>  r   zLiteral['openai', 'anthropic'])r  r  r1  r$  )rS   rT   rU   rV   rW   	__slots____annotations__r   r  r  r  propertyr  r  r  r  r   setterrA  r=  r  r  r  r  r)  rb  r_  r`  r9  r6  rb  ro  rr  r|  r  r  r  rX  rY  rZ  r  r  r  r  r  r  r  r  r#  r0  r-  r4  rC  rF  rX  ra  rO  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rG  r  r;   xor_argsr}  r  r  r!  r$  r.  r2  r  r>  rC  rH  rK  rR  rW  rZ  re  rq  ro  rz  r  r  r  r  r  r  r  r  r  ra  r  r  rm  r  r  r"   r  r  r  r  r.  r1  r9  r>  rC  rH  rL  r^  rd  re  r{  ru  r  rl  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,  r2  r5  PromptSortField
updated_atrA  r+  rM  r[  r^  ra  rh  ro  r  r  r  r   r  r  r  r  DEFAULT_INSTRUCTIONSr  r  r  r  rX   r=   r>   r?   r
  r
    s'   8*IX ##!! "&E> "&(,<@!%.2#'7;EIFJGK). -159@D-19='+15&*.2,0HL9E>E> 	E>
 &E> :E> E> ,E> !E> 5E> CE> DE> EE> #'E>#
E>$ +%E>& $3'E>( >)E>* ++E>, 7-E>. %/E>0  /1E>2 $3E>4 ,5E>6 *7E>8 !F9E>: 
;E>N
X3 ( ( B BF
   ^^; ; " " @ @ " "H. -1"#<@=AMQi
 Ai
 	i
 *i
  i
 :i
 ;i
 Ki
 i
 i
 
i
X 6:!!$2!	!H  $17'0'0 	'0
 /'0 '0 
'0` &*3=3F3F3I3I:
:
 :
 "	:

 #:
 #:
 1:
 
:
D #%)3=3F3F3I3I\
4\
 "\
 #	\
 \
 #\
 1\
 
\
B 	3@3 3 	3
 
3j : 6;!"!.2!	!R '+%)-2!%!%]K]K ]K 	]K $]K #]K '+]K ]K ]K ]K 
]KF "&!%PUPU 	PU
 PU 
PUl "&!%1 1  	1 
 1 f)+-(D> "&!%S)S 	S
 S 
Sr  U3 "U3
U3

U3 U3 
U3x "&!%)7)7 	)7
 )7 )7^ "&!%&?M&? 	&?
 &? 
&?X  j3 "-2j3
j3

j3 j3 '+j3 
j3` !%!%@%@ 	@
 @ @N HH !:H
 H\ #)-2604#!%"&+/ $$(8<-27;!%!%%MEME 	ME
 'ME 0ME .ME ME ME  ME )ME ME "ME 6ME '+ME  5!ME" #ME$ %ME& 'ME( 
)MEf "&!%LULU 	LU
 LUd "&!%'' 	'
 ' 
'R-2 -2^
&(V 8=%%04%	%T CG<@"&&*26# $&*%)"&+/26 $/3*.#%@ @@ :	@
  @ $@ 0@ @ @ $@ #@  @ )@ 0@ @  -!@" (#@$ %@& '@( 
")@J '+#'(,"&-1/39=$("& $# $&*%)"&*.%V $V !	V
 &V  V +V -V  7V "V  V V V V $V  #!V"  #V$ (%V& 
'Vx '+(,$
  $
 $	$

 &$
 
$
L KO : :46 D*
  MQK.K8IK	K4 PTB.B9LB	!B* )-&
 '+	&
%&
 $	&

 
'&
T )-&
 '+	&
%&
 $	&

 
'&
P6 

 

: 04# -	
  
&D 04"'+# ! -	
  %  
2J &*#'(,26-U-U #	-U
 !-U -U &-U 0-U 
"-Uf #%)#'(,04/U/U 	/U
 #/U !/U &/U ./U 
"/Ub( 56 %)&*#'
 "'
 $	'

 '
 
('
 7'
T AE0=	. )-&*	nF &nF $	nF
 
nFd 04"'+2604)-(,)-#-1I,I I %	I
 0I !.I 'I &I 'I I +I 
2IV 56/3QU6,6AN6	6 76@ &*)3)<)<)?)?2637LP#'F
F
 #	F

 'F
 0F
 1F
 JF
 !F
 
F
V '+(,	 $ &	
 
. 56 '+(,	-
 $-
 &	-

 
-
 7-
b )-C= '+	C=%C= $	C=
 4C= 2C= 
$C=N )-  '+	 %  $	 
 
 J 04#'&*/3-1#3 -3 !	3
 $3  -3 +3 3 
&3j 56 )-&*	6 &6 $	6
 
6 76> )-&*	:6 &:6 $	:6
 !:6 :6 
:6~ )-&* $#! &! $	!
 ! ! 
-!L )-&*-1!/< &/< $	/<
 +/< /< 
#/<j )-&*HH &	H
 $H 
HT! 56 %)(,&*26

 "
 &	

 $
 0
 

 7
B 56 (,&*265
L5

5
 &5
 $5
 05
 
5
 75
t )-&*26W
W
 &W
 $	W

 0W
 
W
@ $)-2{0
{0 !{0 '+{0 
9{0B =A-2
 
 :	

 '+
 
+
. =A-20 0 :	0
 '+0 
+0l =A-2
 
 :	

 '+
 
+
&B %/'0' "' 
.	'Z =A-21 1 :	1
 '+1 
+1l LP-2	/ I/ '+	/
 
+/b 56 '+(,HL-2=>W
 $W
 &	W

 FW
 '+W
 ;W
 W
 
<W
 7W
r
8*X 56 /3(,&*26/304+/(,+/"':>8<j+j &j $	j
 0j -j .j )j &j )j  j %8j 6j 
j 7jZ LP!
!!
-H!
	!
J )-&*379=*.#{ ##' $$){%{ ${ 1	{
 7{ ({ { { { !{ { "{ { 
&{z 
 	2 2 	2
 2 
2 2> 2 2 	2
 
2 26  !%aa
 a a a a 
(a aN ,0/3#'+/(,MQ8<U#U# )	U#
 -U# !U# )U# &U# !KU# 6U# 
U#t $(%)GK-2W# !W# #	W#
 EW# '+W# W# 
W#r6$ FK/6,/6>B/6	/6h )-&*9=# &# $	#
 7# 
#P )-&* '6 &'6 $	'6
 '6 #'6 '6 
'6RF  
	2"F" " 
&	"L "&%
% % 
-%X 15  %*F* -*
 .*
* * 
'*b )-04(,0 6:0
0
 &0 .0 &0 30 
-0n 15  %*2* -*
 .*
* * 
'*^ %)	y 04(,&*(,$(04 ))--+/)-?C"$(,7;/3 $ $/y "y 	y -y &y $y &y "y .y
y )y  '!y" =#y$  %y& &'y( $5)y* -+y, -y. /y0 1y2 
3y~ 04:>(,$()6)6 -	)6
 8)6 &)6 ")6 
)6V6& 0404RV#) -) .	)
 P) ) ) 
')V6( 0406
 ;?(,$(#'06+06 -06
 806 &06 "06 !06 
06n HL?C)-?A?A ?A
 E?A =?A '?A 
(?AL HL dd %d
 Ed
d 
2dT  $	 	
 
2: )-(,#& && &	&
 & & 
.&P=#*=	#=6 )-(,5= 5= 0	5=

5= &5= &5= 
$5=n,=$,= 	,=
 0,=
,= 
$,=\6$ .2"'+#( +( 	(
 %( ( 
.(\ &*&*-1%
 %
 #	%

 $%
 +%
 
/%
NH. &*-166 	6
 #6 +6 
6@6 66-:6	6(66,36	6&HH+.H	.H< 04%)26-1 $9>9> '9>
 -9> #9> 09> +9> 9> 
*9>v
?

"%
	$
 IJ>%(>14>BE>	>*!$,0	.
.
)
I
J $(&+1;1K1K1V1V17#*A *A 	*A
 "*A $*A /*A /*A *A 
(*AX2 &* $(,3<3< #	3<
 3< &3< 3< 
3<t -12N2N 2N
 *2N 
2Np &* $(,$(&*88 #	8
 8 &8 "8 $8 
8t$. ).	

 &	

 
!
F  $#77 	7
 7 7 
17t JOd!$d8Fd	dT !%"*$(%) $(,CC 	C
  C "C #C C &C 
CJ$ 
 "&6:FJ#'+/%))* -1#  	 
 4  D  !  )  #  '      +   7     
!   $ 
 "&BFFJ#'+/%))* -1#+ 	+
 @+ D+ !+ )+ #+ '+ + + ++ +8+ +  
&!+ +0 "& FJ#'+/%))* -1#38'b
 b

b
 Db
 !b
 )b
 #b
 'b
 b
  !b
" +#b
$ %b
& 1'b

b
( )b
* 
@+b
b KOFJ#'+/%))* MQ#381y

y
 Iy
 Dy
  !!y
" )#y
$ #%y
& ''y
( )y
* +y
, K-y
. /y
0 11y

y
2 3y
4 
 5y
~ 9=59#8!8! 8! 	8!
 $78! 38! 8! 
)8!x #*.9=59#]
]
 (]
 	]

 $7]
 3]
 ]
 
&]
~ 
 17;%)(,` )` 	`
 ` 5` #` &` 
#` `D  48%)-135 135 #	35
 +35 35 35 35 
#35 35p &*(,7;#G ##G &	#G
 5#G 
(#GJ r>   r
  c                    SSK Jn  U" 5       nU=(       d    0 nUR                  SS5      n UR                  " U 4SU0UD6$ ! [         a    [        S5      ef = f! [
         a  n[        R                  " SU 35      eSnAff = f)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.

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_openairI  rL   r_  _get_request_payloadr   r;   r  )ru  model_kwargsrI  r  rJ  r   s         r?   convert_prompt_to_openai_formatrN  #  s    (
/ \F%2LFD)DQ**8O$O,OO  
K
 	

  Q%%(KA3&OPPQs"   A A A
B%A>>Bc                P    SSK Jn  U=(       d    0 nUR                  SS5      nUR                  SS5      nUR                  SS5      nU" SX5US	.UD6n UR	                  XS
9$ ! [         a    [        S5      ef = f! [
         a  n[        R                  " SU 35      eSnAff = f)aA  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`.

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-20240307rJ  Nr  )rQ  r  rJ  )rJ  z&Error converting to Anthropic format: r=   )langchain_anthropicrP  rL   r_  rL  r   r;   r  )ru  rM  rP  rQ  rJ  r  r  r   s           r?   "convert_prompt_to_anthropic_formatrS  3#  s     
5  %2L!!,0IJJFD)Dy$/G T=IIT--h-BB#  
=
 	

$  T%%(Nqc&RSSTs#   A$ A= $A:=
B%B  B%c                  >   ^  \ rS rSrSrSU 4S jjrSSS jjrSrU =r$ )	_FailedAttachmentReaderi[#  zHBytesIO that raises an error when read, for failed attachment downloads.c                .   > [         TU ]  5         Xl        g r   )r   r   _error)r   r  r   s     r?   r    _FailedAttachmentReader.__init__^#  s    r>   c                ^    [         R                  " SU R                   35      U R                  e)NzFailed to download attachment: )r;   r  rW  )r   r  s     r?   read_FailedAttachmentReader.readb#  s*    %%-dkk];
{{	r>   )rW  )r  r   )r@  )r  r  r   r  )	rS   rT   rU   rV   rW   r   rZ  rX   r  r  s   @r?   rU  rU  [#  s    R r>   rU  r  c          
     $   0 nX;   a  X   (       a  X   R                  5        H  u  pEUR                  S5      (       d  M  Ub  [        X%S   5      nOUS   n [        R                  " USS9nUR                  5         [        R                  " UR                  5      n[        S
0 US   UUR	                  S5      S	.D6X4R                  S5      '   M     U$ ! [         a0  n	[        R                  SU SU	 35        [        U	5      n Sn	A	NmSn	A	ff = f)zOConvert attachments from the backend database format to the user facing format.zattachment.Npresigned_urlT)r  zError downloading attachment r  r  )r]  readerr  r=   )r   
startswithr  r`  r  r!  r2  r3  contentr   r   rt  rU  r5   removeprefix)
r  r]  r   attachments_dictr  r   r8  r  r^  r   s
             r?   r^  r^  h#  s    4#8/557JC>>-00")'3IJ 14#<<>))+H$4$45 AO A%*?%;$!&;!7A--m<= 8*   4!>se2aSIJ034s   AC
D&D

Dc                    U  H  n UR                  5         M     g! [         a$    [        R                  SUR                  5         MF  f = f)z2Close all opened files used in multipart requests.zCould not close file: %sN)r   r   r   r   r1  )r  r>  s     r?   r  r  #  sA    	JJL   	LL3TYY?	s   *A
	A
c                d    U R                  S5      R                  S5      (       a  SU S3$ SU S3$ )Nrn   r  z/platform/datasets/r  z/v1/platform/datasets/r   r   )r   r  s     r?   r  r  #  s:    ~~c##E**$ZL	::'
|9==r>   c                `    U R                  S5      R                  S5      (       a  SU 3$ SU 3$ )z=Construct a platform API path based on the API URL structure.rn   r  z
/platform/z/v1/platform/re  )r   rx   s     r?   r7  r7  #  s6    ~~c##E**D6""tf%%r>   c                @   UR                  S5      (       a  U$ U R                  S5      (       a  SnU [        S5      S  n O6U R                  S5      (       a  SnU [        S5      S  n O[        SU < 35      eU R                  S5      R	                  S5      nUR                  S5      R	                  S5      nU(       d  [        SU < SU< 35      eU(       d  U $ US   S	:X  a  US
   S	:X  a  US S
 nOUSS  S	S/:X  a  US S nX4-   nUSR                  S U 5       5      -   $ )NhttprM  rL  zBapi_url must start with 'http://' or 'https://'. Received api_url=rn   zPMust specify non-empty api_url or pathname must be a full url. Received api_url=z, pathname=r   apir@  r  v1c              3  6   #    U  H  o(       d  M  Uv   M     g 7fr   r=   )r  ps     r?   r  !_construct_url.<locals>.<genexpr>#  s     1eq11es   
	)r_  rz   ru   r   ry   lstripr  )r   r   rh  	api_partsr   r   s         r?   r  r  #  sB   6""*%%#j/+,			I	&	&#i.*+Q
S
 	
 s#))#.I%++C0J!zH;0
 	
 !}R=E!!#2Irs^t},!#2I"E#((1e1111r>   r  c                   [        U S5      (       a  U R                  US9$ [        U S5      (       a  U R                  US9$ [        S5      e)z)Dump model depending on pydantic version.
model_dumpr  r   zUnsupported model type)rz  rq  r   	TypeError)r  r  s     r?   r  r  #  sM    ul##\::			zz|z44011r>   c                    SSK Jn  SSKJn  SSKJnJn  U n[        X5      (       Ga8  [        U R                  U5      (       Ga  [        U R                  S   U5      (       a  S[        U R                  5      s=::  a  S::  a  O  U$ U R                  nU R                  S   nUR                  nUR                  n	[        Xb5      (       d3  S	UR                  ;   a#  UR                  S	   n
U" SS
UR                  0U
D6n[        Xb5      (       aT  Xh-  R                  S   R                  nU	R                  5        VVs0 s H  u  pX;  d  M  X_M     snnUl        U" Xg5      nU$ ! [         a    [        S5      ef = fs  snnf )z/Format the object so its Prompt Hub compatible.r   )ChatPromptTemplateru  rw  rR  r   r  r   ls_structured_output_formatru  r=   )r  rt  r  rv  langchain_core.runnablesrx  ry  rL   rq   r  r  rz   r  r  ru  r   )objrt  rv  rx  ry  chain_to_pushr   bound_modelr  rM  output_formatstructured_kwargsrm  rn  s                 r?   rW  rW  #  sk   
=FN M3))syy"455syy|_55SYY$1$6 3 iil!!"))
 644-1C1CC'../LMM%PvP-PF f//!' 6 6q 9 @ @ ".!3!3!5"!59S!5"K -VAMQ  
I
 	

B"s   E# ;E<
E<#E9r  )r  r,  )
r~   r3  r   rt   r   r   r   rt   r   ztuple[str, str])r   rt   r   r   )r   r   )r   zrequests.Sessionr   r   )r   rt   r   r1  r   r   )r   r-  r   )r   r  r   zfloat | None)r   r  r   r2  )r   r  ro   r1  r   r  )r   Optional[Union[str, uuid.UUID]]r   r  )r   r|  r   r   r   r  )r   r|  r   r   )ru  r   rM  r  r   r   )r  r   r]  rt   r   r1  r   zdict[str, AttachmentInfo])r  zlist[io.BufferedReader]r   r   )r   rt   r  r  r   rt   )r   rt   rx   rt   r   rt   )r   rt   r   rt   r   rt   )r  r   r   r  )rw  r   r   r   )rW   
__future__r   rf  r  r  rA  r=  r  r[  ro  r   importlib.metadatar2  r  r  loggingrX  r  rh  rr  r  typingrr   r   rd  collections.abcr   r   r   r   r   inspectr	   pathlibr
   r  r   r   r   r   r   r   r   r   r   urllibr   rv   r`  pydanticr   r   r  requests_toolbeltr   r  typing_extensionsr   r   urllib3.poolmanagerr   urllib3.utilr   r  r   rf  r   rb  r   r;   langsmith._internalr   r  r    r!   rk  #langsmith._internal._beta_decoratorr"   &langsmith._internal._compressed_tracesr#   langsmith._internal._constantsr$   r%   r&   r'   langsmith._internal._multipartr(   r)   r*   langsmith._internal._operationsr+   r,   r-   r.   r/   r0   r1   r2   langsmith._internal._serder3   r'  langsmith._internal._uuidr4   langsmith.schemasr5   r6   r  r  r@   rN   zoneinforO   rL   opentelemetry.sdk.tracerY   r  r  rv  r\   rH   rC   rM   rK   rG   r\  r^   rU  r  r_   r`   ra   r  rb   rc   rd   re   rf   rg   rh   ri   	getLoggerrS   r   r  r  rk   rA  
parametersr   rG  r   r   rs   rt   r  r	  rp  r   r   r   r   r   r   r{   r   r   HTTPAdapterr   r
  rN  rS  r3  rU  r^  r  r  r7  r  r  rW  r=   r>   r?   <module>r     s  
 #         	    	         P P   	 	 	 )   2 2 '   # + ' ' : C  
	 	 	 A + ="( 6

$(!.6 1!5H ? 
	 	 	 
		8	$##$<=	 	  ,	'0B0M0MM S  	'  	
 :  		3
H

 Q3  3>4  .2*.$   J  J CG*<@ 
 QV  Q  T-99 T8eE eETK .2$Q$Q*$Q 
$QR .2%T%T*%T 
%TP
bjj 
 CG
$'2?<>&2D /4 2.UZ  (( ((  .. .."  
s6   L  
L7 (M  L43L47M
M
MM