
    Zi`}                      % S r SSKJr  SSK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!J"r"  SSK#J$r$  SSK%J&r&  SSK'J(r(J)r)  SS	KJ*r*J+r+J,r,J-r-J.r.J/r/J0r0J1r1J2r2J3r3  SS
K4J5r6  SSK7r7SSK8r8SSK9J:r:  SSK8J;r<  SSK=J>r?  SSK@JArAJBrB  SSKCJDrD  SSKEJFrF  SSKGrGSSKGJHrI  SSKGJJrK  SSKGJLrM  SSKNJOrO  SSKPJQrQ  SSKPJRrS  SSKTJUrU  SSKVJWrW  SSKXJYrYJZrZJ[r[J\r\J]r]  SSK^J_r_J`r`JaraJbrbJcrc  SSKdJereJfrfJgrg  SSKhJiriJjrjJkrkJlrlJmrmJnrnJoroJprp  SSKqJrrs  SSKtJuru  SSKvJwrwJxrx  SS KyJzrzJ{r{  \R                  " \}5      r~S!rSqS"q\GR                  " 5       r\.S#   r\" \3" \5      5      rS$\S%'   StS& jrSuS' jrS(rS)rS*rSS+.     SvS, jjrS- r SS.KJr   SS1KJr  \*(       aA  SSKrSS4KJr  SSKGJJrJ   SS5KJr  SS6KJr  SS7KJr  SS8KJrJrJr  SS9KJrJrJrJrJrJrJrJr  \R                  " \}5      r~\R                  " S:5      rS;rS<rS=\S>'   \" 5       rS?\$" \D5      GRd                  ;   rS@r\" 5       rSA\SB'   \!" SCSD9SwSE j5       rSSFSGSH.         SxSI jjr      SySJ jr          SzSK jr  S{         S|SL jjrS}SM jr\1\GRz                  \4   r\.SN   r\RB                  " SCSD9S~SO j5       rSSP jrSQSR.       SSS jjrSST jr S   SSU jjrSSV jrSSSW jjr\R                  SSX j5       r\R                  SYSZ.     SS[ jj5       rS\SZ.SS] jjr\RB                  " SCSD9S^ 5       r " S_ S`\<GR                  5      r " Sa Sb\05      r " Sc Sd5      r S     SSe jjr S     SSf jjr " Sg Sh\GR                  5      rSSi.       SSj jjrSSk jrSSl jrSSm jrSSn jrS\So.SSp jjrSSq jr                SSr jr      SSs jrg! \ a     " S/ S05      r GNkf = f! \ a     " S2 S35      r GN{f = f! \ a    \,r\,r GNhf = f)a  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)	lru_cachepartial)	signature)Path)FullPriorityQueue)
TYPE_CHECKING	AnnotatedAnyCallableLiteralOptional	TypedDictUnioncastget_args)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_TRACING_QUEUE_MAX_SIZE)HUBPLATFORM_HUBREPO_HANDLE_PATTERNbuild_commit_urlvalidate_parent_commit)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)PromptCacheprompt_cache_singleton)AttachmentInfoExampleWithRuns<           )	langsmithotelhybridzfrozenset[str]_VALID_TRACING_MODESc                    [            [        S-  q[        R                  " 5       nU[        -
  [        :  a&  [        nSqUq[
        R                  SU[        U 5        SSS5        g! , (       d  f       g= f)z;Rate-limited logging for dropped trace data (once per 60s).   r   z1Dropped %d trace data item(s) in the last %ds: %sN)_tracing_drops_lock_tracing_drops_counttime_tracing_drops_last_log_time_TRACING_DROP_LOG_INTERVAL_Sloggerwarning)reasonnowcounts      j/var/www/eduai.edurigo.com/question_generate/ques_gen_env/lib/python3.13/site-packages/langsmith/client.py_log_tracing_droprW   |   sa     
!iik--1MM(E#$ +.(NNC,	 
		s   AA&&
A4c                 L    [            SqSqSSS5        g! , (       d  f       g= f)z7Reset rate-limit state for drop logging. Used in tests.r   rE   N)rL   rM   rO        rV   _reset_tracing_drop_logr[      s     
 '*$ 
		s   
#)   
   OPENAI_API_KEYANTHROPIC_API_KEYotel_enabledc               H   SnSnSn[         R                  " U5      nU bU  U R                  5       n U [        ;  a9  [         R                  " SU < SSR                  [        [        5      5       35      eU $ Ub?  [        R                  " S[        SS	9  U(       a  [         R                  " U5      (       a  g
ggUb  UR                  5       nU[        ;  a9  [         R                  " SU< SSR                  [        [        5      5       35      e[         R                  " U5      n[         R                  " U5      nU(       d  U(       a"  [        R                  " SU SU SU SU S3	SS	9  U$ [         R                  " U5      (       a  g
[         R                  " S5      (       a  gg)a  Resolve the effective tracing mode from the constructor arg and env vars.

Priority: explicit ``tracing_mode`` argument >
deprecated ``otel_enabled`` argument >
``LANGSMITH_TRACING_MODE`` env var >
legacy ``OTEL_ENABLED`` / ``OTEL_ONLY`` env vars >
default ``"langsmith"``.
TRACING_MODEOTEL_ENABLED	OTEL_ONLYzInvalid tracing_mode=z. Must be one of: , zThe 'otel_enabled' parameter is deprecated and will be removed in the next minor version. Use 'tracing_mode' instead, e.g. Client(tracing_mode="hybrid") or Client(tracing_mode="otel").r\   
stacklevelrG   rH   rF   zInvalid LANGSMITH_TRACING_MODE=zBoth LANGSMITH_z and the legacy LANGSMITH_z / LANGSMITH_z env vars are set. LANGSMITH_z takes precedence.)ls_utilsget_env_varlowerrI   LangSmithUserErrorjoinsortedwarningswarnFutureWarningis_env_var_truish)tracing_modera   mode_envvar_nameotel_enabled_envvar_nameotel_only_envvar_nameenv_modelegacy_otellegacy_onlys           rV   _resolve_tracing_moderz      s    &-'##$45H#))+33--''7 8##'99V4H-I#J"KM  L 	
 ))*?@@>>#//--1( >##'99V4H-I#J"KM  001IJ001FG+MM!"2!3 456 723 4-..@B   !!"788!!.11rZ   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]`)	opentelemetryr}   opentelemetry.tracer~   %langsmith._internal.otel._otel_clientr   'langsmith._internal.otel._otel_exporterr   ImportError)
otel_tracer~   r   r   s       rV   _import_otelr      sC    
5;	
 	I0HVV 
Y
 	

s    4)ZoneInfoc                      \ rS rSrSrSrg)r      zIntroduced in python 3.9.rY   N__name__
__module____qualname____firstlineno____doc____static_attributes__rY   rZ   rV   r   r      s    'rZ   r   )TracerProviderc                      \ rS rSrSrSrg)r      zUsed for optional OTEL tracing.rY   Nr   rY   rZ   rV   r   r      s    -rZ   r   )Runnabler|   r   	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-keyrY   ztuple[dict, ...]	EMPTY_SEQkey_blocksizez:How are people using my agent? What are they asking about?zset[str]_fallback_dirs_createdrK   maxsizec                    Sn  SSK Jn  [        R                  R	                  U5      nU[        R                  R	                  S5      :  =(       a"    U[        R                  R	                  S5      :  =(       d"    U[        R                  R	                  S5      :  n U $ ! [
        [        [        4 a!  n[        R                  SU5         SnAU $ SnAff = f)	zCheck if the installed `langchain_core.load.load` supports the `allowed_objects` parameter.

Returns `True` if `langchain-core >= 0.3.81` and `< 1.0`, or `>= 1.2.5`.
Fr   )__version__z0.3.81z1.0.0z1.2.5zbFailed to determine langchain-core version for allowed_objects support, defaulting to disabled: %sN)
langchain_corer   	packagingversionr   r   
ValueError	TypeErrorrQ   debug)allowed_objects_supportedr   
lc_versionexcs       rV   &_lc_load_allowed_objects_arg_supportedr   /  s     !&
.&&,,[9
 )++11(;; >Y..44W==%> I--33G<< 	" %$ Y/ 
2	
 	

 %$
s   BB C4CCr]   2   depth	max_depth	max_widthc                 ^^^ TS:  a  [        S5      eTS:  a  [        S5      eTT:  a  g[        U [        5      (       a  [        U 5      1 Sk:X  a
  U S   S:X  a  gTS-   T:X  a  g[        U [        5      (       a:  [	        UUU4S	 j[
        R                  " U R                  5       T5       5       5      $ [        U [        [        45      (       a  [	        UUU4S
 jU ST  5       5      $ g)z<Recursively check if a manifest contains any secret objects.rK   zmax_depth must be positive.zmax_width must be positive.F>   idlctyper   secretTc              3  B   >#    U  H  n[        UTS -   TTS9v   M     g7frK   r   N_manifest_has_secrets.0xr   r   r   s     rV   	<genexpr>(_manifest_has_secrets.<locals>.<genexpr>\  s0      
 D "i9 D   c              3  B   >#    U  H  n[        UTS -   TTS9v   M     g7fr   r   r   s     rV   r   r   c  s.      
 * "i9 *r   N)
r   
isinstancedictsetany	itertoolsislicevaluestuplelist)manifestr   r   r   s    ```rV   r   r   I  s     1}6771}677	8T""M11V(	i		Hd	#	# 
 %%hoo&7C	
 
 	
 
Hudm	,	, 
 jy)	
 
 	
 rZ   c               j    [         R                  " U 5      u  n  nUS:w  a  U(       d  [        S5      eg g )N-zPulling a public prompt by owner/name is disabled by default because prompts may contain untrusted serialized LangChain objects. If you trust this prompt, set `dangerously_pull_public_prompt=True` to acknowledge the risk.)ri   parse_prompt_identifierr   )prompt_identifierdangerously_pull_public_promptowner_s       rV   _validate_public_prompt_pullr   m  s>     223DEKE1a|:$
 	
 ;|rZ   c          	         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  0 n[%        5       (       a  U(       a  SOSUS'   U" 5           U" U R&                  4UUS.UD6n SSS5        [/        WU5      (       d+  [/        X5      (       a  [/        UR0                  U5      (       a  [/        X5      (       a  UO8[/        X5      (       a'  [/        UR0                  U5      (       a  UR0                  OSnUc  [2        R4                  " S5      eUR6                  c  0 Ul        UR6                  R9                  U R:                  U R<                  U R>                  S.5        U(       Gay  [/        X5      (       Gah  [/        UR0                  U5      (       GaL  [A        URB                  5      S:X  Ga2  [/        URD                  U5      (       Gd  [/        URD                  U	5      (       a  [/        URD                  RF                  U5      (       a  [I        XR0                  URD                  RF                  -  5      n[A        URB                  5      S:X  aU  URB                  S   nU
" UR0                  URJ                  " S0 0 URD                  RL                  ED6URD                  5      nU$ Un U$ [/        URD                  U5      (       a  UR0                  URD                  -  nU$  U$ ! [         a    [        S5      ef = f! [         a    [         R"                  S
 5       n GNf = f! [(         a=  n[+        U R&                  5      (       a  U(       d  U(       d  [-        SU 35      eUeSnAff = f! , (       d  f       GN= f)a@  Process a prompt manifest into a LangChain prompt object.

This is the common logic shared between `Client.pull_prompt()` and
`AsyncClient.pull_prompt()`.

Args:
    prompt_object: The prompt commit object containing the manifest.
    include_model: Whether to include model information.
    secrets: Map of secrets to use when loading.
    secrets_from_env: Whether to load secrets from environment variables.

Returns:
    The processed prompt object.

Raises:
    ImportError: If `langchain-core` is not installed.
    ValueError: If secrets are required but not provided.
r   )BaseLanguageModel)load)BaseOutputParser)BasePromptTemplateStructuredPromptRunnableBindingRunnableSequencezuThe client.pull_prompt function requires the langchain-core package to run.
Install with `pip install langchain-core`)suppress_langchain_beta_warningc               3     #    S v   g 7fNrY   rY   rZ   rV   r   A_process_prompt_manifest.<locals>.suppress_langchain_beta_warning  s     s   allcoreallowed_objects)secrets_mapsecrets_from_enva  Failed to load prompt. The prompt manifest contains secrets (like API keys or access tokens) but no secrets were provided. This is due to a security patch in langsmith 0.5.1 that disabled reading secrets from environment variables by default.

To resolve this:
- Recommended: Pass secrets directly via `secrets={'KEY_NAME': 'value'}`
- If this is a trusted prompt: Set `secrets_from_env=True` to read secrets from environment variables

Underlying error:
Nz-Prompt object is not a valid prompt template.)lc_hub_ownerlc_hub_repolc_hub_commit_hash   r\   rK   rY   )'#langchain_core.language_models.baser   langchain_core.load.loadr   langchain_core.output_parsersr   langchain_core.promptsr   !langchain_core.prompts.structuredr   langchain_core.runnables.baser   r   r   langchain_core._apir   
contextlibcontextmanagerr   r   	Exceptionr   r   r   firstri   LangSmithErrormetadataupdater   repocommit_hashlenstepslastboundr   bindkwargs)prompt_objectinclude_modelsecretsr   r   r   r   r   r   r   r   r   load_kwargsprompteprompt_templateseqrebound_llms                     rV   _process_prompt_manifestr  z  s'   2
I1B=FSG K-//2?V%&	(	*	&&#!1 	F 
+8 	6-..f//v||%788 &55  f77v||-?@@   	 "))?  ##+')O$  '' - 3 3,11&3&?&?	
 	v00v||%566!#Jv{{DT,U,Ufkk?33
KK09
 9
 '8I8I)IJC399~"!iil)LL$$>'=&++*<*<'=>HH M  M %677'-||fkk'AF M MM  
I
 	

  		"	"	 
#	$  	%m&<&<==( * +,.
 
 G#	 
+	*sF   &K* L M4L**L  L'&L'*
M148M,,M11M44
N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)r   uuidUUIDstrr   urllib_parseurlparsepathsplitr  _as_uuidri   rl   netloc)url_or_tokenapi_url	num_partskind
parsed_url
path_parts
token_uuids          rV   _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: The URL to check.

Returns:
    `True` if the URL is langchain hosted, `False` otherwise.
:r   zlangchain.comz.langchain.comF)r  urlsplitr   r  endswithr   )urlr   s     rV   _is_langchain_hostedr.     sY    &&s+2288=a@(MFOO<L,MM s   AA 
AA)toolchainllm	retriever	embeddingr  parserc            	         [        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:
    The default retry configuration.
r\   )i  i  i    i        ?FT)totalstatus_forcelistbackoff_factorraise_on_redirectraise_on_statusrespect_retry_after_headerurllib3.)rK      Nallowed_methodsrY   )
r   	importlibr   r   r   mapintr  ri   LangSmithRetry)retry_paramsurllib3_versionuse_allowed_methodss      rV   _default_retry_configrI  6  s|     2#'L  ((00;OC)>)>s)C DEP*.&'""2\22rZ   c                N    [         R                  S5        U R                  5         g)z=Close the session.

Args:
    session: The session to close.
zClosing Client.sessionN)rQ   r   close)sessions    rV   close_sessionrM  V  s     LL)*MMOrZ   rF   rs   c                   U(       dY  [        U 5      (       aH  US:w  aA  [        R                  " 5       (       a&  [        R                  " S[        R
                  5        ggggg)aP  Verify API key is provided if url not localhost.

Args:
    api_url: The API URL.
    api_key: The API key.
    tracing_mode: Resolved tracing mode; when ``"otel"`` the warning is
        suppressed because no LangSmith REST calls are made.

Raises:
    LangSmithUserError: If the API key is not provided when using the hosted service.
rG   z8API key must be provided when using hosted LangSmith APIN)r.  ri   tracing_is_enabledro   rp   LangSmithMissingAPIKeyWarning)r"  api_keyrs   s      rV   _validate_api_key_if_hostedrS  `  sU    "  ))&++--MMJ66 . ' * rZ   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
   )r   floatround)scores    rV   _format_feedback_scorerY  }  s"     %UALrZ   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$ )zHGet the tracing sampling rate.

Returns:
    The tracing sampling rate.
NTRACING_SAMPLING_RATEr   rK   zELANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: )ri   rj   r  rV  rl   )tracing_sampling_ratesampling_rate_strsampling_rates      rV   _get_tracing_sampling_rater_    sy     $$001HI  !   56+,MqMA-))"O%
 	
 rZ   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"'r  )itemsstripri   rl   rstriprS  )_write_api_urlsprocessed_write_api_urlsr-  rR  processed_urlprocessed_api_keys         rV   _get_write_api_urlsrj    s    %+O!'--/		--.VWW%++-33C8>>sCJJ3O#MMO11#6<<SA#ME2C/ 0 $#rZ   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 )r   r  r  r   ri   rl   )rl  r  r  s      rV   r  r    si    '1%'C'CtyyNN nW))e=eWE
	s   49 9 
A/'A**A/c                    g r   rY   )rl  s    rV   _ensure_uuidrn    s    GJrZ   Taccept_nullc                   g r   rY   rl  rp  s     rV   rn  rn    s     rZ   Fc               B    U c  U(       a  g [        5       $ [        U 5      $ r   )r?   r  rr  s     rV   rn  rn    s    }wE?rZ   c                n    [         R                  " U 5      nUR                  R                  S5      S   nU$ )Nr*  r   )r  r  r   r  )r-  r%  hosts      rV   
_parse_urlrv    s2    &&s+J""3'*DKrZ   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_maxsizery  
pool_block	blocksize	__class__s         rV   r  _LangSmithHttpAdapter.__init__  s     $)QrZ   c                   > [         (       a  U R                  US'    [        TU ]  " XU40 UD6$ ! [         aB    SU;   a:  [
        R                  S5        UR                  S5        [        TU ]  " XU40 UD6s $ e f = f)Nr  zWAn intermediate HTTPAdapter does not accept the 'blocksize' kwarg. Retrying without it.)URLLIB3_SUPPORTS_BLOCKSIZEr~  r  init_poolmanagerr   rQ   rR   pop)r  connectionsr   blockpool_kwargsr  s        rV   r  &_LangSmithHttpAdapter.init_poolmanager  s    %%'+K$	7+K%W;WW 
	k)2 ,w/%3>  
	s   / AA;9A;)r~  )r  rD  r  rD  ry  zUnion[Retry, int, None]r  boolr  rD  returnNoneF)r   r   r   r   	__attrs__requests_adaptersDEFAULT_POOLSIZEDEFAULT_RETRIESDEFAULT_POOLBLOCKr  r  r   __classcell__r  s   @rV   rx  rx    s    I !2 B B->>/@/P/P,>>	R	R 	R -		R
 	R 	R 
	R 	R rZ   rx  c                  L    \ rS rSr% SrS\S'   S\S'   S\S'   S	\S
'   S	\S'   Srg)ListThreadsItemi  z-Item returned by :meth:`Client.list_threads`.r  	thread_idzlist[ls_schemas.Run]runsrD  rU   Optional[str]min_start_timemax_start_timerY   N)r   r   r   r   r   __annotations__r   rY   rZ   rV   r  r    s!    7N
J!!!!rZ   r  c                      \ rS rSr% Sr/ SQrS\S'   S\S'   S\S'   S	\S
'   S\S'    GS6S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S.                                                       GS7S jjjr      GS8S jr\	SS.           GS9S jj5       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\R(                  GS@S! j5       r\GSAS" j5       rGSBS# jrGSCS$ jrSS%SSSS&S'.                   GSDS( jjrSS).     GSES* jjrSS+S,S-.         GSFS. jjrS\R<                  R>                  S/.             GSGS0 jjr SS\R<                  R>                  S1.             GSHS2 jjr!  GSI       GSJS3 jjr"GSKS4 jr#GSLS5 jr$SS6.     GSMS7 jjr%\GSNS8 j5       r&GSOS9 jr'SSSSSS:.                   GSPS; jjr(SSSSSSS<.               GSQS= jjr)SSSSSSS<.             GSRS> jjr*GSSS? jr+GSTS@ jr,GSUSA jr-\	    GSVSB j5       r.GSLSC jr/GSWSD jr0SSSSSSSE.               GSXSF jjr1  GSY     GSZSG jjr2SSSSSSSE.               GS[SH jjr3SSSSSSSE.               GS\SI jjr4  GSYSSJ.       GS]SK jjjr5SLSSSSSSSM.               GS^SN jjr6SLSO.     GS_SP jjr7SSSSSSSSSSSSSSSSSSSSQ.                                           GS`SR jjr8SSSSSSS<.             GSaSS jjr9SSSSSSS<.               GSbST jjr: GSc     GSdSU jjr;GS6GSeSV jjr<GSfSW jr= GSg     GShSX jjr>SSSSSSSYSZ.                   GSiS[ jjr?SSSSSSSSSSSSSSSSS\.                                   GSjS] jjr@SSSS^SSS_.             GSkS` jjrASSSSSSSSSSSSSSSSSa.                                 GSlSb jjrBSSSc.       GSmSd jjrCSSe.GSnSf jjrDGSoSg jrEGSpSh jrFGSqSi jrG GS6     GSrSj jjrH GS6     GSsSk jjrI GS6SSl.     GStSm jjjrJ GS6SSl.     GStSn jjjrKGSuSo jrL    GSvSp jrMSSSq.       GSwSr jjrNSSSSSs.           GSxSt jjrOSSSSSSu.             GSySv jjrPSSSSSSw.             GSzSx jjrQGS{Sy jrRGS|Sz jrS\TR                  " S{5      SSSS|.       GS}S} jj5       rVSS~.     GS~S jjrWSSS{.     GSS jjrX          GS                     GSS jjrY\TR                  " Sc5      SSSc.     GSS jj5       rZS\R<                  R>                  SSSSS.               GSS jjr[SSS.     GSS jjr\\TR                  " S5      SSS.     GSS jj5       r] GS6SSl.         GSS jjjr^ GS6SSl.     GSS jjjr_SSSSSSS.             GSS jjr`\TR                  " S5      SSS.     GSS jj5       raSSS.         GSS jjrbSSSSS.         GSS jjrcSSSSS.         GSS jjrdSSS.       GSS jjreGSS jrf\TR                  " S5          GS           GSS jj5       rg\TR                  " S5          GS           GSS jj5       rh   GS         GSS jjri  GSI       GSS jjrjSSS.       GSS jjrkSSS.       GSS jjrlSSS.       GSS jjrmGSS jrn GS     GSS jjroSSS.       GSS jjrpSSS.     GSS jjrq\TR                  " S5      SSSSS%S.             GSS jj5       rrS rsS rt\TR                  " S5                  GS                         GSS jj5       ruSS.     GSS jjrv      GSS^SSSSS.                         GSS jjjrwSSSSSSSS.                 GSS jjrxSSSSS.           GSS jjryGSS jrzSS.     GSS jjr{SSSS.       GSS jjr|SSSS.           GSS jjr}      GSS jr~      GSS jrSS.     GSS jjrSSSS.           GSS jjr   GSSS.           GSS jjjrSSSS.           GSS jjr  GSSSSSSS\GR                  GR
                  SSSSSSSSSSSS.                                           GSS jjjrSSSSS.           GSS jjrGSS jrSSSSS.           GSS jjrGSS jr GS6S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S^S.         GSS jjr    GSS jrSSS.           GSS jjr          GSS jrGSS jrSS.       GSS jjrSSSS^S.         GSS jjrSSS.       GSS jjrGSS jrSSSSS.         GSS jjrSSSSS.           GSS jjrGSS jrSSS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r      GSS jrGSS jrGSS jrGSS jrGSS jrSS^SS\GRT                  GRV                  SSS.               GSS jjrGSS jrSSSSS.           GSS jjrSSSS.           GSS jjrSSSSSS.             GSGS  jjrGSGS jr GSg     GSGS jjr GSg     GSGS jjrSSSGS.         GSGS jjrSS^SGS.         GSGS jjrSSSSSGS.             GSGS	 jjrSGS
SSSSSSGS.                   GSGS jjrSGS.     GSGS jjrSSSSSGS.               GSGS jjrSGS.     GSGS jjrSSSSSGS.               GSGS jjrGSGS jrGSGS jrGSGS jrGSGS jrSS^SSSGS.           GSGS jjrSS^SSSGS.           GSGS jjr        GSGS jr                  GSGS jrGSGS jr              GSGS jrGSGS jr              GSGS jr              GSGS  jrGS6GSeGS! jjr\           GS                           GSGS" jj5       r\           GS                           GSGS# jj5       r            GS                             GSGS$ jjr            GS                             GSGS% jjr    GS             GSGS& jjr      GS             GSGS' jjr\\SSSSGS(.             GSGS) jj5       r\SSSGS*GS+SGS,.             GSGS- jj5       r\SSSSGS..         GSGS/ jj5       rSSGS0.       GSGS1 jjrSSSGS2.       GSGS3 jjrGSGS4 jrGS5rg(  Clienti  z.Client for interacting with the LangSmith API.).__weakref__r"  _api_key_workspace_id_headers_custom_headersretry_config
timeout_ms_timeoutrL  _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_inforf  	_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_use_daemon_threads_tracing_error_callback_multipart_disabled_cache_failed_traces_dir_failed_traces_max_bytes_tracing_moder  r  dict[str, str]r  r  ztuple[float, float]r  r  r  NTF)rR  r  r  web_urlrL  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_providerrs   ra   r\  workspace_idmax_batch_size_bytesheaderstracing_error_callbackdisable_prompt_cachecachec                  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US9nUU l        [        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        Or[         R&                  " U5      U l        [         R(                  " U5      U l        [+        U R"                  U R$                  US9  U R"                  U R$                  0U l        U=(       d
    [-        5       U l        [1        U[2        5      (       a  XD4O
U=(       d    SU l        U R4                  S	   S
-  U R4                  S   S
-  4U l        XPl        SU l        U(       a  UO[<        R>                  " 5       nUU l         Ub  [1        U[B        RD                  5      (       a  UO[B        RD                  " S20 UD6U l#        [H        RJ                  " U [L        U R@                  5        [N        RP                  " [L        U5        SU l)        SU l*        SU l+        / U l,        [Z        R\                  " 5       U l/        SU l0        UU l1        SU l2        [         Rf                  " S5      S:H  U l4        US;   a   [k        5       u  nnn n!URl                  " 5       n"U"Ro                  [p        5      n#Uc  [1        U"URr                  5      (       aJ  [u        U#S5      (       a9  [1        [w        URx                  U#5      Rz                  UR|                  5      (       d  [w        [~        U"5      nOU " 5       nUR                  " U5        U!" US9U l0        UU lA        UU lB        U(       a  [         Rf                  " S5      n$U$b  [3        U$5      O[        n%[        U%S9U lH        [Z        R                  " [        [H        R                  " U 5      4U Rh                  S9R                  5         OSU lH        [        U R.                  [        [        S-   S9n&U R@                  R                  SU&5        U R@                  R                  SU&5        [        R                  " SS9" U R                  5      U lT        XlU        U	b  U	O[         Rf                  " S5      S:H  U lV        U
b  U
O[         Rf                  " S 5      S:H  U lW        Ub  UO[         Rf                  " S!5      S:H  U lX        XlY        XlZ        Xl[        U=(       d    S"U l\        [        R                  " 5       U l^        Ub  Uc  [        S#5      eUc  Ub  [        S$5      eSU l`        [         Rf                  " S%5      bF  Sn' S	SKan'U'(       a8  S'n)S(n*S
n+Sn, U'R                  U R"                  U R$                  U)U*U+U,5      U l`        SU lg        SU lh        UU li        Ub!  U(       a  [        R                  " S*[        SS9  Ub@  [        R                  " S+[        SS9  USL a  SU lk        O3US,L a  [        U lk        O"UU lk        OU(       d  [        U lk        OSU lk        [         Rf                  " S-5      U lm        [         Rf                  " S.5      n- U-(       a  [3        U-5      OS	n.U.S	:  a  [3        U.S/-  S/-  5      OS0U ln        g! [         aK    [        R                  " SU< S3SS9  SU l0        SU l        [+        U R"                  U R$                  SS9   GNf = f! [         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NSn(A(ff = f! [        [        4 a     [        R                  S1U-5        S0U ln         gf = f)3uw  Initialize a `Client` instance.

Args:
    api_url: URL for the LangSmith API.

        Defaults to the `LANGCHAIN_ENDPOINT` environment variable or
        `https://api.smith.langchain.com` if not set.
    api_key: API key for the LangSmith API.

        Defaults to the `LANGCHAIN_API_KEY` environment variable.
    retry_config: Retry configuration for the `HTTPAdapter`.
    timeout_ms: Timeout for the `HTTPAdapter`.

        Can also be a 2-tuple of `(connect timeout, read timeout)` to set them
        separately.
    web_url: URL for the LangSmith web app.

        Default is auto-inferred from the `ENDPOINT`.
    session: The session to use for requests.

        If `None`, a new session will be created.
    auto_batch_tracing: Whether to automatically batch tracing.
    anonymizer: A function applied for masking serialized run inputs and
        outputs, before sending to the API.
    hide_inputs: Whether to hide run inputs when tracing with this client.

        If `True`, hides the entire inputs.

        If a function, applied to all run inputs when creating runs.
    hide_outputs: Whether to hide run outputs when tracing with this client.

        If `True`, hides the entire outputs.

        If a function, applied to all run outputs when creating runs.
    hide_metadata: 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: 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: 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: 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: 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: 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 tracer provider for OpenTelemetry
        integration.

        If not provided, a LangSmith-specific tracer provider will be used.
    tracing_mode: Where to send traces.  One of:

        - ``"langsmith"`` (default) — LangSmith only.
        - ``"otel"`` — OpenTelemetry export only.
        - ``"hybrid"`` — both OTel and LangSmith.

        Falls back to the ``LANGSMITH_TRACING_MODE`` env var, then to
        the legacy ``OTEL_ENABLED`` / ``OTEL_ONLY`` env vars, then to
        ``"langsmith"``.
    otel_enabled: *Deprecated.* Use ``tracing_mode`` instead.

        When ``True``, interpreted as ``tracing_mode="hybrid"``
        (or ``"otel"`` if the ``OTEL_ONLY`` env var is set).
        Will be removed in the next minor version.
    tracing_sampling_rate: 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: The workspace ID.

        Required for org-scoped API keys.
    max_batch_size_bytes: The maximum size of a batch of runs in bytes.

        If not provided, the default is set by the server.
    headers: 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.
    disable_prompt_cache: Disable prompt caching for this client.

        By default, prompt caching is enabled globally using a singleton cache.
        Set this to `True` to disable caching for this specific client instance.

        To configure the global cache, use `configure_global_prompt_cache()`.

        !!! example

            ```python
            from langsmith import Client, configure_global_prompt_cache

            # Use default global cache
            client = Client()

            # Disable caching for this client
            client_no_cache = Client(disable_prompt_cache=True)

            # Configure global cache settings
            configure_global_prompt_cache(max_size=200, ttl_seconds=7200)
            ```
    cache: **[Deprecated]** Control prompt caching behavior.

        This parameter is deprecated. Use `configure_global_prompt_cache()` to
        configure caching, or `disable_prompt_cache=True` to disable it.

        - `True`: Enable caching with the global singleton (default behavior)
        - `False`: Disable caching (equivalent to `disable_prompt_cache=True`)
        - `Cache(...)`/`PromptCache(...)`: Use a custom cache instance

        !!! example

            ```python
            from langsmith import Client, Cache, configure_global_prompt_cache

            # Old API (deprecated but still supported)
            client = Client(cache=True)  # Use global cache
            client = Client(cache=False)  # Disable cache

            # Use custom cache instance
            my_cache = Cache(max_size=100, ttl_seconds=3600)
            client = Client(cache=my_cache)

            # New API (recommended)
            client = Client()  # Use global cache (default)

            # Configure global cache for all clients
            configure_global_prompt_cache(max_size=200, ttl_seconds=7200)

            # Or disable for a specific client
            client = Client(disable_prompt_cache=True)
            ```

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.r`   rN  )i'  i`  r     rK   NF
USE_DAEMONtrue)rG   rH   _tracer)tracer_providerztracing_mode=zu requires OpenTelemetry packages. Install with `pip install langsmith[otel]`. Falling back to LangSmith-only tracing.r   rg   rF   TRACING_QUEUE_MAX_SIZEr   )targetargsdaemon)ry  r  r  http://https://r]   HIDE_INPUTS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: %szBoth 'cache' and 'disable_prompt_cache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value.zThe 'cache' parameter is deprecated and will be removed in a future version. Use 'configure_global_prompt_cache()' to configure the global cache, or 'disable_prompt_cache=True' to disable caching for this client.TFAILED_TRACES_DIRFAILED_TRACES_MAX_MBi   i  @zJInvalid value for LANGSMITH_FAILED_TRACES_MAX_MB: %r, using default 100 MBrY   )pri   rl   osgetenvrz   r  r_  r  r   r  rj  rf  get_workspace_idr  r  nextiterr"  rR  get_api_urlget_api_keyrS  rI  r  r   rD  r  r  r  r  requestsSessionrL  
ls_schemasLangSmithInfor  weakreffinalizerM  atexitregisterr  r  r  r  	threadingLockr  r  r  r  rj   r  r   get_tracer_provider
get_tracerr   ProxyTracerProviderhasattrr   ProxyTracerr  
NoOpTracerr   set_tracer_providerr  r  r   ro   rp   r-   r   r  Thread_tracing_control_thread_funcrefstartrx  r*   r)   mount	functoolsr	   _get_data_typer  r  r  r  r  r  r  r  r  rN   r  r   r  langsmith_pyo3rQ   rR   reprBlockingTracingClientr   r  r  r  DeprecationWarningr  rA   r  r  OverflowError)/r  r"  rR  r  r  r  rL  r  r  r  r  r  r  r  r  r  r  r  r  rs   ra   r\  r  r  r  r  r  r  resolved_modesession_r   r~   r   r   existing_providertracerqueue_maxsize_strqueue_maxsizeadapterr  r  queue_capacity
batch_sizebatch_timeout_millisworker_threads_max_mb_str_max_mbs/                                                  rV   r  Client.__init__B  s   d x--? 
 II*++ryy9M/N/Nii233--0 
 .lV*7#=>S#T 47E!<O=
 &66|D&}"T%9%9 :;DL//=DL#//8DL#//8DL'dll %)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QS$-NN$4!59%9"). #+#7#7#E#O ..* !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"#- ,?)   ( 4 45M N %0 %&, 
 ;H%;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$'=$ !5MM1 # MMR # ~59$4 $%0DKDK191E1E2
 **+AB	>*5c+&1G.5kGdNT)*?P )E  #M#4 5> >  !	 &*"%0"+LL$,,[n  6G . ! NNZQ n M* 	>NN'
 ->D)	>sV   C ]" $^: 8/_1 /2`( "A^76^7:
_._))_.1
`%;`  `%(-aac                    U R                   (       d  g U" 5       n[        U[        5      (       a  UR                  S5      nU R	                  U R                   USUU R
                  S9  g! [         a     gf = f)u   Dump a failed trace payload to disk if a fallback directory is configured.

*body_fn* is called lazily inside a try/except so that any serialization
errors are silently swallowed — we must never raise from a failure path.
Nzutf-8zruns/multipart)endpointr  	max_bytes)r  r   r  encode_write_trace_to_fallback_dirr  r   )r  body_fnr  bodys       rV   _dump_failed_traceClient._dump_failed_trace"  sy     &&	9D$$${{7+--'')77 .   		s   AA) )
A65A6)r0  c               >   SUU[         R                  " U5      R                  5       S.nS[        R                  " 5       S S[        R
                  " 5       R                  SS  S3n[        U 5      U-  n U [        ;  a/  UR                  R                  S	S	S
9  [        R                  U 5        UbP  US:  aJ  [        U 5      n[        S UR                  S5       5       5      n	X:  a  [        R                  SU U	U5        gUR!                  S5      n
U
R#                  [$        R&                  " U5      5        U
R)                  S5        U
R+                  U5        [        R                  SU5        g! [,         a!  n[        R/                  SU U5         SnAgSnAff = f)a  Persist a failed trace payload to a local fallback directory.

Saves a self-contained JSON file with the endpoint, the HTTP headers
required for replay, and the base64-encoded request body.  Can be
replayed later with a simple POST:

    POST /<endpoint>
    Content-Type: <value from saved headers>
    [Content-Encoding: <value from saved headers>]
    <decoded body>

If *max_bytes* is set, new traces are dropped when the directory is
already at or over the budget.
rK   )r   r/  r  body_base64trace_z.6fr   N   z.jsonT)parentsexist_okr   c              3     #    U  H6  nUR                  5       (       d  M  UR                  5       R                  v   M8     g 7fr   )is_filestatst_size)r   fs     rV   r   6Client._write_trace_to_fallback_dir.<locals>.<genexpr>b  s.      :yy{ %AFFH$$:s
   A !A ztrace_*.jsonzCould not write trace to fallback dir %s as it's already over size limit (%d bytes >= %d bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.z.tmpi  zALangSmith trace upload failed; data saved to %s for later replay.zELangSmith tracing error: could not write trace to fallback dir %s: %s)base64	b64encodedecoderN   r  uuid4hexr   r   parentmkdiraddsumglobrQ   rR   with_suffix
write_textjsondumpschmodrenamer   error)	directoryr4  r/  r  r0  envelopefilenamefilepathdir_pathr8  	temp_path	write_excs               rV   r2  #Client._write_trace_to_fallback_dir<  s}   0  !++D188:	
 DIIK,Adjjl.>.>r.B-C5I	?X-#	 66%%dT%B&**95$Q	? %]]>: 
 %NNO "!  ,,V4I  H!56OOE"X&NNS  	LLW 	s    6BE1 A.E1 1
F;FFc                &    U R                   nSU S3$ )z}Return an HTML representation of the instance with a link to the URL.

Returns:
    The HTML representation of the instance.
z	<a href="z6", target="_blank" rel="noopener">LangSmith Client</a>)	_host_url)r  links     rV   _repr_html_Client._repr_html_  s     ~~4& VWWrZ   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   rQ   rS  )r  rS  s     rV   _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:
    The string representation of the instance.
zClient (API URL: )r"  r  s    rV   __repr__Client.__repr__  s     #4<<.22rZ   c                ,    [        U R                  5      $ r   )rv  r"  ri  s    rV   _hostClient._host  s    $,,''rZ   c                X    [         R                  " U R                  U R                  5      $ )zThe web host url.)ri   get_host_urlr  r"  ri  s    rV   r]  Client._host_url  s     $$T]]DLLAArZ   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AcceptX-Tenant-Id)rF   r   r  r  rR  	X_API_KEYr  )r  r  s     rV   _compute_headersClient._compute_headers  sd    ))*?*?)@A(

 	t++,<<!%GI%)%7%7GM"rZ   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__rw  )r  	attr_namerl  s      rV   _set_header_affecting_attr!Client._set_header_affecting_attr  s-    4E24T-B-B-DErZ   c                    U R                   $ )z+Return the API key used for authentication.)r  ri  s    rV   rR  Client.api_key  s     }}rZ   c                (    U R                  SU5        g )Nr  r}  r  rl  s     rV   rR  r    s    ''
E:rZ   c                    U R                   $ )z.Return the workspace ID used for API requests.)r  ri  s    rV   r  Client.workspace_id       !!!rZ   c                (    U R                  SU5        g )Nr  r  r  s     rV   r  r    s    ''?rZ   c                    U R                   $ )z0Return the custom headers used for API requests.)r  ri  s    rV   r  Client.headers  s     ###rZ   c                :    U R                  SU=(       d    0 5        g )Nr  r  r  s     rV   r  r    s    ''(95;BGrZ   c           	     b   U R                   b  U R                   $ U R                  S:X  a3  U R                  b&  [        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.
NrG   GETz/infort  rs  )r  timeoutzFailed to get info from : rY   )r  r  r  r  r  request_with_retriesr  ri   raise_for_status_with_textrO  BaseExceptionrQ   rR   r"  r  )r  responser  s      rV   r  Client.info  s    ::!:: 'D,>,>,J#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 
D.AD))D.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                   $ )z\Get the settings for the current tenant.

Returns:
    The settings for the current tenant.
r  z	/settingsrY   )r  r  ri   r  r  LangSmithSettingsrO  )r  r  s     rV   _get_settingsClient._get_settings  sS     >>!00DH//9'99LHMMOLDN~~rZ   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   r  r  batch_ingest_configr  get)r  content_lengthr  bic
size_limits        rV   _content_above_sizeClient._content_above_size  s    !TZZ%7J,,djj9&&//N377;M3N
&((8 9))3G= rZ   rK    )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a]  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  a7  [        R                  " SUR8                   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      S0-
  5      -  nU U U 3n[        R                  " S1U SU SU S[;        U5       S2U S3U 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                  S4S55      nU(       aZ  S6Rc                  [        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                  S7S85      5      n O8! [Z         a+  n[,        Rg                  S9[;        U5      5        S:n  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)<aq  Send a request with retries.

Args:
    method: The HTTP request method.
    pathname: The pathname of the request URL. Will be appended to the API URL.
    request_kwargs: Additional request parameters.
    stop_after_attempt: The number of attempts to make.
    retry_on: The exceptions to retry on.

        In addition to: `[LangSmithConnectionError, LangSmithAPIError]`.
    to_ignore: The exceptions to ignore / pass on.
    handle_response: A function to handle the response and return whether to
        continue retrying.
    _context: The context of the request.
    **kwargs: 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  r  r  datafilesContent-Typers  )ru  rY   NstreamFzPassing on exception %srK   r   r7  i  zServer error (z) caused failure to  z in LangSmith API. r6  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  rS  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 r  z'Please confirm your LANGCHAIN_ENDPOINT.z(Please confirm your internet connection.zContent-Lengthr      *r      z#Connection error caused failure to z
Content-Length: z

API Key: rL  zsession (project)
zretry-after30zInvalid retry-after header: %s   z in LangSmith API.)4r  r  r  ri   FilterLangSmithRetryFilterPoolFullWarningr  rm  LangSmithConnectionErrorLangSmithRequestTimeoutLangSmithAPIErrorrangefilter_logs_urllib3_loggerrL  request_construct_urlr"  r  r  
exceptionsReadTimeoutrQ   r   randomrN   sleep	HTTPErrorstatus_coder  LangSmithRateLimitErrorLangSmithAuthErrorLangSmithNotFoundErrorLangSmithConflictErrorrO  rl   r   KeyErrorr   ConnectionErrorrD  r  r  maxr  r   r   r  replacerm   rV  rR   )!r  methodpathnamer  r  r  r  r  r  r	  logging_filters	retry_on_
to_ignore_r  idxr  
sleep_timeshould_continue
error_data
error_coderecommendationr  size_recrR  prefixsuffixfillermasked_api_keyr  msgargemsgretry_afters!                                    rV   r  Client.request_with_retries  sU   N (-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"*"<"<"01E1E0FFZ[aZb"#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  [AH92[9["R)3[:E!R)>PR)P.+R)-P..A;R))[W/A$T;:W/;U
W/	U

B%W//[<A9Z>5Z
4Z>>[[_8[5&_85$_8%] ?_8 
]5
!]0+_80]557_80A_87_8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: The path of the request URL.
    params: The query parameters.

Yields:
    The items in the paginated list.
offsetr   limitr  r  r  N)copyr  r  rO  r  )r  r  r  params_r  r  rc  s          rV   _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 POSTr  )r4  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)a  Get a cursor paginated list of items.

Args:
    path: The path of the request URL.
    body: The query body.
    request_method: The HTTP request method.
    data_key: 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_jsonrO  r  )	r  r  r4  r  r  r  r  response_bodyr  s	            rV   _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$ )a  Upload a dataframe as individual examples to the LangSmith API.

Args:
    df: The dataframe to upload.
    name: The name of the dataset.
    input_keys: The input keys.
    output_keys: The output keys.
    description: The description of the dataset.
    data_type: The data type of the dataset.

Returns:
    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  dfr  r  r  r  r  csv_files           rV   upload_dataframeClient.upload_dataframeJ  sY    ` ::<
		(%	(a"!##  
 	
rZ   )r  r  r  c               z   UUS.nU(       a  XGS'   U(       a  XWS'   U(       a  [         R                  " U5      US'   [        [        R                  " 5       5      US'   [        U[        5      (       aB  [        US5       nS[        U5      R                  US40n	U R                  S	S
UU	S9n
SSS5        OQ[        U[        5      (       a1  Un[        U5      S:X  a  US   US   S4n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)aB  Upload a CSV file to the LangSmith API.

Args:
    csv_file: 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: The input keys.
    output_keys: The output keys.
    name: The name of the dataset.
    description: The description of the dataset.
    data_type: The data type of the dataset.

Returns:
    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  r  r  r  r  r   rbfileztext/csvr  z/datasets/upload)r  r  Nr   r   rK   z"csv_file must be a string or tupledetailzalready existsr  Dataset z already existsr]  r  rY   )ri   get_enum_valuer  r  rF  r   openr   r  r  r   r  r   r  rO  r  r  Datasetr]  _get_optional_tenant_id)r  r  r  r  r  r  r  r  rA  file_r  
file_tupleresult	file_names                 rV   r  Client.upload_csv  s   j %&
 L"- ( 7 7	 BD&T
h$$h%$x."5"5q*!EF44&	 5  &% %((!J8}!&qk8A;
C
00"z*	 1 H ABB++H5v"2fX6F"F$.x$=$=8A;I!,R0Ix	{/BCC!! 

nn335
 	
7 &%s   >-F,,
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;   a  US   b  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$ )a  Transform the given run object into a dictionary representation.

Args:
    run: The run object to transform.
    update: Whether the payload is for an "update" event.
    copy: Whether to deepcopy run inputs/outputs.

Returns:
    The transformed run object as a dictionary.

model_dumpr   inputsNoutputseventsextrar   
start_time
serializedrun_type)r1  r  graph)r  callablegetattrr  r   r   r  rF  r   r  r  ri   deepish_copy_hide_run_inputs_hide_run_outputs_filter_new_token_events_hide_run_metadatar  datetimerT   timezoneutcr  )r  runr  r  
run_creater  s         rV   _run_transformClient._run_transform  s;     3%%(733M*N*N"~~/J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!z!j&:&F#'#@#@HAU#VJx 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;rZ   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 )Nr  runtimer   )	r  ls_envget_runtime_environmentr   r   
setdefaultget_langchain_env_var_metadatar  rc  )
r  r  runtime_envr,  	run_extrar0  r   langchain_metadatakvs
             rV   _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  ri  s    rV   _should_sampleClient._should_sample.  s(    ##+}}!9!999rZ   patchc               d   U R                   c  [        U5      $ [        4SS jjnU(       ak  / nU Ha  n[        U" US5      5      nX`R                  ;  a  UR                  U5        M7  U" US5      U:X  d  MF  U R                  R                  U5        Mc     U$ / nU H  nU" USS 5      =(       d	    U" US5      nX`R                  ;   a  M.  U" US5      U:X  aE  U R                  5       (       a  UR                  U5        Mc  U R                  R                  U5        M  UR                  U5        M     U$ )Nc                |     X   $ ! [         [        4 a%    U[        L a  [        X5      s $ [        XU5      s $ f = fr   )r  r   _UNSETr"  )r+  keydefaults      rV   _val)Client._filter_for_sampling.<locals>._val<  sB    2xi( 2f$"3,,s112s    $;;;trace_idr   )r+  r   rD  r  rE  r   r  r   )	r  r   rC  r  r  appendremover=  rJ  )r  r  r@  rF  sampledr+  rH  s          rV   _filter_for_samplingClient._filter_for_sampling3  s    ##+:4: 	2 G#Dj$9:#<#<<NN3'#t_0--44X>  NGZ6I$sD/ 888 T?h.**,,s+1155h? NN3'   NrZ   c                    U R                   $ )zPer-client tracing mode.)r  ri  s    rV   rs   Client.tracing_modea  r  rZ   c                    U R                   c   e U R                   R                  U5        g! [         a&    [        SU R                   R                   S35         gf = f)z3Put an item on the tracing queue, dropping if full.Nztracing queue full (maxsize=rg  )r  
put_nowaitr   rW   r   )r  items     rV   _put_tracing_queueClient._put_tracing_queuef  s]    !!---	))$/ 	.t/A/A/I/I.J!L	s   - -AA)project_namerevision_iddangerously_allow_filesystemrR  r"  c                  U	R                  SS5      n
U	R                  SS5      nU	R                  SS5      nU	R                  SS5      n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
  X^S   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                  (       aw  U	R                  S5      (       da  U R                     U R                  R                  SUUUU
UUUS.45        U R!                  5       (       a  U R#                  5          SSS5        gU R%                  UUUU
UUU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.
    service_key (Optional[str]): The service JWT key for service-to-service auth.
    tenant_id (Optional[str]): The tenant ID for multi-tenant requests.
    authorization (Optional[str]): The Authorization header value.
    cookie (Optional[str]): The Cookie header value.
    **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,
    )
    ```
service_keyN	tenant_idauthorizationcookiesession_name)r]  r  r  r  r  r   rV  Fr  attachmentsrK   UMust set dangerously_allow_filesystem=True to allow passing in Paths for attachments.is_run_ops_buffer_flushpostr"  rR  rY  rZ  r[  r\  rR  r"  rY  rZ  r[  r\  )r  ri   get_tracer_projectrL  r-  r:  r  r   r   r   r   r   r  r  r  rI  _should_flush_run_ops_buffer_flush_run_ops_buffer_create_run)r  r  r  r  rU  rV  rW  rR  r"  r	  rY  rZ  r[  r\  r,  
attachments                   rV   
create_runClient.create_runp  s   v #)**]D"A &

; =	$*JJ$E#ZZ$7# 
vzz'')(



( 

 ((*66"=Hw
+M:((%(@
  *.>>-(4(7>>@
z511":a=$7788$o  A ))&**=V2W2W**$$++"'.'.+6)2-:&, 4466..0% +*( '#+  ) +*s   +AG
G$rd  c                  UR                  S5      Gb"  UR                  S5      Gb  U R                  b  U R                  R                  U5        g U R                  Gb  Uc  Uc  Uc  Uc  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,                  bK  U R/                  [1        US   UUUUUUUU R3                  U R4                  R7                  5       5      S	9	5        g U R/                  [1        US   UUUUUUUS
95        g U R9                  UUUUUUUS
9  g U R9                  UUUUUUUS
9  g ! , (       d  f       GN= f)NrH  dotted_order@Run compression is enabled but threading event is not configuredrb  r  5Adding compressed multipart to queue with context: %srK   /Adding to tracing queue: trace_id=%s, run_id=%srR  r"  rY  rZ  r[  r\  otel_contextrd  )r  r  rj  r  r  r   r;   r=   rQ   logcontextlockr9   r+   trace_countr   _close_filesr   r   r  rH  r   r  rS  r%   r  r  get_current_span_create_run_non_batch)r  r,  rR  r"  rY  rZ  r[  r\  serialized_opmultipart_formopened_filesenqueueds               rV   rh  Client._create_run  st    NN:&2~.:  ,!!,,Z8&&2OO'%!)N--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)$+$+(3&/*7#))-)B)B $ 0 0 A A C*  ++(&~6)$+$+(3&/*7#)	 **## +'"/! +  &&'#+ ' { 10s   AI
Ic               .   / n[        X2XFU/5      n	U	(       aj  U=(       d    U R                  n
[        U R                  UUUUUU R                  S9n U R                  SU
 S3[        U5      US.[        R                  4S9  OmU R                  R                  5        HO  u  p [        U R                  US S S S S S9nU R                  SU S3[        U5      US.[        R                  4S9  MQ     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)	NrR  rY  rZ  r[  r\  fallback_api_keyr  /runsr  r  )r  r  rK   )r  r   )r   r"  _apply_auth_overridesr  rR  r  r  ri   r  r   rI  rf  rc  r  LangSmithExceptionGrouprd  )r  r,  rR  r"  rY  rZ  r[  r\  errorsuse_overridetarget_api_urlr  r  write_api_urlwrite_api_keyexception_groups                   rV   ry  Client._create_run_non_batch^	  s    Gk&QR$4N+'#+!%G!))%&e, +J 7#*$  (>>@ *  150D0D0J0J0L,%3 -$("&&*#)-G --(//$/
$;'.( $,#B#B"D .  1M, 6{Q"*"B"Bf"U33OD%%33F1I>Qi 5  !a  !0 ! %MM!$$%s1   0E "A	E.
E+E&&E+.
F8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  r  json_inputss      rV   r$  Client._hide_run_inputs	  sf    $I!--F(;<K##K00%M  ((rZ   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  r  json_outputss      rV   r%  Client._hide_run_outputs	  sf    %I"==W)=>L##L11&N!!'**rZ   c                h    U R                   SL a  0 $ U R                   SL a  U$ U R                  U5      $ r  )r  )r  r   s     rV   r'  Client._hide_run_metadata	  s9    $&I%'O""8,,rZ   c                    U (       d  U $ U  VVVs/ s HG  nUR                  S5      S:X  a-  UR                  5        VVs0 s H  u  p#US:w  d  M  X#_M     snnOUPMI     snnn$ s  snnf s  snnnf )zFilter content from new_token events.

This prevents streaming LLM output from being uploaded via events.

Args:
    events: The events to filter.

Returns:
    The filtered events with kwargs removed from new_token events.
r  	new_tokenr	  )r  rc  )r  eventr8  r9  s       rV   r&  Client._filter_new_token_events	  sv     M
  	
   yy K/ $kkm=mdaqH}TQTm=  	
 	
=
s   .A)A#A#
A)#A)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.FTr  )r  r  r  r  rN   r  )r  time_since_last_flushs     rV   rf  #Client._should_flush_run_ops_buffer	  st    ## %%1D(()T-F-FF **6$(IIK$2V2V$V!$)H)H4)OPrZ   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   clearrN   r  &langsmith._internal._background_threadr  r  submitr  rJ  RuntimeError)r  batch_to_processr  r  futures        rV   rg  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rc  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        XR                     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@                  " UU   5      nU(       d  M&  US:  a|  U[C        US   S   5      -   U:  ad  U RE                  [        R&                  " U5      SU SSRG                  UU   5       3UUUUUUS9  SnURI                  5         URI                  5         URK                  5       u  nnU[C        U5      -  nUU   R!                  [        R                  " U5      5        UU   R!                  U5        U(       a  M  GM     U(       aT  SRG                  S URM                  5        5       5      nU RE                  [        R&                  " U5      SU-   UUUUUUS9  g g )N)rb  r@  r  r  r  r  rS  r  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   rb  r@  rK   r  r  ; )r  r"  rR  rY  rZ  r[  r\  c              3  R   #    U  H  u  pU S SR                  U5       3v   M     g7f)r  r  N)rm   )r   r8  r9  s      rV   r   /Client._batch_ingest_run_ops.<locals>.<genexpr>[
  s'     WCV411#R		!~ 6CVs   %')'r   r7   r$   r  _noner  Fragmentr  r  r  rS  r  r_  rQ   rR   	operationrI  rH  r   rP  r6   r   r  r  r  r  r,   collectionsdefaultdictr   r   r   dequer  _post_batch_ingest_runsrm   r  popleftrc  )r  opsr"  rR  rY  rZ  r[  r\  ids_and_partial_bodyop	curr_dictr  r  body_chunkscontext_ids	body_sizerD  
body_dequecurr_id	curr_bodyrt  s                        rV   _batch_ingest_run_opsClient._batch_ingest_run_ops
  sy    
 	 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{37G-H,I!J ' '$/"+&3% 1 	 !"I%%'%%'%/%7%7%9"S^+	C ''(8(8(CDC ''0+ * K0 iiW;CTCTCVWWG((k*'#+ ) 	 rZ   c                   U(       d  U(       d  gU R                  U=(       d    [        5      nU R                  U=(       d    [        SS9nU(       d  U(       d  gU Vs/ s H  o0R                  USS9PM     nnU Vs/ s H  o0R                  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 R                  (       aB  U(       a  [        U R                  U5      5      nU(       a  [        U R                  U5      5      nU R                  XE-   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 )ah
  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.

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)
    ```
NTr?  Fr^  )r  r  rH  rm  z:Batch ingest requires trace_id and dotted_order to be set.c              3  :   #    U  H  n[        S U5      v   M     g7frb  Nr;   r   r+  s     rV   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r@  Nr  r  s     rV   r   r  
  s     R\c+GS99\r  )rL  r   r-  r  ri   rl   r  r   r:  r   r7   r8   r   r0  r  )r  creater  r+  create_dictsupdate_dictsserialized_opss          rV   batch_ingest_runsClient.batch_ingest_runsg
  s   ~ f**6+>Y?**6+>Yd*KfHNO++Ce+<OIO
IO#Du= 	 
  C77:&&cggn.E.E11P   
  C77:&&cggn.E.E11P    ))#D$B$B<$PQ#D$B$B<$PQ  !<= '(/OOQLQR\R

 	"">2K P
s   G3=G8c                  [        X4XWU/5      n	U	(       a>  U=(       d    U R                  n
U
[        0 U R                  EUUUUUU R                  S94/nOIU R
                  R                  5        V
Vs/ s H"  u  pU
[        0 U R                  EUS S S S S S94PM$     nn
nU H/  u  p U R                  SU
 S3UUS.[        R                  4SUS9  M1     g s  snn
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[%        U5       35         Of = fU R'                  U5         S nAM  S nAff = f)	Nr  r  z/runs/batchr  r\   )r  r  r  r  r  zFailed to batch ingest runs: )r   r"  r  r  rR  rf  rc  r  ri   r  r   	tracebackformat_exception_onlyr   rm   re  rQ   rR   r  rd  )r  r4  r  r"  rR  rY  rZ  r[  r\  r  r  	endpointstarget_api_keyr  r  exc_desc_linesexc_descs                    rV   r  Client._post_batch_ingest_runs
  s    Gk&QR$4N #))4==) '$/"+&3%)-I8 7;6J6J6P6P6R 7S2N #))4==) .$("&&*#)- 7S    (1#N7))%&k2 $#*$  (>>@'(% * 
 (1!:  7N%.%D%DT!Wa%PN!ww~6==?HNN%B8*#MN  NNN%B47)#LMN33A667s=   1)C%)C
F	$AD<;F<+E*'F)E**FF	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(       a9   U R                  UUUUUUUS9  [!        [#        U	R%                  5       5      5        g g ! [        R                   aU    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UUUUUUS9   Nf = f! [!        [#        U	R%                  5       5      5        f = f)Nz+Unknown operation type in tracing queue: %src  T)r   r7   r=   rI  r  r6   r<   rQ   rS  r   r5   _send_multipart_reqri   r  r  r  rw  r   r   )r  r  r"  rR  rY  rZ  r[  r\  partsopened_files_dictr  partr|  acc_multipartrun_opss                  rV   _multipart_ingest_opsClient._multipart_ingest_ops;  sr    13:<B"455 LBO T"!((6B ;<<PQST JDQSHU  9??((!## +'"/! ) 4 T"3":":"<=>9  22  ,0((+V"z">T/U2VV.. ' '$/"+&3% / " T"3":":"<=>s6   8C1 1ED4-D43$EE EE $F)rW  c          	        U(       d  U(       d  gU R                  U=(       d    [        5      nU R                  U=(       d    [        SS9nU(       d  U(       d  gU Vs/ s H  o@R                  U5      PM     nnU Vs/ s H  o@R                  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  oDS	   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(       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 )aj
  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.

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)
    ```
NTr?  )r  rH  rm  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   c              3  :   #    U  H  n[        S U5      v   M     g7fr  r  r  s     rV   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     rV   r   r  	  s     N#'55r  rK   r`  )rL  r   r-  r  ri   rl   rc  rI  r:  r8   r   r   r0  r   r7   r_  r   r   r   r   r  )r  r  r  rW  r+  r  r  create_by_idstandalone_updatesr8  r9  r  r  ri  s                 rV   multipart_ingestClient.multipart_ingestu  so   | &**6+>Y?**6+>Yd*Kf<BCFS++C0FCIOP#++C+=P#wwz**#''.2I2I"556  $ #wwz**#''.2I2I"556  $ L6BClsIsNlLC-/#t9, #		=9:T3A6 !, '--c2 $ -LL  .  . =MMNN
 !B"455"..."$.."7"7"9J":u55&z!}d;; < <(s  #: ! 	"">2A DP, Ds   K>K
Kr\   )attemptsr"  rR  rY  rZ  r[  r\  c               4  ^^ UR                   mUR                  n	[        X4XWU/5      n
U
(       a>  U=(       d    U R                  nU[	        0 U R
                  EUUUUUU R                  S94/nOIU R                  R                  5        VVs/ s H"  u  pU[	        0 U R
                  EUS S S S S S94PM$     nnnU H  u  p[        SUS-   5       Ho  n [        R                  " T[        S9nUR                  S::  a  UR                  5       mOUmU R                  SU S3T0 UESUR                   0E["        S.SU	S	9    M     M     g s  snnf ! [$        R&                   a       M  [$        R(                  [$        R*                  [$        R,                  4 a/  nX:X  a  [.        R1                  S
U 35        Un S nAO S nAM  S nAf[2         a  n [4        R6                  " [9        U5      U5      nSR;                  U5      R=                  5       n[.        R1                  S
U 35        O1! [2         a$    [.        R1                  S
[?        U5       35         Of = fUn S nAOS nAff = fU RA                  UU4S jSS[         305        U RC                  U5          GM  )Nr  rK   boundary -1r  /runs/multipartr  r  r  r  r  r  r  z!Failed to multipart ingest runs: r  c                    > [        T [        5      (       a  T $ [        R                  " T[        S9R                  5       $ )Nr  )r   bytesrqtb_multipartMultipartEncoderr+   	to_string)r  r  s   rV   <lambda>,Client._send_multipart_req.<locals>.<lambda>}  s9    %dE22  &+<<!I#)+	&rZ   multipart/form-data; boundary=)"r  rt  r   r"  r  r  rR  rf  rc  r  r  r  r+   r  r  r  content_type_TRACING_SEND_TIMEOUTri   r  r  r  r  rQ   rR   r   r  r  r   rm   re  r  r5  rd  )r  accr  r"  rR  rY  rZ  r[  r\  r  r  r  r  r  headers_for_endpointr  encoderr   	_fail_excr  r  r  r  r  s                         @@rV   r  Client._send_multipart_req  s    		;; Gk&QR$4N #))4==) '$/"+&3%)-I8 7;6J6J6P6P6R 7S2N #))4==) .$("&&*#)- 7S    5>0NQ1-(",==eiXG{{j0&002&--)*/:$(("6( .0D0D( (=( ,-!) .  + . 5>!N  66 5544.. 	!
 )J3%'PQ/2	   "V)2)H)HaRS)T#%77>#:#A#A#C)J8*'UV$ V)J4PQ7)'TUV !I" '' $'Ei[%QR	 33I>sP   )EA*EI"#2I"F??I"AH%$I%+I	II	II"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 [        U R                  USSSSSS9nS[         3US'   S	US
'   U(       a  [        US   5      OSUS'   U(       a  [        US   5      OSUS'   [        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  a  [        R'                  SU	 35        U	n
 Sn	A	OUR	                  S5         Sn	A	GM(  Sn	A	f[(         a  n [*        R,                  " [/        U5      U5      nSR                  U5      R1                  5       n[        R'                  SU 35        O1! [(         a$    [        R'                  S[3        U5       35         Of = fUn
 SnAOSnAff = fUR	                  S5        U R5                  UR6                  S[         3S	S.5        U R9                  U
5          GM?  )zASend a zstd-compressed multipart form data stream to the backend.r  rt  r   rK   Nr  r  r  zstdContent-Encodingr  zX-Pre-Compressed-SizezX-Post-Compressed-Sizez3Sending compressed multipart request with context: r  r  r  r  z,Failed to send compressed multipart ingest: )r  r  )rm   r"  rf  rc  r  r  r  r  r+   r  rQ   r   r  r  ri   r  r  r  r  rR   r   r  r  r   re  r  r5  readrd  )r  data_streamcompressed_traces_infor  r  r"  rR  r  r  r   r  r  r  r  s                 rV   _send_compressed_multipart_req%Client._send_compressed_multipart_req  s    		'+y""EF $ 4 4 : : <GQQ1-="3 '$("&&*#)-G 9D N+ 39G./:P2156VX 34 ;Q2156VX 45 LLMhZX --")?3$/'.'<(
 ,-!) . 
 G . !=N  66 5544.. !
 J3%P 03	#((+   "	)2)H)HaRS)T#%77>#:#A#A#CJ8*U % J4PQ7)T !"I"   #''$$*H(T,2 33I>sP    BC>>H'2H'F,FH'AG*)H"*+H	H"H	H""H')r  r  r  end_timerS  r  r  r  r  tagsr_  rW  reference_example_idrR  r"  rY  rZ  r[  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 R'                  U	5      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.                  (       aw  UR+                  S5      (       da  U R0                     U R2                  R5                  SUUUUUUUS.45        U R7                  5       (       a  U R9                  5          SSS5        gU R;                  UUUUUUUS9  g! , (       d  f       g= f)aG	  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.
    service_key (Optional[str]): The service JWT key for service-to-service auth.
    tenant_id (Optional[str]): The tenant ID for multi-tenant requests.
    authorization (Optional[str]): The Authorization header value.
    cookie (Optional[str]): The Cookie header value.
    **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_idrH  Nparent_run_idrm  
session_idr]  )
r   r  r  rH  r  rm  r	  r  r  r]  r  rK   r`  r_  Tr?  r  rS  r  r  r  r  r   r
  ra  r@  rc  rd  )r  r  	isoformatrc  r   r   r   r   r  r  rL  r(  rT   r)  r*  r$  ri   r#  r%  r&  r:  r  r'  r  r  r  rI  rf  rg  _update_run)r  r  r  r  r  r  rS  r  r  r  r  r	  r_  rW  r
  rR  r"  rY  rZ  r[  r\  r	  r  r   ri  use_multipartr   s                              rV   
update_runClient.update_run  s   n 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!::6BDN=$$dV,=,,Z88x8,0,C,CH,MWj)++?D'( ))&**=V2W2W**$$++'.'.+6)2-:&, 4466..0% +*( '#+  ) +*s   AK::
L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c  Uc  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*                  bK  U R-                  [/        US   U	UUUUUUU R1                  U R2                  R5                  5       5      S
9	5        g U R-                  [/        US   U	UUUUUUS95        g g U R7                  UUUUUUUS9  g ! , (       d  f       N= f)NrH  rm  r@  )r  payloadr  ro  rn  rK   rp  rq  rd  )r  r  r  r  r;   r=   rQ   rs  rt  ru  r  r   r9   r+   rv  r   rw  r   r   rH  r   r  rS  r%   r  r  rx  _update_run_non_batch)r  
run_updaterR  r"  rY  rZ  r[  r\  r  rz  r{  r|  r}  s                rV   r  Client._update_run  su    t+Qt/E/ET/Q 7:&d27 >*$6	 	 (((4.*UM&&2OO'%!)N
 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)$+$+(3&/*7#))-)B)B $ 0 0 A A C*  ++(&~6)$+$+(3&/*7#)	1 0J &&'#+ ' g 10s   A4I		
Ic                  [        X2XFU/5      nU(       a^  U=(       d    U R                  n	[        U R                  UUUUUU R                  S9n
U R                  SU	 SUS    3[        U5      U
S.S9  g U R                  R                  5        HC  u  p[        U R                  US S S S S S9n
U R                  SU SUS    3[        U5      U
S.S9  ME     g )Nr  PATCH/runs/r   r  r  )	r   r"  r  r  rR  r  r  rf  rc  )r  r  rR  r"  rY  rZ  r[  r\  r  r  r  r  r  s                rV   r  Client._update_run_non_batch  s    Gk&QR$4N+'#+!%G %%!"&D)9(:;'
3&  &  150D0D0J0J0L,/MM) $""&%) ))$oVJt,<+=> +J 7#*$ *  1MrZ   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                  (       aG  [        U R                  5      n[        R                  " XS9u  pU R                  R                  U	5        gg! [         a    U R                  XVUS9   Nuf = f)	an  Force flush the currently buffered compressed runs.

Args:
    attempts: Retry attempts for the send request.
    timeout: Maximum seconds to wait for in-flight sends to complete.
        None (default) waits indefinitely. Bounds only the wait on
        already-submitted sends; the synchronous drain and submit
        steps above are not bounded by this timeout.
Nz>Run compression is enabled but request pool futures is not setr   )r  '_tracing_thread_drain_compressed_bufferrK   )r  r  r  r  )r  r  r   r  r  r  r  r  rJ  r  r   cfwaitdifference_update)r  r  r  r  r  final_data_streamr  r  futuresdoner   s              rV   flush_compressed_tracesClient.flush_compressed_traces*  s    !!)== P 
	
 4Q
	
"
 (F5<<77%*%	 =  !!&) ==4==)Gggg7GDMM++D1	    33% 4 s    7C C-,C-c                &   Ub  [         R                  " 5       U-   OSnU R                  (       a6  U R                     U R                  (       a  U R                  5         SSS5        U R                  b  Uc  U R                  R                  5         OU R                  R                     U R                  R                  (       aa  U[         R                  " 5       -
  nUS::  a  OBU R                  R                  R                  U5        U R                  R                  (       a  Ma  SSS5        U R                  b7  Ub"  [        SU[         R                  " 5       -
  5      OSnU R                  US9  gg! , (       d  f       GN= f! , (       d  f       Ne= f)zFlush the tracing queue and compressed buffer.

Args:
    timeout: Maximum seconds to wait for pending traces to drain.
        None (default) waits indefinitely. A timeout of 0 returns
        immediately without waiting.
Nr   rE   r  )rN   	monotonicr  r  r  rg  r  rm   all_tasks_doneunfinished_tasksr!  r  r  r&  )r  r  deadlinewait_for	remainings        rV   flushClient.flushc  s7    291D4>>#g-$))**''..0 + )""'') ''66,,==#+dnn.>#>#q=!**99>>xH	 ,,=== 7 !!-9A9MCDNN$445SW  (((;	 .! +* 76s   "E0&A;F0
E?
F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  rH  c                    U R                   $ r   )rm  rs    rV   r  )Client._load_child_runs.<locals>.<lambda>  s    !..rZ   rD  z
Child run z has no parentr?  ZrK   )	list_runsr  rH  r  r  r   r  r   rn   r  ri   r   rm  r  rI  r  
child_runsrc  )r  r+  r:  treemapr  
run_id_str	child_runsegancestor_idsr  childrens              rV   _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  r  r  s3_urlsattachments_keyr"  r_  r]  rY   )	r  r  /_convert_stored_attachments_to_attachments_dictrO  r"  r  Runr]  rA  )r  r  load_child_runsr  r_  r+  s         rV   read_runClient.read_run  s    2 ,,VHVX678
 FMMOY
 nn 
#
'/}}
BF..
 '',C
rZ   asc
project_idrU  r2  r  selectfilterorderc                   U(       d  U(       d  [        S5      e[        R                  " [        U5      5      n
SU
 S3nU(       a	  SU SU S3OUnU R                  " SUUUUUUUS.U	D6$ )a  Read runs for a single thread.

Args:
    thread_id: Thread id (required).
    project_id: Project id(s) (required when not using project_name).
    project_name: Project name(s) (required when not using project_id).
    is_root: If True, return only root runs. Default True.
    limit: Maximum number of runs to return.
    select: Fields to select.
    filter: Additional filter expression.
    order: Sort order for runs (e.g. "asc" for chronological). Default "asc".
    **kwargs: Additional arguments passed to the runs query.

Yields:
    Runs in the thread.

Examples:
    ```python
    for run in client.read_thread(
        thread_id="thread_abc123",
        project_name="My Project",
        limit=50,
    ):
        print(run.id)
    ```
z-thread_id requires project_id or project_namezeq(thread_id, rg  zand(rf   rM  rY   )r   rO  rP  r  r9  )r  r  rN  rU  r2  r  rO  rP  rQ  r	  thread_id_escapedthread_filtercombined_filters                rV   read_threadClient.read_thread  s    N lLMM JJs9~6():(;1=?EDr&;=~~ 	
!%"	
 	
 		
rZ   )rN  rU  r  rH  r
  queryrP  trace_filtertree_filterr2  r  r  rS  run_idsrO  r  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)a  List runs from the LangSmith API.

Args:
    project_id: The ID(s) of the project to filter by.
    project_name: The name(s) of the project to filter by.
    run_type: The type of the runs to filter by.
    trace_id: The ID of the trace to filter by.
    reference_example_id: The ID of the reference example to filter by.
    query: The query string to filter by.
    filter: The filter string to filter by.
    trace_filter: 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: 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: Whether to filter by root runs.
    parent_run_id: The ID of the parent run to filter by.
    start_time: The start time to filter by.
    error: Whether to filter by error status.
    run_ids: The IDs of the runs to filter by.
    select: The fields to select.
    limit: The maximum number of runs to return.
    **kwargs: 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rU  )app_pathcompletion_costcompletion_tokensrm  r  rS  r  r  feedback_statsfirst_token_timer   r  r  r  r  parent_run_idsprompt_costprompt_tokensr
  r  r  r  statusr	  
total_costtotal_tokensrH  child_run_idszOThe child_run_ids field is deprecated and will be removed in following versions)rL  r  reference_examplerX  rP  rY  rZ  r2  
parent_runr  rS  r   r}   rO  r  /runs/queryr4  rD  rE  r_  r]  rK   rY   )r   r  r  r  rI  r   extendread_projectr   ro   rp   r  r  rc  	enumerater  rG  r"  r  rH  r]  )r  rN  rU  r  rH  r
  rX  rP  rY  rZ  r2  r  r  rS  r[  rO  r  r	  project_idsr  default_select
body_queryr8  r9  ir+  r_  s                              rV   r9  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   )rN  rU  r  r  rP  r  c          
     Z   Uc  Uc  [        S5      eUb  Ub  [        S5      eUb  U R                  US9R                  nUc   e[        [	        US5      5      nUcL  [
        R
                  R                  [
        R                  R                  5      [
        R                  " SS9-
  nUR                  c'  UR                  [
        R                  R                  S9n/ S	QnU/S
SSUUR                  5       S.n	Ub  XYS'   U	R                  5        V
Vs0 s H  u  pUc  M
  X_M     n	n
n[        R                  " [         5      nU R#                  SU	S9 H0  nUR%                  S5      nU(       d  M  X   R'                  U5        M2     / nUR                  5        H  u  nnUR)                  S S9  / nU HM  n[+        USU R,                  S9nUR'                  [.        R0                  " SSU0UDSU R2                  0D65        MO     U Vs/ s H%  nUR%                  S5      c  M  [        US   5      PM'     nnUR'                  UU[5        U5      U(       a  [7        U5      OSU(       a  [9        U5      OSS.5        M     UR)                  S S
S9  US:  a  XS nUb  USU nU$ s  snn
f s  snf )a  List threads and fetch the runs for each thread.

Args:
    project_id: The project (session) id.
    project_name: The project name (alternative to project_id).
    limit: Maximum number of threads to return. Default None (no limit).
    offset: Pagination offset for threads. Default 0.
    filter: Optional filter for threads and runs.
    start_time: Only include runs from this time. Default: 1 day ago.

Returns:
    List of thread items, each with "thread_id", "runs", "count",
    "min_start_time", and "max_start_time".
Nz2Either project_id or project_name must be providedz1Provide exactly one of project_id or project_namer]  rN  rK   )days)tzinfo)r   r  rf  r  r  r  rH  r  rS  r	  r  r  rh  rg  rm  r
  ra  r^  Tr  desc)rL  r2  r  rQ  rO  r  rP  rl  rm  r  c                j    U R                  S5      =(       d    SU R                  S5      =(       d    S4$ )Nr  r  rm  r  r4  s    rV   r  %Client.list_threads.<locals>.<lambda>!  s)    EE,'-2EE.)/RrZ   r7  rD  rE  r_  r]  r  )r  r  rU   r  r  c                6    U R                  S5      =(       d    S$ )Nr  r  r{  )ts    rV   r  r|  B  s    !%% 017R7rZ   )rD  reverser   rY   )r   ro  r   r  r  r(  rT   r)  r*  	timedeltarx  r  r  rc  r  r  r   r  r  rI  sortrG  r"  r  rH  r]  r  minr  )r  rN  rU  r  r  rP  r  r  
run_selectrs  r8  r9  threads_maprun_dicttidr  r  	run_dictsr  r_  r5  start_timess                         rV   list_threadsClient.list_threads  s   0 ,"6QRR!l&>PQQ#***EHHJ%%%*l;<
!**..!!%%""*+J $#++83D3D3H3H+IJ

* #| $..0&

 #)x '1'7'7'9K'9tqQdad'9
K-8-D-DT-J77J7WH,,{+Cs ''1 X
 )+$/$5$5$7 IyNN   D%Mi NN $/" #'..	 & #&"A55& %AlO$"  &
 MM!*  Y:Ec+&64:Ec+&641 %8D 	7 	 	
 A:G_FFU^Fg L8&s   	J"J"J(!J()r   r}   rk  r  project_namesrq  reference_example_idsr  r  rS  rX  rP  rY  rZ  r2  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_completedr]  N)r   r}   rk  r  rL  rj  r  r  rS  rX  rP  rY  rZ  r2  r  r  z/runs/statsr  r  )concurrent.futuresr  r  r  ro  rI  r  r   rc  r  r  ri   r  rO  )r  r   r}   rk  r  r  rq  r  r  r  rS  rX  rP  rY  rZ  r2  r  r  r  executorr  r$  r  r  r8  r9  r  s                              rV   get_run_statsClient.get_run_statsK  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)rU  rN  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]  r]  z/o/z/projects/p/z/r/z
?poll=true)r"  ro  r   ri   re  r  r]  _get_tenant_id)r  r+  rU  rN  r  r]  session_id_s          rV   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
$	
rZ   )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PUTr  /sharer  rO  r  /public//r)
r  r  r  rF  r  r  ri   r  rO  r]  )r  r  r  run_id_r  r  r  s          rV   	share_runClient.share_run  s     68,'l#8s4::<'8
 ,,WIV$MM	 - 
 	++H5mmom4..!+b99rZ   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
DELETEr  r  r  r  Nr  r  r  ri   r  )r  r  r  s      rV   unshare_runClient.unshare_run  sG     ,,Xfh/07MM - 

 	++H5rZ   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  r  r  r  r  Nr  r  r  )r  r  r  ri   r  rO  r]  )r  r  r  r  s       rV   read_run_shared_linkClient.read_run_shared_link  s     ,,Xfh/07MM - 

 	++H5>]&8..!&*?)@CCrZ   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      rV   run_is_sharedClient.run_is_shared  s&     ((&()CD4rZ   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  /runr  r  r  r  r]  rY   )
r(  r  r  r  ri   r  r  rH  rO  r]  )r  r  r  r   r'  r  r  s          rV   read_shared_runClient.read_shared_run  s     ,K%H*T*a2344D,,MM - 

 	++H5~~JJ4>>JJrZ   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  rl  rm  r]  NrY   )r(  r  r  rH  r]  )r  r  r[  r4  r   r'  r+  s          rV   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)r   read_datasetr   r  r  r  ri   r  rO  r   r  DatasetShareSchemar]  )r  r  r  r  ds        rV   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
 	
rZ   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  )r   r  r   r  r  r  r  ri   r  rO  r   r  r  r]  )r  r  r  r  r  r  s         rV   share_datasetClient.share_dataseth  s    ( ,"6NOO***EHHJ#j/
 ,,*l;<FCMM	 - 
 	++H5--/))IqI%DNN+8Am4D3ERHI
 	
rZ   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      rV   unshare_datasetClient.unshare_dataset  sG     ,,*l;<FCMM - 

 	++H5rZ   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_pathrY   )
r(  r"  r  r  ri   r  r  r  rO  r]  )r  r  r   r'  r  s        rV   read_shared_datasetClient.read_shared_dataset  s     ,KF,,zl),MM - 

 	++H5!! 
mmo
nn#K=3
 	
rZ   )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]  rK   rY   )r  rp  r  r  r  Exampler]  )r  r  r  r  r  r   rt  examples           rV   list_shared_examplesClient.list_shared_examples  s     " ".9:kCGk:F4L#$$8K?@	J % 
JA $$IwI$..II QUe^
 ;s   
BBAB>B	
B)rq  r  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   r  r  dataset_share_tokenr  z/datasets/sessionsr  r]  NrK   rY   )r  rp  r  r  TracerSessionResultr]  )
r  r  rq  r  r  r  r  r  rt  projects
             rV   list_shared_projectsClient.list_shared_projects  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      U
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   )r  r  r  r   Tr  r  r  r  rs  )r  r  r  r]  rY   )r"  r  r  rF  r  r  r  ri   r  r  TracerSessionrO  r]  )r  rU  r  r   r  r  r  r/  r  r4  r  r  s               rV   create_projectClient.create_project  s    . ll^9-;;j(;E &djjl#	 
 #F8++?'(,,It}}In6HIT" - 
 	++H5''T(--/TT^^TTrZ   )r  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/rN  r   N)r  r  r  r  r  r  rs  r  r  r]  rY   )r"  r  r  r  r  r  ri   r  r  r  rO  r]  )r  rN  r  r  r   r  r  r/  r  r4  r  s              rV   update_projectClient.update_project(  s    < ll^:hz<.P-QR;;j(;E&08**,d	 
 ,,It}}In6HIT"	 - 
 	++H5''T(--/TT^^TTrZ   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  rK   r  r   r]  z*Failed to get tenant ID from LangSmith: %sTrb  rY   )r  r  rO  r   r   r  r  r  r]  rZ  r   rQ   r   r  )r  r  r  tracer_sessionr  s        rV   r  Client._get_optional_tenant_idY  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)r  ri   r   )r  rZ  s     rV   r  Client._get_tenant_idm  s.    002	))*>??rZ   )rN  rU  )rN  rU  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  rK   r  rN  r  'Must provide project_name or project_idr  r  r  r   zProject 
 not foundr]  rY   )r  r   r  rO  r   r   r  ri   r  r  r  r]  )r  rN  rU  r  r  r  r  r  s           rV   ro  Client.read_projects  s    * ")1!a\:;<<D%)6NFGG"/,,UD,Hfd##6{a55|nJ7  11XF1IXXX-- 
mmo
)-
 	
rZ   rN  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.
r]  FT)ro  ri   r  )r  rU  rN  s      rV   has_projectClient.has_project  s7    	<8  .. 		    ))c                 ^  [         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:                  " [=        [>        [@        [B        [D        4      URG                  SS95      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   rg   r   r  NT)r   r
  r  r  rS  ra  r  r  )rN  rU  r2  rO  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   r  rc  )batchexamplesr  r8  r9  r  s        rV   fetch_examples/Client.get_test_results.<locals>.fetch_examples  s    ))e)<H  (
  (G !'**8?8M27T7T7VW7VtqA3'*7VW  (  Xs   9A6A0"	A60A6r   r  zinput.zoutputs.)execution_timerS  r   notecommentsz	feedback.avgnoteszRun z has no reference example ID.)
left_indexright_indexrecords)orient)$ro   rp   UserWarningr  r  r  pandasr9  r
  r  rc  r  r  r  total_secondsrS  r   ra  r  r  rI  rQ   rR   r  r  	DataFrame	set_indexr  mergejson_normalizer   r   r   r  r   to_dict)r  rN  rU  r  r  pdr  resultsr  r  r(  r  r  r$  r5  r8  r9  rowr  r  	result_dfr  outputexample_outputs
example_dfs   `                        rV   get_test_resultsClient.get_test_results  sn   . 	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   d38n%y'8'8	'8'JK
 	
[ EO# "!T
sD   3N3N!*N3N'BN3$#N-N-$D(N3 $O!N33
O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  Nr  r   r  r  zGOnly one of reference_dataset_id or reference_dataset_name may be givenreference_datasetr  reference_freer  dataset_versionr   r  r  r]  rK   rY   )r  r   r  r   rO  rP  rp  r  r  r  r]  )r  rq  r  r  r  reference_dataset_namer  r  r   r  r   r  rt  r  s                 rV   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.
Nr]  r  r  r  rN  r  )	r  ro  r   r   r  r  r  ri   r  )r  rU  rN  r  s       rV   delete_projectClient.delete_projectn  s{    $ #T..L.ILLMJFGG,,*l;<=MM - 

 	++H5rZ   )r  r  inputs_schemaoutputs_schematransformationsr   c               0   S[         R                  " 5       0U=(       d    0 EnUUR                  US[         R                  " 5       0U=(       d    0 ESS.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.
r0  sdk)r   source)r  r  r)  r  r  inputs_schema_definitionoutputs_schema_definitionr  r  r  rs  r  r   r  rY   )r1  r2  rl  r  r  r$   rP  ri   r  rO  r  r  r  r]  r  )r  r  r  r  r'  r(  r)  r   datasetr  json_responses              rV   create_datasetClient.create_dataset  s2   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
 	
rZ   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.
r3  TF)r  ri   r  )r  r  r  s      rV   has_datasetClient.has_dataset  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  rK   r  r  r  'Must provide dataset_name or dataset_idr  r  r   r  r  r  rY   )r  r   r  rO  r   r   r  ri   r  r  r  r]  r  )r  r  r  r  r  r  r  s          rV   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
 	
rZ   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r  r  rY   )r   r  r   r  r  r  r   r(  r  ri   r  r  DatasetDiffInforO  )r  r  r  r<  r=  dsidr  s          rV   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<<rZ   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  r8  r  r  r  z
/openai_ftr  )
r  r   r   r  r  textrd  r  rO  r  )r  r  r  r  r  liner/  s          rV   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  Nr  r   r  r  r  r   r  r  r  rK   rY   )	r  rO  rP  rp  r  r  r  r]  r  )
r  rH  r  r  rI  r   r  r  rt  r/  s
             rV   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  r;  r  r  r  r  )r  r   r   r  r  r  ri   r  )r  r  r  r  s       rV   delete_datasetClient.delete_dataset  sv    $ #***EHHJEFF,,*l;<=MM - 

 	++H5rZ   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  r;  r  r  r  /tagsas_oftagr  )	r  r   r   r  r  r  r  ri   r  r  r  r  rS  rT  r  s         rV   update_dataset_tagClient.update_dataset_tag  s    Z #***EHHJEFF,,*l;<EBMM*	 - 
 	++H5rZ   )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  r  )rX  r  r  r  z	/versionsr  rK   rY   )r  r   r  rp  r  r  r  DatasetVersion)r  r  r  rX  r  r  rt  r   s           rV   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  rS  rT  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.

Use this to retrieve the dataset version to a 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/versionrR  r  rY   )r  r   r   r  r  r  rZ  rO  rU  s         rV   read_dataset_versionClient.read_dataset_version3  s    L ***EHHJcu}NOO,,*l;<HE"/ - 

 ((;8==?;;rZ   )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.
placeholder)r"  rR  r  r  z) already exists in your tenant. Skipping.)r  r  r  r'  r(  r)  )r  r  r  z)An error occurred while creating dataset z . You should delete it manually.N)r"  r(  r  r  r  r  rQ   r  ri   r  r   r  r1  r  r  r  DataTypekvr'  r(  r)  create_examplesr  r  r   r  rS  )
r  token_or_urlr`  r  r'  source_clientdsr   r/  r  s
             rV   clone_public_datasetClient.clone_public_datasetd  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      rV   r  Client._get_data_type  s!    ##z#:   rZ   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  r  r  r  r  
created_at)create_example)r  r  
generationr  r  rp  s         rV   create_llm_exampleClient.create_llm_example  s5    4 ""V$z*!%! # 
 	
rZ   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
Nrn  r  ro  )	ri   is_base_message_likerI  convert_langchain_messager   r  BaseMessageLiker   rq  )	r  messagesgenerationsr  r  rp  final_inputmessagefinal_generationss	            rV   create_chat_exampleClient.create_chat_example  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!%! # 
 	
rZ   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  r1  z	Run type z+ is not supported for dataset of type 'LLM'z2Error converting LLM run inputs to prompt for run z with inputs rn  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.ro  )r  r   r  r  rc  r1  r  r   ri   get_prompt_from_inputsr  r  get_llm_generation_from_outputschatget_messages_from_inputs#get_message_generation_from_outputsrd  rq  )
r  r+  r  r  rp  dataset_typer  r  r  rr  s
             rV   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  rp  use_source_run_iouse_source_run_attachmentssource_run_idr   r  rs  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  )&r   r  ExampleUpsertWithAttachmentsr   r  ExampleCreateExampleUpdater   r  r  rF  rp  r  r  r  r   r  r  rI  r  r  r_  rc  r   r   r  r  getsizer  FileNotFoundErrorrQ   rR   r  attachments_operationsr  r  r+   r  )r  r   include_dataset_idrW  r  r  r  r  r  rp  r  r  r  example_bodyvalbinputsboutputsbr  ri  r  attachment_data	file_sizer	  attachments_operationsbr  r  s                             rV   _prepare_multipart_dataClient._prepare_multipart_datae  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)updatesrW  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  rW  )_update_examples_multipart)r  r  r  rW  s       rV   update_examples_multipart Client.update_examples_multipart"  %     ..!)E / 
 	
rZ   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  rW  r  r  r  r  r  instance_flagsr  r   r  r  _dataset_examples_pathr"  r  r  ri   r  rw  r   r   rO  )r  r  r  rW  r  r  r  r  s           rV   r  !Client._update_examples_multipart5  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)uploadsrW  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  rW  )_upload_examples_multipart)r  r  r  rW  s       rV   upload_examples_multipart Client.upload_examples_multipartg  r  rZ   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.r  r  r     )r  r  r  r  r   r_  rc  r   r   r   r  r  r  r  OSError)r  r  sizer   ri  r  s         rV   _estimate_example_sizeClient._estimate_example_sizez  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  rI  )	r  r   r  batchescurrent_batchcurrent_sizer  example_sizesize_exceededs	            rV   _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=)rZ   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  rW  r  r  r  r  s           rV   r  !Client._upload_examples_multipart  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  )upsertsrW  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  r   r  r  r"  r  r  ri   r  rw  r   r   rO  )r  r  rW  r  r  r  r  s          rV   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   rW  max_concurrencyc               R   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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": [...
    ```
rK   r\   z'max_concurrency must be between 1 and 3rf   rb  zCannot specify z when 'examples' is specified.>   idsr  splitsr  r   source_run_idsz(Received unsupported keyword arguments: r?  z3Either dataset_id or dataset_name must be provided.r  r  z+Must specify either 'examples' or 'inputs.'N
Length of  (z#) does not match length of inputs (rg  r  c              3  &   #    U  H  nS v   M	     g 7fr   rY   r   r   s     rV   r   )Client.create_examples.<locals>.<genexpr>  s     -M<Lqd<L   r   c              3  &   #    U  H  nS v   M	     g 7fr   rY   r  s     rV   r   r    s     .N=Mt=Mr  r  c              3  &   #    U  H  nS v   M	     g 7fr   rY   r  s     rV   r   r    s     ,L;KaT;Kr  r  c              3  &   #    U  H  nS v   M	     g 7fr   rY   r  s     rV   r   r    s     )I8H1$8Hr  r  c              3  &   #    U  H  nS v   M	     g 7fr   rY   r  s     rV   r   r    s     4TCSaTCSr  )r  r  r   r  r   r  r   r  rU   rS  rY   )r   rm   r   
differencer   r  r   r   r   r  r  r  r  rc  zipr  r  r  rF  UpsertExamplesResponser  !_upload_examples_batches_parallel)r  r  r  r   rW  r  r	  r8  
kwarg_keyssupported_kwargsunsupportedr   r  r  	input_lenarg_name	arg_valuein_out_	metadata_split_id_source_run_id_r  s                           rV   re  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  ..w755Z
 	
S $>0$s   L&7L:ALc           
        / nS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       Hn  nUR                  5       nUR                  UR                  S/ 5      5        XmR                  SS5      -  nUR                  S5      nU(       d  Mb  Ub  X:  d  Ml  UnMp     S S S 5        [        R                  " XVUS9$ s  sn
f ! , (       d  f       N(= f)Nr   )ContextThreadPoolExecutormax_workersr  rU   rS  r  )langsmith.utilsr  r  _upload_single_batchr   r  r  rn  r  r  r  )r  r  r  rW  r  all_examples_idstotal_countlatest_as_ofr  r  r  r$  r  r  rS  s                  rV   r  (Client._upload_examples_batches_parallel  s    =&?Cx % %E --0	 %   //'2!==? '']B(GH||GQ77 !W-5l2e6J#(L 3 D, 00(<
 	
) DCs)   C,(C' A6C,:C,C,'C,,
C:c                t   U R                   R                  =(       d    0 R                  SS5      (       a+  U R                  [	        [
        R                  U5      UUS9nU$ 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  snf s  snf )zIUpload a single batch of examples (used by both sequential and parallel).r  Fr  r_  Nz7Must upgrade your LangSmith version to use attachments.r  /examples/bulkr  rs  Texclude_noner  r  r   r  )r  r  r  r  r   r  r  r"  r_  ro   rp   r  r  r  
dump_modelr  ri   r  rO  r  )r  r  r  rW  r  uploadresponse_datar  s           rV   r  Client._upload_single_batch  sQ   II$$*//0%
 
 66		:6-I 7 H
 O  6=1=)-F&MMQ   00 M4==M.:LM  ',
 ',F	(dC(#j/ ',	 1 H //9$MMOM7DE}tT
}E]+   Fs   <#D0D5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  )r  r  r   r  r  r  r  r_  r  F)r  r  )r  r_  z6Must upgrade your LangSmith version to use attachmentsr  r  r  rs  r  r  r  rY   )r   r  r   r  r  rp  r   r  r  r  rF  r  r  r  r  read_exampler"  r_  ro   rp   r  r  r  r  rc  ri   r  rO  r  r]  r  )r  r  r  r  rp  r  r   r  r  r  r  r  r_  r  r8  r9  r  r  s                     rV   rq  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)rS  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  rS  Nr  attachment_urlsrE  r_  r]  r  rY   )r  r  r  rO  rG  r"  r  r  rc  r]  r  )r  r  rS  r  r  r_  r8  r9  s           rV   r  Client.read_example|  s     ,,*l;<=e* - 
 --/E%6
 !! 
 'J18I3ItqtJ
#nn335	
 	
Js   B<B<)r  r  r   rP  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"))',
    )
    ```
Nr  )r  r   rS  r  inline_s3_urlsr  rP  r   r/  r  )r  r  r   rO  r  r  r  rE  r  rK   rY   )r   r(  r  r  r  r  r   rp  r  rG  r"  r  r  rc  r]  r  )r  r  r  r  rS  r  r
  r  r  r   rP  r  r	  r  rt  r  r_  r8  r9  s                      rV   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	)r  r  r   r  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.)r  r  r   r   r  r  r_  )r  r  r  r  r  r  rs  r  r  rY   )r  r  r  r   r   r  r  rc  r  r  r  r  r  r  r  r  r  ri   r  rO  )r  r  r  r  r   r  r  r  r_  example_dictr8  r9  r  r  s                 rV   update_exampleClient.update_example  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  rW  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'.rH  rK   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 (rg  r  c              3  &   #    U  H  nS v   M	     g 7fr   rY   r  s     rV   r   )Client.update_examples.<locals>.<genexpr>       )L8K1$8Kr  r  c              3  &   #    U  H  nS v   M	     g 7fr   rY   r  s     rV   r   r    s     *M9LA49Lr  r   c              3  &   #    U  H  nS v   M	     g 7fr   rY   r  s     rV   r   r    s     +N:MQD:Mr  r  c              3  &   #    U  H  nS v   M	     g 7fr   rY   r  s     rV   r   r    r  r  c              3  &   #    U  H  nS v   M	     g 7fr   rY   r  s     rV   r   r          .Q=Pt=Pr  c              3  &   #    U  H  nS v   M	     g 7fr   rY   r  s     rV   r   r  !  r  r  c              3  &   #    U  H  nS v   M	     g 7fr   rY   r  s     rV   r   r  #  s     2UATA4ATr  )r   r  r  r  r   r  r_  r  Fr  r|  rU   z examples updatedr  r  r  rs  r  rY   )r   r   r  r   r   r   r  r  r  r  r  r  r   r  r  rc  r  r  r  r   r  r  r  r  r  r  ri   r  rO  )r  r  r  r  rW  r	  r   updates_objr  multipart_enabledexamples_lenr  r  r  r  r  r  r  dataset_id_attachments_attachments_operations_r  r  r8  r9  s                            rV   update_examplesClient.update_exampless  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      rV   delete_exampleClient.delete_exampleL  sE     ,,*l;<=MM - 

 	++H5rZ   )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  r'  zdatasets/examples/deleter  r  rs  )r  r  r  r  r  r  r>  N)rp  r  r  _platform_pathr"  r  rL  r  r  r  r  r  ri   r  )
r  r  r'  rt  r  r4  r  full_urlr  r  s
             rV   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  rS  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  rS  r  r  r  /splitsr  )r   r  r   r   r(  r  r  r  ri   r  rO  )r  r  r  rS  r  r  s         rV   list_dataset_splitsClient.list_dataset_splits  s    & # !BCC***EHHJ%/x7H7H%I%I!u 7O ,,*l;<GD - 

 	++H5}}rZ   )r  r  rJ  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
Nr0  r  r)  r*  )
split_namer   rJ  r  r  r  r1  rO  )	r   r  r   rp  r  r  r  ri   r  )
r  r  r  r5  r  rJ  rt  r  r  r  s
             rV   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.
rI  )r   r  r  r  rJ  r   r  rH  )r  r+  rI  run_s       rV   _resolve_run_idClient._resolve_run_id  sH    & cC+,,===FD  
,DrZ   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.
r  NrY   )r   r  r  r  r  r  r  r   r]  r  r
  )r  r  r+  reference_example_s       rV   _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 "! "&!!rZ   )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      (       aV  0 U EnSU;   a  SU;  a  US   US'   UR                  SS 5        Tb  UR                  S5      c  TUS'   TR                  " S0 UD6$ U $ )N	reasoningcommentrD  rY   )r   r   r  r  EvaluationResult)single_resultmerged_resultrB  ls_evaluators     rV   _cast_result1Client._select_eval_results.<locals>._cast_result  s     -..0A=0A-/I]4R/<[/IM),!!+t4&=+<+<U+C+K+2M%(#44E}EE  rZ   r  c                :    [        U [        5      =(       a    SU ;   $ )Nr  )r   r   )r  s    rV   _is_eval_results5Client._select_eval_results.<locals>._is_eval_results,  s    gt,Eg1EErZ   z!Invalid evaluation results type: z.. Must be EvaluationResult, EvaluationResults.)rH  z*Union[ls_evaluator.EvaluationResult, dict]r  ls_evaluator.EvaluationResult)r  r   r  z)TypeGuard[ls_evaluator.EvaluationResults])langsmith.evaluationr   r   rG  r   r   r   r   )r  r  rB  rK  rN  results_r5  rJ  s     `    @rV   _select_eval_resultsClient._select_eval_results  s     	C	!E	!*	! 	!	F g|<<==yH  g&&181CD1CAQ1CHD  &&$T$%89:H 	 3DM? C@ @ 	 Es   B*)source_inforj  rI  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.
r:  r  rU  r   )r<  r@  evaluate_run_log_evaluation_feedback
r  r+  r   rU  rj  rI  r;  r?  evaluator_responser  s
             rV   rY  Client.evaluate_run<  sq    < ##C#I!556GN&33& 4 
 //# 0 
 qzrZ   )	_executorc          
     H  ^ ^ T R                  U5      nUU 4S jnU GH  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" S0 SU
_SUR                  _SUR                  _SUR                  _SUR                  _SUR                  _S	U	_S
UR                  _S[        [        [        R                     UR                   5      _S[        R"                  R$                  _SU_SUR                  _SU(       a  UR&                  OS _SU(       a  UR(                  OS _SU(       a  UR*                  OS _SU_6  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 )NrY   )r  create_feedback)r	  r^  r  s    rV   _submit_feedback9Client._log_evaluation_feedback.<locals>._submit_feedbacku  s0      !5!5@@$$.v.rZ   rS  r  rD  rX  rl  rF  
correctionrU  r  feedback_configfeedback_source_typerN  r  rH  r  r  rY   )rS  evaluator_infotarget_run_idr   r  r  rD  rX  rl  rF  rd  r  r   r   r  FeedbackConfigre  FeedbackSourceTypeMODELrH  r  r  )r  r\  r+  rU  rN  r^  r  rb  ressource_info_r  rS  s   `    `      rV   rZ  Client._log_evaluation_feedbackh  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 *-$  .13>>d!" .13>>d#$ % > rZ   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.
r:  rW  NrX  r   )r<  r@  aevaluate_runrZ  r[  s
             rV   rp  Client.aevaluate_run  s~     < ##C#I!556GN#,#:#:& $; $
 

 //# 0 

 qz
s   4AAAr]   )rX  rl  rH  rd  rF  rU  rf  r  feedback_idre  r  rN  comparative_experiment_idfeedback_group_idr  rS  r  r  c          
     
   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S	5      5      (       a  UR#                  5       nSU;   a(  [        [%        UR                  S   S   S
5      5      US'   UUR                  S'   ['        Ub  UOUSS9n[        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/                  [,        R0                  R2                  5      _S[,        R,                  R/                  [,        R0                  R2                  5      _SU_SU_SU_S['        USS9_S['        USS9_SU_SU_6nU R4                  (       + =(       a/    U R6                  R8                  =(       d    0 R;                  SS5      nU(       Gam  U R6                  R<                  (       GaQ  [>        R@                  " U R6                  R<                  S5      (       Ga   U RB                  c  U RD                  Gb  URF                  b  U RH                  c  [K        U5      nU RD                  b  [M        U5      nU RD                  RN                     [Q        UU RD                  [R        5      nU(       aJ  U RD                  =RT                  S -  sl*        U RV                  (       a  U RV                  RY                  5         SSS5        OxU RB                  b.  U R[                  []        [        UR^                  5      U5      5        O<[a        UR#                  SS!95      nU Rc                  S"S#S$U0U[>        Rd                  4S%9  [        Rf                  " S(0 UR#                  5       D6$ ! , (       d  f       N2= f! [h         a  n[j        Rm                  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.
    session_id (Optional[Union[UUID, str]]):
        The session (project) ID of the run this feedback is for. Used to
        optimize feedback ingestion by avoiding server-side lookups.
    start_time (Optional[datetime]):
        The start time of the run this feedback is for. Used to optimize
        feedback ingestion by avoiding server-side lookups.
    **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']Tro  r   rH  rD  rX  rl  rd  rF  feedback_sourcerp  modified_atre  r  r  rs  rt  r  rS  use_multipart_endpointz0.8.10rK   r  r  	/feedbackr  )r  r  r  zError creating feedbackrb  rY   )7r   ro   rp   rn   r  r   r  rj  APIAPIFeedbackSourcerk  ModelFeedbackSourcer   r  r  r!  r"  r  r  rn  FeedbackCreaterY  r(  rT   r)  r*  r  r  r  r  r   ri   is_version_greater_or_equalr  r  rH  r  r:   r<   ru  r9   r+   rv  r  r   rS  r%   r   r  r  r  Feedbackr   rQ   rS  ) r  r  rD  rX  rl  rH  rd  rF  rU  rf  r  rr  re  r  rN  rs  rt  r  rS  r  r  r	  rw  	_run_meta_session_idfeedbackr  rz  r{  r}  feedback_blockr  s                                    rV   ra  Client.create_feedback  s   V #8>j0WXX*"8Q  MM$Vn-/"
p	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	9l33I|49 9 !* 4 4 6Iy(*- +44W=hGI+Ih' 5>((1&(4
*RVK "00 , $F=	
 &hDA  -U3  &   !0 $,,001B1B1F1FG %--11(2C2C2G2GH !0 '  &!" +7-4+#( #//@d"S)* +, -H2 !% 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-@-@d-@-S!T))$ (:&==? *  &&?)<)<)>??3 544  	LL2TLBG	s3   NT :A-T'B$T 
TT 
U'T==U)rX  rl  rd  rF  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
NrX  rl  rd  rF  r  
/feedback/rr  r  rs  r  )rY  r  r  r  r  ri   r  )r  rr  rX  rl  rd  rF  feedback_updater  s           rV   update_feedbackClient.update_feedback  s    4 +-'=e'DOG$',G$!,6L))0I&,,+}=>?It}}In6HI_-	 - 
 	++H5rZ   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  rr  rY   )r  r  r  r  rO  r  rr  r  s      rV   read_feedbackClient.read_feedback  sE     ,,+}=>?
 ""5X]]_55rZ   )r[  feedback_keyrf  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.
Nr  )r+  r  rD  r,  rz  r  rK   rY   )r  rp  r  r  r  )	r  r[  r  rf  r  r	  r  rt  r  s	            rV   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  rr  r  Nr  r  s      rV   delete_feedbackClient.delete_feedback8  sE     ,,+}=>?MM - 

 	++H5rZ   )rl  rd  rF  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
rK   )r#  zInvalid source API URL. r  z/feedback/tokens/)rX  rl  rd  rF  r   r  N)	r(  r"  r   r  r  r  r  ri   r  )
r  rf  rX  rl  rd  rF  r   r`  r'  r  s
             rV   create_feedback_from_token!Client.create_feedback_from_tokenI  s    8 &9,,!&
" \\)77GHII,, 456""",& (	 MM - 
 	++H5rZ   )
expirationre  rr  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  re  r   r   r\   rw  hoursminutes
expires_in
expires_at  rD   Unknown expiration type: r  /feedback/tokens)r  rY   )r  r  rF  r  TimeDeltaInputr   r(  r  r  rw  secondsr   r   r  r  ri   r  FeedbackIngestTokenrO  )r  r  r  r  re  rr  r4  r  s           rV   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--@@@rZ   )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  rD   r  )r  r  re  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  rv  rR  ri   r  rO  )r"  rR  r  r4  r  s      rV   req4Client.create_presigned_feedback_tokens.<locals>.req  sn    00)+,  -- !7#:dll   1 
H //9==?"rZ   r  )r"  r  rR  r  r  r   rY   )r  r   r  r  r   r(  r  r  rw  r  r   r  r  r   r  rf  rc  r  r  r  rn  r  )r  r  feedback_keysr  r  r  r  r  re  r  tokensr  r"  rR  futsfutr  r  r4  s   `                 @rV    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  Nr  )r  r  r  r  rK   rY   )r  r  rp  r  r  r  )r  r  r  r  rt  tokens         rV   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  r  r  /feedback/formulasr  rK   rY   )r  r  rp  r  r  FeedbackFormula)r  r  r  r  r  r  rt  feedback_formulas           rV   list_feedback_formulasClient.list_feedback_formulas<  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_idrY   )r  r  ri   r  r  r  rO  r  r  r  s      rV   get_feedback_formula_by_id!Client.get_feedback_formula_by_idd  sU     ,,!(+>@U"V!WX
 	++H5))<HMMO<<rZ   )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  rY   )r   r  FeedbackFormulaWeightedVariableFeedbackFormulaCreater  r  r  r  ri   r  r  rO  )
r  r  r  r  r  r  r  typed_partsr  r  s
             rV   create_feedback_formulaClient.create_feedback_formulaw  s   @ &	I
 & $
 J JKK ;;CdCD &	 	 I
 22%-%6@6L\2RV 7A6L\2RV

 ,, G$6$6D$6$IJ - 
 	++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  rY   )r   r  r  FeedbackFormulaUpdater  r  r  r  ri   r  r  rO  )	r  r  r  r  r  r  r  r  r  s	            rV   update_feedback_formulaClient.update_feedback_formula  s    : &	I
 & $
 J JKK ;;CdCD &	 	 I
 22%-%

 ,,!(+>@U"V!WXG$6$6D$6$IJ - 
 	++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  ri   r  r  s      rV   delete_feedback_formulaClient.delete_feedback_formula  s;     ,,!(+>@U"V!WX
 	++H5rZ   )is_lower_score_betterc                   UUUS.nU R                  SSUS9n[        R                  " U5        [        R                  " S0 UR                  5       D6$ )aL  Create a feedback configuration.

Defines how feedback with a given key should be interpreted.
If an identical configuration already exists for the key, it is
returned unchanged. If a different configuration already exists
for the key, an error is raised.

Args:
    feedback_key (str):
        The feedback key to configure.
    feedback_config (FeedbackConfig):
        The configuration defining type, bounds, and categories.
    is_lower_score_better (Optional[bool]):
        Whether a lower score is considered better.
        Defaults to False.

Returns:
    FeedbackConfigSchema: The created or existing feedback
        configuration.

Raises:
    requests.HTTPError: If a conflicting configuration already
        exists for the given key (HTTP 400).

Example:
    .. code-block:: python

        from langsmith import Client

        client = Client()
        config = client.create_feedback_config(
            feedback_key="user-rating",
            feedback_config={
                "type": "continuous",
                "min": 0.0,
                "max": 5.0,
            },
        )
)r  re  r  r  /feedback-configsr6  rY   r  ri   r  r  FeedbackConfigSchemarO  r  r  re  r  r4  r  s         rV   create_feedback_configClient.create_feedback_config  s_    ^ ).%: 

 ,, - 

 	++H5..AAArZ   )r  r  r  r  c             #     #    Ub  [        US5      OSUS.nUb  XS'   Ub  X%S'   [        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 configurations.

Args:
    feedback_key (Optional[Sequence[str]]):
        Filter by specific feedback keys.
    name_contains (Optional[str]):
        Filter by substring match on the feedback key.
    limit (Optional[int]):
        The maximum number of configurations to return.
    offset (int):
        The number of configurations to skip. Defaults to 0.

Yields:
    FeedbackConfigSchema: The feedback configurations.

Example:
    .. code-block:: python

        from langsmith import Client

        client = Client()
        for config in client.list_feedback_configs():
            print(f"{config.feedback_key}: {config.feedback_config}")
Nr  r  r  rD  r  r  r  rK   rY   )r  rp  r  r  r  )r  r  r  r  r  r  rt  rz  s           rV   list_feedback_configsClient.list_feedback_configs&   s     B ).(9S_s"
 #(5M$&3?#"$$%8$H
IA 11;F;; QUe^
s   AA0 A0+A0)re  r  c                   SU0nUb  X$S'   Ub  X4S'   U R                  SSUS9n[        R                  " U5        [        R                  " S0 UR                  5       D6$ )a  Update a feedback configuration.

Only the provided fields will be updated; others remain unchanged.

Args:
    feedback_key (str):
        The feedback key of the configuration to update.
    feedback_config (Optional[FeedbackConfig]):
        The new configuration values.
    is_lower_score_better (Optional[bool]):
        Whether a lower score is considered better.

Returns:
    FeedbackConfigSchema: The updated feedback configuration.

Raises:
    LangSmithNotFoundError: If no configuration exists for the
        given feedback key (HTTP 404).

Example:
    .. code-block:: python

        from langsmith import Client

        client = Client()
        config = client.update_feedback_config(
            "user-rating",
            is_lower_score_better=True,
        )
r  re  r  r  r  r6  rY   r  r  s         rV   update_feedback_configClient.update_feedback_configU   sy    L L 
 &&5"# ,,A(),, - 

 	++H5..AAArZ   c                V    U R                  SSSU0S9n[        R                  " U5        g)an  Delete a feedback configuration.

This performs a soft delete. The configuration can be recreated
later with the same key.

Args:
    feedback_key (str):
        The feedback key of the configuration to delete.

Example:
    .. code-block:: python

        from langsmith import Client

        client = Client()
        client.delete_feedback_config("user-rating")
r  r  r  r  Nr  ri   r  )r  r  r  s      rV   delete_feedback_configClient.delete_feedback_config   s7    $ ,,"L1 - 

 	++H5rZ   )	queue_idsr  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[r*  r  )r  r  r  r  /annotation-queuesr  rK   rY   )rp  r  r  r  r  AnnotationQueue)	r  r  r  r  r  rt  r  r  queues	            rV   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_instructionsrubric_itemsc          
     d   UUUb  [        U5      O[        [        R                  " 5       5      US.nUb  XVS'   U R                  SSUR	                  5        VVs0 s H  u  pxUc  M
  Xx_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.
    rubric_items (Optional[list[AnnotationQueueRubricItem]]):
        The feedback configs to assign to this queue's rubric.
        Each item specifies a feedback_key and optional per-queue
        customization like description and value_descriptions.

Returns:
    AnnotationQueue: The created annotation queue object.
)r  r  r   r  r  r  r  r6  rY   )
r  r  rF  r  rc  ri   r  r  AnnotationQueueWithDetailsrO  )
r  r  r  r  r  r  r4  r8  r9  r  s
             rV   create_annotation_queueClient.create_annotation_queue   s    : &#+#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  rY   )r  r  r  ri   r  r  r  rO  )r  r  base_urlr  s       rV   read_annotation_queueClient.read_annotation_queue   sf     )(J)G(HI,,jMM - 

 	++H544Gx}}GGrZ   )r  r  r  r  c                   0 nUb  X&S'   Ub  X6S'   Ub  XFS'   Ub  XVS'   U R                  SS[        US5       3U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 (Optional[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.
    rubric_items (Optional[list[AnnotationQueueRubricItem]]):
        The feedback configs to assign to this queue's rubric.

Returns:
    None
Nr  r  r  r  r  r  r  r6  r  )r  r  r  r  r  r  r4  r  s           rV   update_annotation_queueClient.update_annotation_queue!  s~    0  "L""-**=&'##/ ,,!(8Z"@!AB - 

 	++H5rZ   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  rt  rs  r  Nr  )r  r  r  s      rV   delete_annotation_queueClient.delete_annotation_queue6!  sP     ,,!(8Z"@!AB1CT]]C - 

 	++H5rZ   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[r*  r6  N)r  r  rp  r  ri   r  )r  r  r[  rt  r  r  s         rV   add_runs_to_annotation_queue#Client.add_runs_to_annotation_queueF!  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  r  r  Nr  )r  r  r  r  s       rV    delete_run_from_annotation_queue'Client.delete_run_from_annotation_queueZ!  sI     ,,!(8Z"@!AQWYaHbGcd
 	++H5rZ   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  r  r  rY   )r  r  r  ri   r  r  RunWithAnnotationQueueInforO  )r  r  r  r  r  s        rV   get_run_from_annotation_queue$Client.get_run_from_annotation_queuem!  sq      )(J)G(HM,,j%!MM - 

 	++H544Gx}}GGrZ   )r  r  rp  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   r  experiment_idsr  r  rp  r  r  r   r  z/datasets/comparativer  r  rY   )r   ro  r  r  r  rF  r(  rT   r)  r*  r  rc  r  ri   r  rO  r  ComparativeExperiment)r  r  experimentsr  r  rp  r   r   r4  r8  r9  serr  
response_ds                 rV   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   )r  tenant_handle)r  r   settingss      rV   _current_tenant_is_ownerClient._current_tenant_is_owner!  s,     %%'|>x55>>rZ   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: )ri   rl   r  r  )r  actionr   s      rV   _owner_conflict_errorClient._owner_conflict_error!  sH     **fX #113AAB C!!&)
 	
rZ   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/r  r  r  commitsr   r  N)r  rO  )r  prompt_owner_and_namer  r  r  r  s         rV   _get_latest_commit_hashClient._get_latest_commit_hash!  sX     ,,-.a0"5 - 

 --/),,3wqz-(==rZ   c                T  ^ ^^ [        U[        5      (       a  U/OUnSUUU 4S jjn[        R                  " 5        nU Vs/ s H  ovR	                  XW5      PM     nn[        R
                  " U5       H  n	U	R                  5         M     SSS5        gs  snf ! , (       d  f       g= f)aO  Update tags for a prompt commit.

Args:
    prompt_owner_and_name (str): The owner and name of the prompt in the format 'owner/repo'.
    commit_id (str): The commit hash/ID to tag.
    tags (Union[str, list[str]]): A single tag or list of tags to apply to the commit.

Raises:
    requests.exceptions.HTTPError: If the request fails.
c                f   > U TS.nTR                  SST S3US9n[        R                  " U5        g )N)tag_name	commit_idr  /repos/rQ  r6  r  )rT  r  r  r%  r  r  s      rV   
create_tag.Client._create_commit_tags.<locals>.create_tag!  sI    &G 00'"7!8>W 1 H //9rZ   N)rT  r  )r   r  r   r  r  r  r  )
r  r  r%  r	  tag_listr'  r  rT  r$  r  s
   ```       rV   _create_commit_tagsClient._create_commit_tags!  s     (c22D6	: 	: ""$CKL8Cz78GL//'2 3 %$L %$s   BB/BB
B'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/r  liker6  )ri   r   r  raise_for_statusrO  )r  r   r-  r   prompt_namer   r  s          rV   _like_or_unlike_promptClient._like_or_unlike_prompt"  sa      !) @ @AR SA,,geWAk]364. - 
 	!!#}}rZ   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/r  r*  Nr:  z	/prompts/z?organizationId=)ri   r   r  r]  r  r   )r  r   r   r/  r  r  s         rV   _get_prompt_urlClient._get_prompt_url$"  s     +3*J*J+
'K ,,U33nn%U5';-qRa@QRR%%'~~i}Ak"1o5Fx{{m-	
rZ   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      rV   _prompt_existsClient._prompt_exists;"  s      !23t(5(rZ   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-  r0  r  r   s     rV   like_promptClient.like_promptG"  s     **+<4*HHrZ   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:  r;  r<  s     rV   unlike_promptClient.unlike_promptS"  s     **+<5*IIrZ   r  ry  )r  r  	is_publicis_archived
sort_fieldsort_directionrX  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.
r  Nfalse)r  r  rB  rC  rD  rE  rX  match_prefixr  r&  r  rY   )r  r  ListPromptsResponserO  )
r  r  r  rB  rC  rD  rE  rX  r  r  s
             rV   list_promptsClient.list_prompts_"  si    : #I4It%06g$,&+F
 ,,UIf,M--@@@rZ   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&  r  r  NrY   )ri   r   r  r  PromptrO  r  r  r   r   r/  r   r  s         rV   r6  Client.get_prompt"  s{     !) @ @AR SA	00%+/H $$?x}}v'>??.. 		s   >A A10A1r  readmer	  rB  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  rQ  r	  rB  r  r&  r6  r  rY   )r  r  ri   rl   r   r  r  r  r.  r  rM  rO  )r  r   r  rQ  r	  rB  r  r   r/  r   rO  r  s               rV   create_promptClient.create_prompt"  s    8 %%'X33--6  !) @ @AR SA,,5,9,,->FF '&,"lJB"<
 ,,VYT,J!!#  ;8==?6#:;;rZ   parent_commit_hashr	  r  c                  U R                  U5      (       d  [        R                  " S5      e[        U5      n[	        U[
        5      (       a  SU;   a	  SU;   a  UnO% SSKJn  U" U5      n	[        R                  " U	5      n[        R                  " U5      u  pnU
 SU 3nUS:X  d  Uc  U R                  U5      nUUS	.nUb  X^S
'   U R                  SSU 3US9nUR                  5       S   nUS   nUS   nU(       a  U R                  UUU5        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.
    tags (Optional[str | list[str]]): A single tag or list of tags to apply to the commit.
        Defaults to None.
    description (Optional[str]): Optional human-readable description for the
        commit (max 1000 chars). Defaults to None.

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   r   )rP  vThe client.create_commit function requires the langchain-corepackage to run.
Install with `pip install langchain-core`r  latest)parent_commitr   r  r  r  r6  commitr  r*  )r7  ri   r  prep_obj_for_pushr   r   langchain_core.loadrP  r   rO  r  r   r   r  r*  r3  )r  r   rz  rX  r	  r  preppedmanifest_dictrP  json_objectr   r/  r   r  request_dictr  commit_jsonr  r%  s                      rV   create_commitClient.create_commit"  s   8 ""#45511B 
 $F+gt$$TW_#M5  .K JJ{3M ( @ @AR SA#(';- 8)-?-G!%!=!=>S!T 0%(
 "*5',,i 567l - 
 mmoh/!-0%	$$%:ItL##'<&=Q{m$LMM=  !Q s   D( (D>)r  rQ  r	  rB  rC  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.
rS  r  rQ  rB  rC  r	  r  r&  r  r6  )r  r  r   ri   r   r  r.  rO  )r  r   r  rQ  r	  rB  rC  r  rO  r   r/  r   r  s                rV   update_promptClient.update_prompt #  s    : %%'X336  <>""-#N  )""-L ( @ @AR SA,,wugQ{m44 - 
 	!!#}}rZ   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&  r  N)ri   r   r  r  r  r.  rN  s         rV   delete_promptClient.delete_promptZ#  sj     !) @ @AR SA,,U33,,->FF,,Xq7VW!!#rZ   c                $    U(       a  SOSnU U 3$ )zGenerate a cache key for a prompt.

Args:
    prompt_identifier: The prompt identifier.
    include_model: Whether model info is included.

Returns:
    The cache key string.
z:with_modelr  rY   )r  r   r  r  s       rV   _get_cache_keyClient._get_cache_keym#  s     #0R#$VH--rZ   c           
         [         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$ )zFetch a prompt directly from the API (no cache).

Args:
    prompt_identifier: The prompt identifier.
    include_model: Whether to include model information.

Returns:
    The fetched PromptCommit.
r  r  r  z?include_model=truer  r   r  rY   )ri   r   r  r  PromptCommitrO  )r  r   r  r   r/  r  r  s          rV   _fetch_prompt_from_apiClient._fetch_prompt_from_api|#  s     +3*J*J+
'K ,,E7!K=+,9(rBD
 && 
FhmmoF
 	
rZ   r  
skip_cacher   c               `   [        UUS9  [        U R                  X5      nU(       d>  U R                  b1  U R	                  X5      nU R                  R                  Xe5      nUb  U$ U" 5       nU(       d:  U R                  b-  U R	                  X5      nU R                  R                  XhU5        U$ )a  Pull a prompt object from the LangSmith API.

Public prompts referenced by owner/name cross a trust boundary because the
prompt manifest may contain serialized LangChain objects and configuration
that affect runtime behavior. For example, a prompt can intentionally
configure a model with a custom base URL, headers, model name, or other
constructor arguments. These are supported features, but they also mean
the prompt contents should be treated as executable configuration rather
than plain text.

Set `dangerously_pull_public_prompt=True` only after reviewing and
trusting the prompt contents, not merely the publishing account. Prompts
from your own or your organization's account can still be unsafe if that
account or prompt was compromised.

Args:
    prompt_identifier: The identifier of the prompt.
    include_model: Whether to include model information.
    skip_cache: Whether to skip the prompt cache. Defaults to `False`.
    dangerously_pull_public_prompt: Set to `True` to allow pulling a
        public prompt by owner/name, for example `username/promptname`.
        Defaults to `False`.

Returns:
    The prompt object.

Raises:
    ValueError: If no commits are found for the prompt.
)r   )r   r
   rs  r  rn  r  r   )	r  r   r  rv  r   refresh_func	cache_keycachedr  s	            rV   pull_prompt_commitClient.pull_prompt_commit#  s    J 	%+I	
 ''):

 dkk5++,=MI[[__Y=F!  dkk5++,=MIKKOOI|<rZ   r  r  r  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.
Nr  r}  r   r  r  r  r  r  r  r8  rq  rK   rY   )ri   r   r  r  rO  r  ListedPromptCommitr  )r  r   r  r  r  r   r/  r   r  rt  r  valrc  r8  its                  rV   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<)r  r  r   rv  r   c               >    U R                  UUUUS9n[        UUUUS9$ )a  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.
    secrets: A map of secrets to use when loading, e.g.
        `{'OPENAI_API_KEY': 'sk-...'}`.

        If a secret is not found in the map, it will be loaded from the
        environment if `secrets_from_env` is `True`. Should only be needed when
        `include_model=True`.
    secrets_from_env: Whether to load secrets from the environment.

        **SECURITY NOTE**: Should only be set to `True` when pulling trusted
        prompts.
    skip_cache: Whether to skip the prompt cache. Defaults to `False`.
    dangerously_pull_public_prompt: Set to `True` to allow pulling a
        public prompt by owner/name (for example, `username/promptname`).
        Only do this for trusted prompts. Defaults to `False`.

Returns:
    Any: The prompt object in the specified format.

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

    Updated to take arguments `secrets` and `secrets_from_env` which default
    to None and False, respectively.

    By default secrets needed to initialize a pulled object will no longer be
    read from environment variables. This is relevant when
    `include_model=True`. For example, to load an OpenAI model you need to
    have an OPENAI_API_KEY. Previously this was read from environment
    variables by default. To do so now you must specify
    `secrets={"OPENAI_API_KEY": "sk-..."}` or `secrets_from_env=True`.
    `secrets_from_env` should only be used when pulling trusted prompts.

    These updates were made to remediate vulnerability
    [GHSA-c67j-w6g6-q2cm](https://github.com/langchain-ai/langchain/security/advisories/GHSA-c67j-w6g6-q2cm)
    in the `langchain-core` package which this method (but not the entire
    langsmith package) depends on.
ru  )r  r  r   )r{  r  )r  r   r  r  r   rv  r   r
  s           rV   pull_promptClient.pull_prompt$  sA    j //'!+I	 0 
 ('-	
 	
rZ   r[  )rz  rX  rB  r  rQ  r	  commit_tagscommit_descriptionc                  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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.
    commit_tags (Optional[str | list[str]]): A single tag or list of tags for the prompt commit.
        Defaults to an empty list.
    commit_description (Optional[str]): Optional human-readable description
        for the commit (max 1000 chars). Defaults to None.

Returns:
    str: The URL of the prompt.
c              3  (   #    U  H  oS Lv   M
     g 7fr   rY   )r   params     rV   r   %Client.push_prompt.<locals>.<genexpr>$  s      /UeT!/U   rP  F)rB  r  rQ  r	  )r   rW  )r7  r   rh  rU  r3  re  )r  r   rz  rX  rB  r  rQ  r	  r  r  r-  s              rV   push_promptClient.push_promptS$  s    X 011 09/U   ""% +!' #  !'0'<)%'   >'':K'LL   1* ! 
 
rZ   r   c               b    U R                  USUS9n[        R                  R                  U5      $ )zPull an agent from Hub.

Args:
    identifier: Repo identifier (owner/name:hash, owner/name, or name).
    version: Commit hash or tag; overrides any hash in identifier.

Returns:
    AgentContext: The agent snapshot.
agentr  )_pull_hub_directoryr  AgentContextmodel_validater  
identifierr   r  s       rV   
pull_agentClient.pull_agent$  s2     ''
GW'M&&55d;;rZ   )r\  r  rQ  r	  rB  c               .    U R                  USUUUUUUS9$ )z=Push an agent to Hub, creating the repo if it does not exist.r  r  r\  r  rQ  r	  rB  _push_hub_directoryr  r  r  r\  r  rQ  r	  rB  s           rV   
push_agentClient.push_agent$  4     '''# ( 	
 		
rZ   c               b    U R                  USUS9n[        R                  R                  U5      $ )zPull a skill from Hub.skillr  )r  r  SkillContextr  r  s       rV   
pull_skillClient.pull_skill$  s2     ''
GW'M&&55d;;rZ   c               .    U R                  USUUUUUUS9$ )zPush a skill to Hub.r  r  r  r  s           rV   
push_skillClient.push_skill$  r  rZ   c                &    U R                  U5        g)z/Delete an agent and its owned child file repos.N_delete_hub_directoryr  r  s     rV   delete_agentClient.delete_agent$      "":.rZ   c                &    U R                  U5        g)z.Delete a skill and its owned child file repos.Nr  r  s     rV   delete_skillClient.delete_skill$  r  rZ   c                V    [         R                  " U5      u  p#nU R                  X#5      $ )zCheck if an agent repo exists.ri   parse_hub_identifier_hub_repo_existsr  r  r   r  r   s        rV   agent_existsClient.agent_exists$  '    !66zBQ$$U11rZ   c                V    [         R                  " U5      u  p#nU R                  X#5      $ )zCheck if a skill repo exists.r  r  s        rV   skill_existsClient.skill_exists$  r  rZ   r  r  rB  rC  rX  c          	     *    U R                  SUUUUUS9$ )zList agents with pagination.r  r  _list_hub_reposr  r  r  rB  rC  rX  s         rV   list_agentsClient.list_agents$  .     ### $ 
 	
rZ   c          	     *    U R                  SUUUUUS9$ )zList skills with pagination.r  r  r  r  s         rV   list_skillsClient.list_skills%  r  rZ   c          	         [         R                  " U5      u  pEnUb  UO	US:w  a  UOSnSU0nU(       a  XxS'   U R                  S[         SU SU S3US9n	U	R	                  5       $ )	zDFetch hub directory payload, merged with owner/repo from identifier.Nr[  	repo_typer]  r  r  /directoriesr  )ri   r  r  r/   rO  )
r  r  r  r   r   r  r]  r  r  r  s
             rV   r  Client._pull_hub_directory"%  s     ';;JGV*G6X;MSW 	 #.y!9%8,,nAeWAdV<8 - 

 }}rZ   c          
        [        U5        [        R                  " U5      u  pnU R                  U	5      (       d  U R	                  SU 3U	5      eU R                  X5      (       a.  [        S XVXx4 5       5      (       a  U R                  U	U
UUUUS9  Od[        R                  " U
5      (       d,  [        R                  " SU
< S[        R                   S35      eU R                  U
UUUU[        U5      S9  0 nUR                  5        H  u  pUc  SX'   M  UR                  SS	9X'   M!     S
U0nUb  XOS'   U R!                  S["         SU	 SU
 S3US9nUR%                  5       S   S   n['        U R(                  XU5      $ )zFCreate a hub directory commit, creating the repo if it does not exist.zpush c              3  (   #    U  H  oS Lv   M
     g 7fr   rY   )r   r9  s     rV   r   -Client._push_hub_directory.<locals>.<genexpr>L%  s     Q*PQD=*Pr  rP  zInvalid repo_handle z: must match r?  NTr  r  r\  r  r  z/directories/commitsr6  r]  r  )r2   ri   r  r  r  r  r   _update_hub_repo_metadatar0   matchrl   pattern_create_hub_repor  rc  r  r  r/   rO  r1   r]  )r  r  r  r  r\  r  rQ  r	  rB  r   r  r   request_filesr  entryr4  r  r  s                     rV   r  Client._push_hub_directory8%  s    	}-!66zBQ,,U33,,uYK-@%HH  --Q;*PQQQ.. +!' /  ',,T2211*4( 3""5"="=!>aA  !!'y/ "  >@ ;;=KD}&*#&+&6&6D&6&I#	 ) !(7$$1!,,nAeWAdV+?@ - 

 mmoh/>[IIrZ   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 S35        g)zDelete a hub directory repo.deleter  r  r  N)ri   r  r  r  r  r/   r  s        rV   r  Client._delete_hub_directoryw%  sa    !66zBQ,,U33,,Xu==!!nAeWAdV<8	
rZ   c                   UUUU(       a  SOSS.nUb  U(       a  SOSUS'   U(       a	  XgS'   SUS'   U R                  S[        US9n[        R                  " S	0 UR	                  5       D6$ )
u   List hub repos filtered by type.

Returns ``ListPromptsResponse`` because ``/repos`` is polymorphic — the
list shape is shared across prompt, agent, and skill repos.
r  rG  )r  r  r  rC  rB  rX  rH  r  r  rY   )r  r.   r  rI  rO  )	r  r  r  r  rB  rC  rX  r  r  s	            rV   r  Client._list_hub_repos%  sv      "%06g	"
  ,5&7F;#7O%+F>",,UC,G--@@@rZ   c                v     U R                  S[         SU SU 35        g! [        R                   a     gf = f)zCheck if a hub repo exists.r  r  TF)r  r.   ri   r  )r  r   r  s      rV   r  Client._hub_repo_exists%  sC    	%%euAeWAdV-DE.. 		s   ! 88c                   UUUS.nUb  X7S'   Ub  XGS'   Ub  [        U5      US'    U R                  SSUS9  g! [        R                   a     gf = f)	z(Create a new hub repo of the given type.)rT  r  rB  Nr  rQ  r	  r  r&  r6  )r   r  ri   r  )r  r  r  r  rQ  r	  rB  r4  s           rV   r  Client._create_hub_repo%  sv      "" 

 ""-#N:DL	%%fid%C.. 		s   9 AAc                   0 nUb  X7S'   Ub  XGS'   Ub  [        U5      US'   Ub  XgS'   U(       a  U R                  S[         SU SU 3US9  gg)	z=Patch hub repo metadata fields that were explicitly provided.Nr  rQ  r	  rB  r  r  r6  )r   r  r.   )r  r   r  r  rQ  r	  rB  r4  s           rV   r   Client._update_hub_repo_metadata%  ss      """-#N:DL  )%%g#awav/FT%R rZ   c                     U R                  US9  SU l        U R
                  b  U R
                  R                  5         gg! [         a   n[        R                  SU5         SnANUSnAff = f)ay  Manually trigger cleanup of background threads.

Drains pending traces via ``flush()`` before stopping the background
threads. Pass ``timeout=0`` to skip the drain entirely (e.g. in error
paths or signal handlers where blocking on network I/O is
unacceptable).

Args:
    timeout: Maximum seconds to wait for pending traces to flush.
        None (default) waits indefinitely.
r  z(Error flushing traces during cleanup: %sNT)r/  r   rQ   rR   r  r  shutdown)r  r  r  s      rV   cleanupClient.cleanup%  se    	JJJwJ'  $;;"KK  " #  	JNNEqII	Js   A 
A+A&&A+c                   g r   rY   r  r  r  
evaluatorssummary_evaluatorsr   experiment_prefixr  r  num_repetitionsblocking
experimentupload_resultsr	  s                 rV   evaluateClient.evaluate%  s    "  rZ   c                   g r   rY   r  s                 rV   r  r  %  s    " (+rZ   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  r  r  r  r  r   r  r  r  r  r  r  r  r  r	  	evaluate_s                   rV   r  r  &  sQ    \ 	G 
!1/#++!))
 
 	
rZ   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  r  r  r  r  r   r  r  r  r  r  r  r  r  r	  
aevaluate_s                   rV   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   Nr  )session_idsr  r  previewrs  filtersr  r  r  r  r  rY   )r  r  r  rO  r  rC   r  )r  r  r  r   rs  r  r  r  results_countr.  batch_limitr4  r  r  r  examples_batchs                   rV   _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.model_dump())

    # 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)rU  rN  r  z&No experiment found with project_id: 'rb  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   rs  r  r  N)r  r  r   )r  rs  r  r  r   r  r  s    rV    _get_examples_with_runs_iteratorGClient.get_experiment_results.<locals>._get_examples_with_runs_iteratord(  sL     ::"77"::*C ;  !   !s   1A >
A )	run_countlatency_p50latency_p99rh  re  r`  last_run_start_time
run_facetsrg  rd  r_  first_token_p50first_token_p99
error_rate)ra  	run_statsexamples_with_runs)ro  r   r  r  r  rh  re  r`  r  r  rg  rd  r_  r  r  r  ra  session_feedback_statsr  r   )r  r  rN  r   rs  r  r  r	  r  ra  r  s   `  ````   @rV   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
 	
rZ   )instructionsr  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?rK   )r  user_contextlast_n_hoursr  r  r  z	/insightsr6  rN  rZ  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: rY   )_ensure_insights_api_key_ingest_insights_runsr  r   ri   r  rO  r  InsightsReportr  r]  printr^  )r  chat_historiesr  r  r  r  r  r  rz  r  rl  reports               rV   generate_insightsClient.generate_insights(  s    D --)/ . 

 ,,^B :tBN 
 ,,jI6V - 
 	++H5mmo** 

zz))+^^	
 	R{{m	

 rZ   r  i  )r'  r   rN  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.
1Must specify ('id' and 'project_id') or 'report'.@Must specify exactly one of ('id' and 'project_id') or 'report'.rK   r  r  
/insights/rf  successr   z1Insights report completed! View the results at %srS  zFailed to generate insights: zPolling time: zInsights still pendingrY   )r   r   rN  r  r  r  ri   r  rO  r  r$  r  r]  r%  r^  rN   r  TimeoutError)r  r'  r   rN  r*  r  r+  	max_triesrt  r  	resp_jsonjobs               rV   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4rZ   )r   r'  rN  include_runsc                  Ub*  Uc  Ub  [        S5      eUR                  nUR                  nOUb  Uc  [        S5      eUnUnU R                  SSU SU 35      n[        R
                  " U5        UR                  5       nU(       d*  [        R                  " S0 UD6n	U	R                  XU5        U	$ [        R                  " U UUS9US'   [        R                  " S0 UD6n	U	R                  XU5        U	$ )	a  Fetch an Insights report by ID or from a prior report object.

Args:
    id: The Insights report ID (aka clustering job ID). Provide with
        ``project_id`` if ``report`` is not provided.
    report: An ``InsightsReport`` object returned by ``generate_insights`` or
        ``poll_insights``. If provided, ``id`` and ``project_id`` must be omitted.
    project_id: The tracing project (session) ID associated with the report.
        Required if ``report`` is not provided.
    include_runs: Whether to include all runs for the report.

Returns:
    An ``InsightsReportResult`` with job metadata, clusters, summary report,
    and optionally ``runs``.

Raises:
    ValueError: If the required identifiers are not provided.
r.  r-  r  r  r/  )r  r  job_idr  rY   )r   r   rN  r  ri   r  rO  r  InsightsReportResult_attach_client_fetch_insights_runs)
r  r   r'  rN  r7  r9  r  respreport_jsonr  s
             rV   get_insights_reportClient.get_insights_report#)  s
   6 ~!7 V  YYF**JzZ/ !TUUF#J((Z
|:fX>
 	++D1iik44C{CF!!$F;M(==!
F
 00?;?d7rZ   )rf  priorityc               ,   SU0nUb  X$S'   Ub  X4S'   [        U R                  S5      n[        U R                  U5      nU R                  R	                  SUUU R
                  U R                  S9n[        R                  " U5        UR                  5       $ )az  List issues associated with a tracing project (forge issues board).

Retrieves all issues from the forge issues board that are linked to the
given tracing project (identified by its session name).

Args:
    project_name (str): The name of the tracing project (session) whose
        issues you want to list.
    status (Optional[str]): Filter issues by status (e.g. ``"open"``,
        ``"resolved"``). If ``None``, issues of all statuses are returned.
    priority (Optional[str]): Filter issues by priority (e.g.
        ``"high"``, ``"medium"``, ``"low"``). If ``None``, issues of all
        priorities are returned.

Returns:
    List[dict]: A list of issue objects. Each dict contains the following
    keys:

    - ``id`` (str): Issue UUID.
    - ``tenant_id`` (str): Workspace/tenant UUID.
    - ``issue_board_id`` (str): UUID of the issue board this issue belongs to.
    - ``title`` (str): Issue title.
    - ``description`` (str): Issue description.
    - ``priority`` (str): Issue priority.
    - ``status`` (str): Issue status.
    - ``category`` (str | None): Optional category label.
    - ``trace_ids`` (List[str]): Run/trace IDs associated with the issue.
    - ``github_issue_url`` (str | None): URL of the linked GitHub issue.
    - ``github_issue_number`` (int | None): Number of the linked GitHub issue.
    - ``created_at`` (str): ISO-8601 creation timestamp.
    - ``updated_at`` (str): ISO-8601 last-updated timestamp.
    - ``resolved_at`` (str | None): ISO-8601 resolution timestamp, or ``None``.

Example:
    ```python
    from langsmith import Client

    client = Client()

    # List all issues for a project
    issues = client.list_project_issues("my-project")

    # Filter by status and priority
    open_high = client.list_project_issues(
        "my-project", status="open", priority="high"
    )
    for issue in open_high:
        print(issue["id"], issue["title"])
    ```
r]  rf  rA  zforge-issuesr  )r  r  r  )
r+  r"  r  rL  r  r  r  ri   r  rO  )r  rU  rf  rA  r  r  r,  r  s           rV   list_project_issuesClient.list_project_issues_)  s    r #1,!?%8!):dllN;!$,,5<<''MMMM ( 
 	++H5}}rZ   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/secretsrD  )Nopenai)N	anthropicrF  rG  z1Must specify openai_api_key or anthropic_api_key.r  )rD  rl  r6  )r  ri   r  rO  r  r   rJ  _OPENAI_API_KEY_ANTHROPIC_API_KEYintersectionr   )r  r  r  r  r  sworkspace_keystarget_keysexisting_keysrR  api_vars              rV   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 )Nr  zDCan only generate insights over 1000 data. Truncating to first 1000.z	insights z%Y-%m-%d %H:%M:%Sry  rK   z%Y%m%dT%H%M%S%fZ)r  r0  r}   )
r  r  r   rH  rm  r  r  r  r  r  )r  )r  ro   rp   r(  rT   r)  r*  r  strftimer  r  r  rF  r  r  r   r  r/  )
r  r  r  rT   r  r   r[  r  r   r  s
             rV   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  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rf  rR  r"  r  r  r  rL  r  r  r  r   )8r"  r  rR  r  r  zOptional[Retry]r  z%Optional[Union[int, tuple[int, int]]]r  r  rL  zOptional[requests.Session]r  r  r  z Optional[Callable[[dict], dict]]r  -Optional[Union[Callable[[dict], dict], bool]]r  rT  r  rT  r  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]rs   Optional[TracingMode]ra   Optional[bool]r\  rV  r  r  r  rU  r  rW  r  z%Optional[Callable[[Exception], None]]r  r  r  z"Optional[Union[bool, PromptCache]]r  r  )r3  zCallable[[], bytes]r  r   r  r  )rT  r  r4  r  r/  r  r  r   r0  rU  r  r  )r  r  )rS  r   r  r  )r  r  )r|  r  rl  r   r  r  )r  r  )rl  r  r  r  )rl  rW  r  r  )r  zls_schemas.LangSmithInfo)r  zls_schemas.LangSmithSettings)r  rU  r  r  )r  z0Literal['GET', 'POST', 'PUT', 'PATCH', 'DELETE']r  r  r  zOptional[Mapping]r  rD  r  'Optional[Sequence[type[BaseException]]]r  rZ  r  z1Optional[Callable[[requests.Response, int], Any]]r  r  r	  r   r  zrequests.Response)r  r  r  Optional[dict]r  Iterator[dict])
r  r  r4  r[  r  zLiteral['GET', 'POST']r  r  r  r\  )r  pd.DataFramer  r  r  Sequence[str]r  r^  r  r  r  Optional[ls_schemas.DataType]r  ls_schemas.Dataset)r  z?Union[str, tuple[str, io.BytesIO], tuple[str, io.BytesIO, str]]r  r^  r  r^  r  r  r  r  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[Union[dict, ls_schemas.Run, ls_schemas.RunLikeDict]]r@  r  r  r   )r  TracingMode)rR  r%   r  r  )r  r  r  dict[str, Any]r  
RUN_TYPE_TrU  r  rV  r  rW  r  rR  r  r"  r  r	  r   r  r  )r,  r   rR  r  r"  r  rY  r  rZ  r  r[  r  r\  r  r  r  )r,  r   rR  r  r"  r  rY  r  rZ  r  r[  r  r\  r  )r  r   )r  r   )r   r   r  r   )r  Optional[Sequence[dict]]r  zOptional[list[dict]]r  r  )r  zlist[SerializedRunOperation]r"  r  rR  r  rY  r  rZ  r  r[  r  r\  r  r  r  r  )r  GOptional[Sequence[Union[ls_schemas.Run, ls_schemas.RunLikeDict, dict]]]r  rg  r  r  )r4  r  r  r  r"  r  rR  r  rY  r  rZ  r  r[  r  r\  r  )r  z@list[Union[SerializedRunOperation, SerializedFeedbackOperation]]r"  r  rR  r  rY  r  rZ  r  r[  r  r\  r  r  r  )r  rg  r  rg  rW  r  r  r  )r  r4   r  rD  r"  r  rR  r  rY  r  rZ  r  r[  r  r\  r  )r  z
io.BytesIOr  zOptional[tuple[int, int]]r  rD  ),r  ID_TYPEr  r  r  zOptional[RUN_TYPE_T]r  Optional[datetime.datetime]r  ri  rS  r  r  r[  r  r[  r  re  r  r[  r	  Optional[list[str]]r_   Optional[ls_schemas.Attachments]rW  r  r
  str | uuid.UUID | NonerR  r  r"  r  rY  r  rZ  r  r[  r  r\  r  r	  r   r  r  )r  r   rR  r  r"  r  rY  r  rZ  r  r[  r  r\  r  )r  r   rR  r  r"  r  rY  r  rZ  r  r[  r  r\  r  r  r  )r\   N)r  rD  r  rV  r  r  )r  rV  r  r  )r+  ls_schemas.Runr  rm  r  )r  rh  rI  r  r  rm  )r  r  rN  +Optional[Union[ID_TYPE, Sequence[ID_TYPE]]]rU  #Optional[Union[str, Sequence[str]]]r2  r  r  rU  rO  Optional[Sequence[str]]rP  r  rQ  zLiteral['asc', 'desc']r	  r   r  Iterator[ls_schemas.Run])$rN  rn  rU  ro  r  r  rH  Optional[ID_TYPE]r
  rr  rX  r  rP  r  rY  r  rZ  r  r2  rY  r  rr  r  ri  rS  rY  r[  Optional[Sequence[ID_TYPE]]rO  rp  r  rU  r	  r   r  rq  )rN  rr  rU  r  r  rU  r  rD  rP  r  r  ri  r  zlist[ListThreadsItem])"r   Optional[list[ID_TYPE]]r}   rr  rk  rr  r  r  r  rj  rq  rt  r  rt  r  r  r  r  rS  rY  rX  r  rP  r  rY  r  rZ  r  r2  rY  r  r  r  rc  )r+  zls_schemas.RunBaserU  r  rN  rr  r  r  )r  rh  r  rr  r  r  )r  rh  r  r  )r  rh  r  r  )r  rh  r  r  )r  Union[ID_TYPE, str]r  rr  r  rm  )r  ru  r[  rj  r  rq  )r  rr  r  r  r  zls_schemas.DatasetShareSchema)r  rh  r  r  )r  r  r  r`  )r  r  r  rt  r  rU  r  Iterator[ls_schemas.Example])r  r  rq  rt  r  r  r  r  r  rU  r  (Iterator[ls_schemas.TracerSessionResult])rU  r  r  r  r   r[  r  r  r  r[  r  rr  r  ls_schemas.TracerSession)rN  rh  r  r  r  r  r   r[  r  r[  r  ri  r  rx  )r  Optional[uuid.UUID])r  	uuid.UUID)rN  r  rU  r  r  r  r  zls_schemas.TracerSessionResult)rU  r  rN  r  r  r  )rN  rr  rU  r  r  r]  )
NNNNNNNNNN)rq  rt  r  r  r  r  r  rr  r!  r  r  rY  r  rY  r   r  r  rU  r   Optional[dict[str, Any]]r  rw  )rU  r  rN  r  r  r  )r  r  r  r  r  ls_schemas.DataTyper'  r{  r(  r{  r)  z0Optional[list[ls_schemas.DatasetTransformation]]r   r[  r  r`  )r  r  r  rr  r  r  )r  r  r  rr  r  r`  )
r  rr  r  r  r<  Union[str, datetime.datetime]r=  r}  r  zls_schemas.DatasetDiffInfo)r  rr  r  r  r  r   )rH  rt  r  r  r  r  rI  r  r   r{  r  rU  r  zIterator[ls_schemas.Dataset])r  rr  r  r  r  r  )
r  rr  r  r  rS  zdatetime.datetimerT  r  r  r  )
r  rr  r  r  rX  r  r  rU  r  z#Iterator[ls_schemas.DatasetVersion])
r  rr  r  r  rS  ri  rT  r  r  zls_schemas.DatasetVersion)rf  r  r`  r  r  r  r  r`  )r  rh  r  r|  )NNNN)r  r  rr  r  r  rr  r  r  rp  ri  r  ls_schemas.Example)ry  z:list[Union[Mapping[str, Any], ls_schemas.BaseMessageLike]]rz  z>Optional[Union[Mapping[str, Any], ls_schemas.BaseMessageLike]]r  rr  r  r  rp  ri  r  r~  r  )
r+  rm  r  rr  r  r  rp  ri  r  r~  )r   zwUnion[list[ls_schemas.ExampleCreate] | list[ls_schemas.ExampleUpsertWithAttachments] | list[ls_schemas.ExampleUpdate],]r  r  rW  r  r  z/tuple[Any, bytes, dict[str, io.BufferedReader]])r  rh  r  z(Optional[list[ls_schemas.ExampleUpdate]]rW  r  r  !ls_schemas.UpsertExamplesResponse)r  rh  r  z(Optional[list[ls_schemas.ExampleCreate]]rW  r  r  r  )r  zls_schemas.ExampleCreater  rD  )r  )r   zlist[ls_schemas.ExampleCreate]r  rD  r  z$list[list[ls_schemas.ExampleCreate]])r  z7Optional[list[ls_schemas.ExampleUpsertWithAttachments]]rW  r  r  r  )r  r  r  rr  r   z3Optional[Sequence[ls_schemas.ExampleCreate | dict]]rW  r  r  z!Annotated[int, Field(ge=1, le=3)]r	  r   r  z2ls_schemas.UpsertExamplesResponse | dict[str, Any])NNNNNNNNNFNN)r  Optional[Mapping[str, Any]]r  rr  r  r  rp  ri  r  r  r   r  r  Optional[str | list[str]]r  rr  r  rr  r  r  r  rj  r_  rk  r  r~  )r  rh  rS  ri  r  r~  )NNNNNT)r  rr  r  r  r  rs  rS  z'Optional[Union[datetime.datetime, str]]r  rp  r
  r  r  rD  r  rU  r   r[  rP  r  r  r  r	  r   r  rv  )r  rh  r  r{  r  r  r   r[  r  r  r  rr  r  z*Optional[ls_schemas.AttachmentsOperations]r_  rk  r  rc  )r  
str | Noner  zID_TYPE | Noner  z3Optional[Sequence[ls_schemas.ExampleUpdate | dict]]rW  r  r	  r   r  rc  )r  rh  r  r  )r  Sequence[ID_TYPE]r'  r  r  r  )r  rr  r  r  rS  z'Optional[Union[str, datetime.datetime]]r  z	list[str])r  rr  r  r  r5  r  r  list[ID_TYPE]rJ  r  r  r  )r+  9Union[ls_schemas.Run, ls_schemas.RunBase, str, uuid.UUID]rI  r  r  rm  )r  z5Union[ls_schemas.Example, str, uuid.UUID, dict, None]r+  rm  r  zOptional[ls_schemas.Example])r  JUnion[ls_evaluator.EvaluationResult, ls_evaluator.EvaluationResults, dict]rB  r  r  #list[ls_evaluator.EvaluationResult])r+  r  r   ls_evaluator.RunEvaluatorrU  r{  rj  9Optional[Union[ls_schemas.Example, str, dict, uuid.UUID]]rI  r  r  rP  )r\  r  r+  zOptional[ls_schemas.Run]rU  r{  rN  rr  r^  zOptional[cf.ThreadPoolExecutor]r  r  )r+  z%Union[ls_schemas.Run, str, uuid.UUID]r   r  rU  r{  rj  r  rI  r  r  rP  )Nunnamed),r  rr  rD  r  rX  Union[float, int, bool, None]rl  (Union[float, int, bool, str, dict, None]rH  rr  rd  Union[dict, None]rF  Union[str, None]rU  r{  rf  z)Union[ls_schemas.FeedbackSourceType, str]r  rr  rr  rr  re  #Optional[ls_schemas.FeedbackConfig]r  rD  rN  rr  rs  rr  rt  rr  r  r[  rS  rY  r  rr  r  ri  r	  r   r  ls_schemas.Feedback)rr  rh  rX  r  rl  r  rd  r  rF  r  r  r  )rr  rh  r  r  )r[  rs  r  rp  rf  z1Optional[Sequence[ls_schemas.FeedbackSourceType]]r  rU  r	  r   r  zIterator[ls_schemas.Feedback])rr  rh  r  r  )rf  Union[str, uuid.UUID]rX  r  rl  r  rd  r  rF  r  r   r[  r  r  )r  rh  r  r  r  0Optional[datetime.datetime | datetime.timedelta]re  r  rr  rr  r  zls_schemas.FeedbackIngestToken)
r  rh  r  r^  r  r  r  z7Optional[Sequence[Optional[ls_schemas.FeedbackConfig]]]r  z(Sequence[ls_schemas.FeedbackIngestToken])r  rh  r  rU  r  z(Iterator[ls_schemas.FeedbackIngestToken])
r  rr  r  rr  r  rU  r  rD  r  z$Iterator[ls_schemas.FeedbackFormula])r  rh  r  ls_schemas.FeedbackFormula)r  r  r  Literal['sum', 'avg']r  ASequence[Union[ls_schemas.FeedbackFormulaWeightedVariable, dict]]r  rr  r  rr  r  r  )
r  rh  r  r  r  r  r  r  r  r  )r  rh  r  r  )r  r  re  zls_schemas.FeedbackConfigr  rY  r  ls_schemas.FeedbackConfigSchema)
r  rp  r  r  r  rU  r  rD  r  z)Iterator[ls_schemas.FeedbackConfigSchema])r  r  re  r  r  rY  r  r  )r  r  r  r  )
r  rt  r  r  r  r  r  rU  r  z$Iterator[ls_schemas.AnnotationQueue])r  r  r  r  r  rr  r  r  r  4Optional[list[ls_schemas.AnnotationQueueRubricItem]]r  z%ls_schemas.AnnotationQueueWithDetails)r  rh  r  zls_schemas.AnnotationQueue)r  rh  r  r  r  r  r  r  r  r  r  r  )r  rh  r  r  )r  rh  r[  r  r  r  )r  rh  r  rh  r  r  )r  rh  r  rD  r  z%ls_schemas.RunWithAnnotationQueueInfo)r  r  r  r  r  rr  r  r  rp  ri  r   r{  r   rr  r  z ls_schemas.ComparativeExperiment)r   r  r  r  )r  r  r   r  r  zls_utils.LangSmithUserError)rK   r   )r  r  r  rD  r  rD  r  r  )r  r  r%  r  r	  zUnion[str, list[str]]r  r  )r   r  r-  r  r  dict[str, int])r   r  r  r  )r   r  r  r  )r   r  r  r  )r  rD  r  rD  rB  rY  rC  rY  rD  zls_schemas.PromptSortFieldrE  zLiteral['desc', 'asc']rX  r  r  ls_schemas.ListPromptsResponse)r   r  r  zOptional[ls_schemas.Prompt])r   r  r  r  rQ  r  r	  rp  rB  r  r  zls_schemas.Prompt)r   r  rz  r   rX  r  r	  r  r  r  r  r  )r   r  r  r  rQ  r  r	  rp  rB  rY  rC  rY  r  rc  )r   r  r  r  )r   r  r  rY  r  r  )r   r  r  rY  r  ls_schemas.PromptCommit)
r   r  r  rY  rv  r  r   r  r  r  )
r   r  r  rU  r  rD  r  r  r  z'Iterator[ls_schemas.ListedPromptCommit])r   r  r  bool | Noner  dict[str, str] | Noner   r  rv  r  r   r  r  r   )r   r  rz  zOptional[Any]rX  r  rB  rY  r  r  rQ  r  r	  rp  r  r  r  r  r  r  )r  r  r   r  r  zls_schemas.AgentContext)r  r  r  z%dict[str, Optional[ls_schemas.Entry]]r\  r  r  r  rQ  r  r	  rp  rB  rY  r  r  )r  r  r   r  r  zls_schemas.SkillContext)r  r  r  r  )r  r  r  r  )r  rD  r  rD  rB  rY  rC  rY  rX  r  r  r  )r  r  r  Literal['agent', 'skill']r   r  r  rc  )r  r  r  r  r  rc  r\  r  r  r  rQ  r  r	  rp  rB  rY  r  r  )r  r  r  rD  r  rD  rB  rY  rC  rY  rX  r  r  r  )r   r  r  r  r  r  )r  r  r  r  r  r  rQ  r  r	  rp  rB  r  r  r  )r   r  r  r  r  r  rQ  r  r	  rp  rB  rY  r  r  )NNNNNNr   rK   TNT)r  Optional[DATA_T]r  zOptional[Sequence[EVALUATOR_T]]r  'Optional[Sequence[SUMMARY_EVALUATOR_T]]r   r[  r  r  r  r  r  rU  r  rD  r  r  r  Optional[EXPERIMENT_T]r  r  r  z'Union[TARGET_T, Runnable, EXPERIMENT_T]r	  r   r  r   )r  r  r  z+Optional[Sequence[COMPARATIVE_EVALUATOR_T]]r  r  r   r[  r  r  r  r  r  rU  r  rD  r  r  r  r  r  r  r  z(Union[tuple[EXPERIMENT_T, EXPERIMENT_T]]r	  r   r  r   )NNNNNNr   rK   TNTrs  )r  r  r  zIOptional[Union[Sequence[EVALUATOR_T], Sequence[COMPARATIVE_EVALUATOR_T]]]r  r  r   r[  r  r  r  r  r  rU  r  rD  r  r  r  r  r  r  r  Literal['log', 'ignore']r  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  r  r  r  r  rU  r  rD  r  r  r  z6Optional[Union[schemas.TracerSession, str, uuid.UUID]]r  r  r  r  r  zVUnion[ATARGET_T, AsyncIterable[dict], Runnable, str, uuid.UUID, schemas.TracerSession]r	  r   r  r   )FNNN)r  rh  r  rz  r   r  rs  ry  r  !dict[uuid.UUID, list[str]] | Noner  rU  r  zIterator[list[ExampleWithRuns]])NNFNNN)r  r  rN  ry  r   r  rs  ry  r  r  r  rU  r  zls_schemas.ExperimentResults)r&  zlist[list[dict]]r  r  r  r  r  %Literal['openai', 'anthropic'] | Noner  r  r  r  r  ls_schemas.InsightsReport)r'   ls_schemas.InsightsReport | Noner   rl  rN  rl  r*  rD  r  rD  r+  r  r  r  )
r   rl  r'  r  rN  rl  r7  r  r  zls_schemas.InsightsReportResult)rU  r  rf  r  rA  r  r  z
list[dict])r  r  r  r  r  r  r  zLiteral['openai', 'anthropic'])r  r   r  r  )r   r   r   r   r   	__slots__r  r  r5  staticmethodr2  r_  rd  rj  propertyrm  r]  rw  r}  rR  setterr  r  r  r  r  r  r  r  r  rc  rd  r  r  r-  r:  r=  rL  rs   rS  rj  rh  ry  r$  r%  r'  r&  rf  rg  r  r  r  r  r  r  r  r  r  r  r&  r/  rA  rJ  rV  r9  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  ri   xor_argsro  r  r  r"  r%  r1  r5  r  rA  rF  rK  rN  rV  r[  r^  ri  r  rs  r~  r  r  r  r  r  r  r  r  r  re  r  r  rq  r  r  r  r"  r%  r-  r2  r7  r<  r@  rS  rY  rZ  rp  rj  r{  ra  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r	  r  r  r  r   r*  r0  r3  r7  r=  r@  PromptSortField
updated_atrJ  r6  rU  re  rh  rk  rn  rs  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'   DEFAULT_INSTRUCTIONSr(  r5  r?  rC  r"  r#  r   rY   rZ   rV   r  r    s0   8/Ib ##!! "&^> "&(,<@!%.2#'7;EIFJGK). -159@D-19=.2'+15&*.2,0HL%*48?^>^> 	^>
 &^> :^> ^> ,^> !^> 5^> C^> D^> E^> #'^>#
^>$ +%^>& $3'^>( >)^>* ++^>, 7-^>. ,/^>0 %1^>2  /3^>4 $5^>6 ,7^>8 *9^>: !F;^>< #=^>> 2?^>@ 
A^>@$  
	4  $(AAA 	A
 A !A 
A AFX3 ( ( B BF
   ^^; ; " " @ @ $ $ ^^H H  @. -1"#<@=AMQj
 Aj
 	j
 *j
  j
 :j
 ;j
 Kj
 j
 j
 
j
Z 6:!!$2!	!H  $17'0'0 	'0
 /'0 '0 
'0` &*3=3F3F3I3I:
:
 :
 "	:

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

 :6
 6
 6
 (6
 6
 &6
 6
 
"6
v CG<@"&&*26# $&*%)"&+/26 $/3*.#%@ @@ :	@
  @ $@ 0@ @ @ $@ #@  @ )@ 0@ @  -!@" (#@$ %@& '@( 
")@J )-&*# $26z &z $	z
 z z z 0z 
z~ '+#'(,"&-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h #%)#'(,04/U/U 	/U
 #/U !/U &/U ./U 
"/Ub( 56 %)&*#'
 "'
 $	'

 '
 
('
 7'
T AE0=	. )-&*	p
 &p
 $	p

 
p
h 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#'G
G
 #	G

 'G
 0G
 1G
 JG
 !G
 
G
X '+(,	 $ &	
 
. 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=>[
 $[
 &	[

 F[
 '+[
 ;[
 [
 
<[
 7[
z 
D(T 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{ ({ { { { !{ { "{ { 
&{B ,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(,2 6:2
2
 &2 .2 &2 32 
-2r 15  %*2* -*
 .*
* * 
'*^ %)	H 04:>&*(,$(04 ))--+/)-?C"$(,7;/3 $ $(,263H "H 	H -H 8H $H &H "H .H
H )H  '!H" =#H$  %H& &'H( $5)H* -+H, -H. /H0 &1H2 03H4 5H6 
7H\ 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( 169B9B 3	9B
  .9B 
)9B| 15'+#- .- %	-
 - - 
3-f @D042B2B =	2B
  .2B 
)2Bh6< .2"'+#( +( 	(
 %( ( 
.(\ &*&*-1MQ,
 ,
 #	,

 $,
 +,
 K,
 
/,
\H, #%)-1MQ&6&6 	&6
 #&6 +&6 K&6 
&6P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>	>*  %(  58  @U  	  D!$,0	.
.
)
I
J $(&+1;1K1K1V1V17#*A *A 	*A
 "*A $*A /*A /*A *A 
(*AX8 &* $(,3<3< #	3<
 3< &3< 3< 
3<t -1*.%)FNFN FN
 *FN (FN #FN 
FNX &* $(,$(&*88 #	8
 8 &8 "8 $8 
8t$( GL.!$.5C.	.$ ).

 &
 
!	
@ ). /4>> &	>
 > )-> 
!>H  $#77 	7
 7 7 
17z &+)-!& /4@
@
 #	@

 '@
 @
 @
 )-@
 
@
L !%"*$(%) $(,15,0KK 	K
  K "K #K K &K /K *K 
Kb "&	<< 	<
 
!<. (,%) $(,$(

 5	

 %
 #
 
 &
 "
 

6 "&	<< 	<
 
!< (,%) $(,$(

 5	

 %
 #
 
 &
 "
 

.//2
2 $(&+#
 
 	

 "
 $
 
 
(
, $(&+#
 
 	

 "
 $
 
 
(
& -
  
,=J=J -=J
 =J %=J #=J =J &=J "=J 
=J~
A,A 	A
 A "A $A A 
(A: -
 #  &  
6SS S
 #S S &S "S 
S.# #( 
 "&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5j  &*37-1!9 #9 1	9
 +9 9 
)9 9~ !%"&HH 	H
  H 
HZ &*(,7;#G ##G &	#G
 5#G 
(#GJ rZ   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:
    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_openair  r   r  _get_request_payloadr   ri   r   )ry  model_kwargsr  rF  r  r  s         rV   convert_prompt_to_openai_formatr  )  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)a;  Convert a prompt to Anthropic format.

Requires the `langchain_anthropic` package to be installed.

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

Returns:
    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-20240307r  Nr  )r  r  r  )r  z&Error converting to Anthropic format: rY   )langchain_anthropicr  r   r  r  r   ri   r   )ry  r  r  r  r  r  rG  r  s           rV   "convert_prompt_to_anthropic_formatr  *  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  rS  r  s     rV   r   _FailedAttachmentReader.__init__@*  s    rZ   c                ^    [         R                  " SU R                   35      U R                  e)NzFailed to download attachment: )ri   r   r  )r  r  s     rV   r  _FailedAttachmentReader.readD*  s*    %%-dkk];
{{	rZ   )r  )rS  r   )r  )r  rU  r  r  )	r   r   r   r   r   r  r  r   r  r  s   @rV   r  r  =*  s    R rZ   r  rh  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  rY   )rc  
startswithr  r  r  r.  r  r  contentr   rQ   rR   r  rB   removeprefix)
r  rF  r"  attachments_dictrD  rl  r,  r  r  r  s
             rV   rG  rG  J*  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)rK  r   rQ   r   r  )r  r	  s     rV   rw  rw  h*  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$ )Nr  r  z/platform/datasets/r  z/v1/platform/datasets/re  r,  )r"  r  s     rV   r  r  r*  s:    ~~c##E**$ZL	::'
|9==rZ   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.r  r  z
/platform/z/v1/platform/r  )r"  r  s     rV   r+  r+  y*  s6    ~~c##E**D6""tf%%rZ   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httpr  r  zBapi_url must start with 'http://' or 'https://'. Received api_url=r  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   rY   )r   ps     rV   r   !_construct_url.<locals>.<genexpr>*  s     1eq11es   
	)r  r  r   re  r  lstriprm   )r"  r  r  	api_partsr&  r  s         rV   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1rZ   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.r  r  r   zUnsupported model type)r  r  r   r   )r  r  s     rV   r  r  *  sM    ul##\::			zz|z44011rZ   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   )ChatPromptTemplater   r   rZ  rK   r   r\   ls_structured_output_formatry  rY   )r   r  r   r   langchain_core.runnablesr   r   r   r   r   r  r  r  r	  ry  rc  )objr  r   r   r   chain_to_pushr  bound_modelr  r  output_formatstructured_kwargsr8  r9  s                 rV   r^  r^  *  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c                   0 U En [        X$U/5      nU(       a  [        U S 5      n Ub	  X[        '   OU(       d  [        X5      n Ub  X S'   Ub  X0S'   Ub  X@S'   Ub  XPS'   U $ )NzX-Service-Keyru  AuthorizationCookie)r   _apply_optional_api_keyrv  )r  rR  rY  rZ  r[  r\  r  has_non_api_keys           rV   r  r  *  s     kG;v>?O)'48$	)'D#. !* #0 "NrZ   c                    U(       a
  X[         '   U $ U R                  [         S 5        U R                  [         R                  5       S 5        U $ r   )rv  r  upper)r  rR  s     rV   r  r  *  s@     $	 N 	It$IOO%t,NrZ   )rS   r  r  r  rf  )rs   rX  ra   rY  r  rb  ra  )
r   zdict | listr   rD  r   rD  r   rD  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#  rD  r$  r  r  ztuple[str, str])r-  r  r  r  )r  r    )rL  zrequests.Sessionr  r  )r"  r  rR  r  rs   rb  r  r  )rX  r  r   )r\  rV  r  zfloat | None)rf  rW  r  r  )rl  rh  r  r  r  rz  )rl  Optional[Union[str, uuid.UUID]]r  rz  )rl  r  rp  r  r  ry  )rl  r  rp  r  )ry  r   r  r{  r  r   )r  r   rF  r  r"  r  r  zdict[str, AttachmentInfo])r  zlist[io.BufferedReader]r  r  )r"  r  r  rh  r  r  )r"  r  r  r  r  r  )r"  r  r  r  r  r  )r  r  r  rc  )r  r   r  r   )r  zMapping[str, str]rR  r  rY  r  rZ  r  r[  r  r\  r  r  r  r  r  )r  r  rR  r  r  r  )r   
__future__r   r	  rC  r  r  r$  r   r   r(  r  rB  importlib.metadatar  r   rO  loggingr  r  r  rN   r  typingr  ro   r  collections.abcr   r   r   r   r   r	   r
   inspectr   pathlibr   r  r   r   r   r   r   r   r   r   r   r   r   r   urllibr   r  r   r  pydanticr   r   r  requests_toolbeltr   r  typing_extensionsr   r   urllib3.poolmanagerr   urllib3.utilr    rF   r!   r1  r"   r  r#   ri   langsmith._internalr$   r  r%   r&   r  #langsmith._internal._beta_decoratorr'   &langsmith._internal._compressed_tracesr(   langsmith._internal._constantsr)   r*   r+   r,   r-   langsmith._internal._hubr.   r/   r0   r1   r2   langsmith._internal._multipartr3   r4   r5   langsmith._internal._operationsr6   r7   r8   r9   r:   r;   r<   r=   langsmith._internal._serder>   r  langsmith._internal._uuidr?   langsmith.prompt_cacher@   rA   langsmith.schemasrB   rC   	getLoggerr   rQ   rP   rM   rO   r  rL   rb  	frozensetrI   r  rW   r[   r  rH  rI  rz   r   zoneinfor   r   opentelemetry.sdk.tracer   r  r  r  r   r   r}   r   r   r   rQ  r   rJ  r  r   r   r   r  r   r   r   r   r   r   r   r   r  rv  r   rz  rC  
parametersr  r  r   r   r   r   r   r  r(  r.  r  r  rh  rd  rI  rM  rS  rY  r_  rj  r  rn  rv  HTTPAdapterrx  r  r  r  r  r  r  rG  rw  r  r+  r  r  r^  r  r  rY   rZ   rV   <module>r	     s  
 #          	    	         P P (   %   )    2 2 '   # + ' ' : C   
	 	 	 A + F =			8	$!  " nn& 34'0+1F'G n G$+   "(  $(B'B !B 	BJ
$(!.6 1!5H ? 
	 	 	 
		8	$##$<=	 	  	,	'0B0M0MM S #&5  ( 1% %4 ,-rTV!!%(!9<!NQ!	!H



?C

	

FF F #	F
 F 	FX 	'  	
 :  		3
H

 Q3  3> !,	 	
 
:  .2*.$   J  J CG*<@ 
 QV  Q  %-99 %P"i "c[ c[Pw .2$Q$Q*$Q 
$QR .2%T%T*%T 
%TP
bjj 
 CG
$'2?<>&2D /4 2.b  	
  !  $ :&3MP  (( ((  .. .."  
s6   P& P= -Q &P:9P:=QQ
Q"!Q"