
    f3fi                       d Z ddlmZ ddlZddlZddlZddlZddlZddlm	Z	m
Z
mZmZ ddlmZmZmZmZmZ ddlZddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ eej@                  e!f   Z" G d d      Z#ddZ$y)zThe Async LangSmith Client.    )annotationsN)AsyncGeneratorAsyncIteratorMappingSequence)AnyLiteralOptionalUnioncast)client)schemas)utils)_beta_decorator)
AsyncCachec                     e Zd ZdZdZ	 	 	 	 	 	 db	 	 	 	 	 	 	 	 	 	 	 dcdZdddZd Zd Ze	d	        Z
e	ded
       Z	 	 	 	 	 	 	 	 dfdZ	 dg	 	 	 	 	 dhdZdddd	 	 	 	 	 	 	 	 	 didZddd	 	 	 	 	 	 	 	 	 	 	 	 	 djdZ	 	 	 	 	 	 dkdZdldZddddddddddddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dmdZdd	 	 	 	 	 dndZdodZdpdZ	 	 	 	 	 	 dqdZ	 	 dr	 	 	 	 	 dsdZddd	 	 	 	 	 dtdZ	 	 	 	 	 	 dudZ	 	 dr	 	 	 	 	 dvd Zdwd!Z	 	 	 	 dxd"Z	 	 	 dy	 	 	 	 	 	 	 	 	 	 	 dzd#Zd{d$Zddd%	 	 	 	 	 	 	 d|d&Z	 	 	 dy	 	 	 	 	 	 	 	 	 	 	 	 	 d}d'Z 	 dgddddd(	 	 	 	 	 	 	 	 	 	 	 	 	 d~d)Z!dddd*	 	 	 	 	 	 	 	 	 	 	 dd+Z"	 	 	 	 dd,Z#ddddd-	 	 	 	 	 	 	 	 	 	 	 dd.Z$dd/Z%ddddd0	 	 	 	 	 	 	 	 	 dd1Z&ddd2	 	 	 	 	 	 	 dd3Z'	 	 	 	 dd4Z(dd5	 	 	 	 	 	 	 dd6Z)dd7Z*	 	 	 	 	 	 dd8Z+	 	 	 	 	 	 dd9Z,	 	 	 	 	 	 dd:Z-e.j^                  d;d<	 	 	 	 	 	 	 dd=       Z0e.j^                  	 	 	 	 	 	 dd>       Z1e.j^                  dd?	 	 	 	 	 	 	 	 	 	 	 dd@       Z2ddAZ3ddBZ4	 	 	 	 	 	 ddCZ5	 d	 	 	 	 	 	 	 ddEZ6	 	 	 	 	 	 	 	 ddFZ7	 	 	 	 	 	 ddGZ8ddHZ9ddIZ:ddJZ;ddKZ<dLdDdde=j|                  j~                  dMddN	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddOZ@ddPZAdddddQ	 	 	 	 	 	 	 	 	 	 	 ddRZBdddS	 	 	 	 	 	 	 	 	 ddTZCddddddU	 	 	 	 	 	 	 	 	 	 	 	 	 ddVZDddWZE	 d	 	 	 	 	 ddXZF	 d	 	 	 	 	 ddYZGdddZ	 	 	 	 	 	 	 dd[ZHddDdd\	 	 	 	 	 	 	 	 	 dd]ZIddddd^	 	 	 	 	 	 	 	 	 	 	 dd_ZJdd;dddddd`	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddaZKy)AsyncClientz4Async Client for interacting with the LangSmith API.)_retry_config_client_web_url	_settings_cacheNFc                0   |xs ddi| _         ddi}t        j                  |      }t        j                  |      }|r||t        j
                  <   t	        j                  ||       t        |t              r
|dz  dddf}n3t        |t              r!t        |D 	cg c]  }	|	|	dz  nd c}	      }nd}t        j                  |||      | _        || _        d| _        |d	u rt               | _        yt        |t              r|| _        yd| _        yc c}	w )
a=  Initialize the async client.

        Args:
            api_url: URL for the LangSmith API.
            api_key: API key for the LangSmith API.
            timeout_ms: Timeout for requests in milliseconds.
            retry_config: Retry configuration.
            web_url: URL for the LangSmith web app.
            cache: Configuration for caching.

                Can be:

                - `True`: Enable caching with default settings
                - `AsyncCache` instance: Use custom cache configuration
                - `False`: Disable caching (default)
        max_retries   zContent-Typeapplication/jsoni  N
   )base_urlheaderstimeoutT)r   ls_utilsget_api_keyget_api_url	ls_client	X_API_KEY_validate_api_key_if_hosted
isinstanceinttuplehttpxr   r   r   r   r   r   )
selfapi_urlapi_key
timeout_msretry_configweb_urlcache_headerstimeout_ts
             T/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langsmith/async_client.py__init__zAsyncClient.__init__#   s   : *?mQ-?.
 &&w/&&w/,3HY(()--gw?j#&-7$->dD,QH
E*:Va!-a$hTAVWHH((h
  AE D=0:DKz*DKDK Ws   Dc                n   K   | j                   "| j                   j                          d{    | S 7 w)zEnter the async client.N)r   startr+   s    r5   
__aenter__zAsyncClient.__aenter__^   s0     ;;"++##%%% &s   *535c                @   K   | j                          d{    y7 w)zExit the async client.N)aclose)r+   exc_typeexc_valexc_tbs       r5   	__aexit__zAsyncClient.__aexit__d   s     kkms   c                   K   | j                   "| j                   j                          d{    | j                  j                          d{    y7 '7 w)zClose the async client.N)r   stopr   r<   r9   s    r5   r<   zAsyncClient.acloseh   sE     ;;"++""$$$ll!!### %#s!   *AA!AAAAc                @    t        | j                  j                        S N)strr   r   r9   s    r5   _api_urlzAsyncClient._api_urln   s    4<<(())    c                V    t        j                  | j                  | j                        S )zThe web host url.)r!   get_host_urlr   rF   r9   s    r5   	_host_urlzAsyncClient._host_urlr   s     $$T]]DMMBBrG   c                F  K   t        t        | j                  j                  dd            }d|v r0|d   }|j	                         D ci c]  \  }}|	|| }}}||d<   t        |      D ]A  }		  | j                  j                  ||fi | d{   }
t        j                  |
       |
c S  t        j                  d      c c}}w 7 9# t        j                  $ rW}
j                  dk(  r't        j                  d| d| dt        |             |
j                  d	k(  rt        j                  d
| |       |
j                  dk(  r$t        j                   d| dt        |             |
j                  dk(  r$t        j"                  d| dt        |             |
j                  dk(  r$t        j$                  d| dt        |             |
j                  dk(  r$t        j&                  d| dt        |             t        j(                  d| d| dt        |             d}~wt        j*                  $ rU}|	|dz
  k(  r!t        j,                  dt        |             t/        j0                  d|	z         d{  7   Y d}~-d}~ww xY ww)z(Make an async HTTP request with retries.r   r   paramsNi  zServer error caused failure to  z in LangSmith API. i  z(Client took too long to send request to i  zRate limit exceeded for z. i  zAuthentication failed for i  zResource not found for i  zConflict for z
Failed to    zRequest error:    z0Unexpected error connecting to the LangSmith API)r   r(   r   getitemsranger   requestr!   raise_for_status_with_textr*   HTTPStatusErrorstatus_codeLangSmithAPIErrorreprLangSmithRequestTimeoutLangSmithRateLimitErrorLangSmithAuthErrorLangSmithNotFoundErrorLangSmithConflictErrorLangSmithErrorRequestErrorLangSmithConnectionErrorasynciosleep)r+   methodendpointkwargsr   rL   kvfiltered_paramsattemptresponsees               r5   _arequest_with_retriesz"AsyncClient._arequest_with_retriesw   s     3 2 2 6 6}a HI vH%F06P1!-q!tPOP.F8[) '	0G&0!5!5!5fh!Q&!QQ33H=	'	0P ((>
 	
W Q
 R (( ''3."449&H: &++/7)5 
 ))S0"::B6(8*U  ))S0"::28*BtAwiH  ))S0"554XJba	J  ))S0"991(2d1gYG  ))S0"99'zDG9=  #11$VHAhZ7J4PQ7)T  %% 0kAo-";;odSTgY<WXXmmAwJ///0sn   AJ!	
CCJ!0!CCC,J!CJ!EH33J	AJJJJ!JJ!c               ,  K   |xs i }|j                  dd      }|j                  dd      |d<   	 ||d<   | j                  d||       d{   }|j                         }|sy|D ]  }| 	 t        |      |d   k  ry|t        |      z  }a7 Dw)zGet a paginated list of items.offsetr   limitd   GETrL   N)rP   rl   jsonlen)r+   pathrL   rn   rj   rQ   items          r5   _aget_paginated_listz AsyncClient._aget_paginated_list   s      2Ha( **Wc2w%F8!88V8TTHMMOE 
5zF7O+c%j F Ts   ABBABPOSTruns)bodyrequest_methoddata_keyc              \  K   |r|j                         ni }	 | j                  ||t        j                  |             d{   }|j	                         }|sy|j                  |      sy||   D ]  }| 	 |j                  d      }	|	sy|	j                  d      sy|	d   |d<   7 gw)z%Get a cursor paginated list of items.contentNcursorsnextcursor)copyrl   r$   _dumps_jsonrs   rP   )
r+   ru   rz   r{   r|   params_rj   response_bodyrunr   s
             r5   _aget_cursor_paginated_listz'AsyncClient._aget_cursor_paginated_list   s      "&$))+2!88!--g6 9  H
 %MMOM  $$X.$X. 	#''	2G;;v& 'GH% s   A B,B*A(B,)project_namerevision_idc                  K   ||j                  d      xs t        j                         |||xs t        j                         |d|}| j                  ddt        j                  |             d{    y7 w)zCreate a run.id)namer   inputsrun_typesession_namer   rx   /runsr~   N)rP   uuiduuid4r!   get_tracer_projectrl   r$   r   )r+   r   r   r   r   r   re   
run_creates           r5   
create_runzAsyncClient.create_run   s~      **T"2djjl (IH,G,G,I&
 

 ))GY%:%::%F * 
 	
 	
s   A1A;3A94A;c                   K   i |dt        j                  |      i}| j                  ddt        j                  |       t        j                  |             d{    y7 w)zUpdate a run.r   PATCH/runs/r~   N)r$   _as_uuidrl   r   )r+   run_idre   datas       r5   
update_runzAsyncClient.update_run   sh      <&;$	 2 26 :;))Y''/01))$/ * 
 	
 	
s   AA&A$A&c                   K   | j                  ddt        j                  |              d{   }t        j                  di |j                         S 7 'w)zRead a run.rq   r   N )rl   r$   r   
ls_schemasRunrs   )r+   r   rj   s      r5   read_runzAsyncClient.read_run  sS     44Y''/01
 
 ~~000	
   ,AA(A)
project_idr   r   trace_idreference_example_idqueryfiltertrace_filtertree_filteris_rootparent_run_id
start_timeerrorrun_idsselectro   c                K   g }t        |t        j                  t        f      r|j	                  |       n!t        |t
              r|j                  |       |tt        |t              r|g}t        j                  |D cg c]  }| j                  |       c}  d{   }|j                  |D cg c]  }|j                   c}       |rd|v rt        j                  dt               |r|nd||r|gnd||||	|
||r|j                         nd|||||d|}|r/|D cg c]   }t        t        j                   |            " c}|d<   |j#                         D ci c]  \  }}|	|| }}}d}| j%                  d|	      2 3 d{   }t'        j(                  di | |d
z  }|)||k\  s/ yc c}w 7 c c}w c c}w c c}}w 7 D6 yw)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r   child_run_idszOThe child_run_ids field is deprecated and will be removed in following versions)sessionr   reference_exampler   r   r   r   r   
parent_runr   r   r   tracer   ro   r   r   z/runs/query)rz   rN   r   )r'   r   UUIDrE   appendlistextendra   gatherread_projectr   warningswarnDeprecationWarning	isoformatr$   r   rQ   r   r   r   )r+   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ro   re   project_idsr   projectsproject
body_queryid_rf   rg   rz   ixr   s                                r5   	list_runszAsyncClient.list_runs  s    b j499c"23z*
D)z*#,, ,~$^^COP4$###6P H (Cw

CDo/MMa" '2{t *>%&D(&'4>*..0D#&
$ %&

( 8C%14I&&s+,%Jy! ",!1!1!3EAq}1EE99-d9S 	 	#..'3''!GB R5[Q Q  D:% F	Ss   A>G F:G F?!G4GAG#%GG!
G,G1G	GGG G2G8GGGG)share_idc               n  K   t        j                  |d      }t        |      t        |xs t        j                               d}| j                  dd| dt        j                  |             d{   }t        j                  |       |j                         d   }| j                   d	| d
S 7 >w)am  Get a share link for a run asynchronously.

        Args:
            run_id (ID_TYPE): The ID of the run to share.
            share_id: Custom share ID.

                If not provided, a random UUID will be generated.

        Returns:
            The URL of the shared run.

        Raises:
            httpx.HTTPStatusError: If the API request fails.
        r   )r   share_tokenPUTr   /sharer~   Nr   /public//r)r$   r   rE   r   r   rl   r   r!   rT   rs   rJ   )r+   r   r   run_id_r   rj   r   s          r5   	share_runzAsyncClient.share_run  s     " $$VX6'lx74::<8
 44WIV$))$/ 5 
 

 	++H5mmom4..!+b99
s   A2B54B35?B5c                p   K   | j                  t        j                  |d             d{   }|duS 7 w)z)Get share state for a run asynchronously.r   N)read_run_shared_linkr$   r   )r+   r   links      r5   run_is_sharedzAsyncClient.run_is_shared  s7     ..y/A/A&(/STT4 Us   )64	6c                   K   | j                  ddt        j                  |d       d       d{   }t        j                  |       |j                         }|d|vry| j                   d|d    dS 7 Ew)	aN  Retrieve the shared link for a specific run asynchronously.

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

        Returns:
            Optional[str]: The shared link for the run, or None if the link is not
            available.

        Raises:
            httpx.HTTPStatusError: If the API request fails.
        rq   r   r   r   Nr   r   r   )rl   r$   r   r!   rT   rs   rJ   )r+   r   rj   results       r5   r   z AsyncClient.read_run_shared_link  s      44Y''9:&A
 
 	++H5>]&8..!&*?)@CC
s   .A8A6AA8c                   K   d|i|}| j                  ddt        j                  |             d{   }t        j                  di |j                         S 7 'w)zCreate a project.r   rx   	/sessionsr~   Nr   )rl   r$   r   r   TracerSessionrs   )r+   r   re   r   rj   s        r5   create_projectzAsyncClient.create_project  sd      //44K)>)>t)D 5 
 
 '':(--/::
   1AA(Ac                  K   |r1| j                  ddt        j                  |              d{   }n,|r| j                  ddd|i       d{   }nt        d      |j	                         }t        |t              r3|st        j                  d| d	      t        j                  di |d
   S t        j                  di |S 7 7 zw)zRead a project.rq   
/sessions/Nr   r   rr   2Either project_name or project_id must be providedzProject 
 not foundr   r   )rl   r$   r   
ValueErrorrs   r'   r   r!   r\   r   r   )r+   r   r   rj   r   s        r5   r   zAsyncClient.read_project  s      !88I$6$6z$B#CD H !88{FL+A 9  H QRR}}dD!55|nJ7  ++6d1g66''/$//#"   .CC
 CCA9CC)r   r   c                 K   ||t        d      |/| j                  |       d{   }t        |j                        }|st        d      | j	                  ddt        j                  |              d{    y7 W7 w)zDelete a project from LangSmith.

        Args:
            project_name: The name of the project to delete.
            project_id: The ID of the project to delete.
        Nr   r   zProject not foundDELETEr   )r   r   rE   r   rl   r$   r   )r+   r   r   r   s       r5   delete_projectzAsyncClient.delete_project  s      ,"6QRR --<-HHGWZZJ011))++J789
 	
 	
	 I	
s"   'BBAB;B<BBc                   K   d|i|}| j                  ddt        j                  |             d{   }t        j                  di |j                         S 7 'w)zCreate a dataset.r   rx   	/datasetsr~   Nr   )rl   r$   r   r   Datasetrs   )r+   dataset_namere   r   rj   s        r5   create_datasetzAsyncClient.create_dataset-  sd      //44K)>)>t)D 5 
 
 !!4HMMO44
r   c                  K   |r1| j                  ddt        j                  |              d{   }n,|r| j                  ddd|i       d{   }nt        d      |j	                         }t        |t              r3|st        j                  d| d	      t        j                  di |d
   S t        j                  di |S 7 7 zw)zRead a dataset.rq   
/datasets/Nr   r   rr   z2Either dataset_name or dataset_id must be providedzDataset r   r   r   )rl   r$   r   r   rs   r'   r   r!   r\   r   r   )r+   r   
dataset_idrj   r   s        r5   read_datasetzAsyncClient.read_dataset9  s      !88I$6$6z$B#CD H !88{FL+A 9  H QRR}}dD!55|nJ7  %%0Q00!!)D))#r   c                p   K   | j                  ddt        j                  |              d{    y7 w)zDelete a dataset.r   r   N)rl   r$   r   )r+   r   s     r5   delete_datasetzAsyncClient.delete_datasetS  s7     ))++J789
 	
 	
s   ,646c               |   K   | j                  d|      2 3 d{   }t        j                  di | "7 6 yw)zList datasets.r   rr   Nr   )rw   r   r   )r+   re   datasets      r5   list_datasetszAsyncClient.list_datasetsZ  sD     
 "66{66R 	0 	0'$$/w//	0Rs   <:8:<:<c                F  K   ||t        d      |&| j                  |       d{   }|j                  }||t        |      d|}| j	                  ddt        j                  |             d{   }t        j                  di |j                         S 7 s7 )w)	zCreate an example.Nz2Either dataset_id or dataset_name must be providedr   )r   outputsr   rx   	/examplesr~   r   )
r   r   r   rE   rl   r$   r   r   Examplers   )	r+   r   r   r   r   re   r   r   rj   s	            r5   create_examplezAsyncClient.create_exampleb  s      ,"6QRR --<-HHG J j/
 	
 44K)>)>t)D 5 
 
 !!4HMMO44 I
s"   'B!BAB!5B6(B!B!c                   K   | j                  ddt        j                  |              d{   }t        j                  di |j                         S 7 'w)zRead an example.rq   z
/examples/Nr   )rl   r$   r   r   r   rs   )r+   
example_idrj   s      r5   read_examplezAsyncClient.read_example|  sT     44Z	 2 2: >?@
 
 !!4HMMO44
r   )r   r   c              ,  K   |j                         }|rt        j                  |      |d<   n+|r)| j                  |       d{   }|j                  |d<   | j                  d|      2 3 d{   }t        j                  di | "7 H7 6 yw)zList examples.r   r   Nr   rr   r   )r   r$   r   r   r   rw   r   r   )r+   r   r   re   rL   r   examples          r5   list_exampleszAsyncClient.list_examples  s       ) 2 2: >F9 --<-HHG '

F9!66{66R 	0 	0'$$/w//	 I	0Rs6   ABB&B,B0B1B4BBBc                   K   t        j                  |d      ||||d|}| j                  ddt        j                  |             d{   }t	        j
                  di |j                         S 7 'w)	a  Create feedback for a run.

        Args:
            run_id: The ID of the run to provide feedback for.

                Can be `None` for project-level feedback.
            key: The name of the metric or aspect this feedback is about.
            score: The score to rate this run on the metric or aspect.
            value: The display value or non-numeric value for this feedback.
            comment: A comment about this feedback.
            **kwargs: Additional keyword arguments to include in the feedback data.

        Returns:
            The created feedback object.

        Raises:
            httpx.HTTPStatusError: If the API request fails.
        T)accept_null)r   keyscorevaluecommentrx   	/feedbackr~   Nr   )r$   _ensure_uuidrl   r   r   Feedbackrs   )	r+   r   r  r  r  r  re   r   rj   s	            r5   create_feedbackzAsyncClient.create_feedback  s     8  ,,VF
 
 44K)>)>t)D 5 
 
 ""5X]]_55
s   A
A6A4(A6)r  
correctionr  metadatac               T  K   t        j                  || j                  d      \  }}|| j                  k7  rt        d|       | j	                  ddt        j
                  |       t        j                  |||||d             d{   }	t        j                  |	       y7 w)	a!  Create feedback from a presigned token or URL.

        Args:
            token_or_url: The token or URL from which to create feedback.
            score: The score of the feedback.
            value: The value of the feedback.
            correction: The correction of the feedback.
            comment: The comment of the feedback.
            metadata: Additional metadata for the feedback.

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

        Returns:
            This method does not return anything.
        rN   )	num_partszInvalid source API URL. rx   z/feedback/tokens/)r  r  r
  r  r  r~   N)	r$   _parse_token_or_urlrF   r   rl   r   r   r!   rT   )
r+   token_or_urlr  r  r
  r  r  source_api_url
token_uuidrj   s
             r5   create_feedback_from_tokenz&AsyncClient.create_feedback_from_token  s     4 &/%B%B$--1&
"
 T]]*77GHII44	 2 2: >?@))""",& (	 5 
 
 	++H5
s   B	B(B&B()
expirationfeedback_configfeedback_idc                 K   ||||xs t        t        j                               d}|t        j                  ddd      |d<   nt        |t        j                        r|j                         |d<   nut        |t        j                        rCt        j                  |j                  |j                  dz  |j                  dz  d	z        |d<   nt        d
t        |       d      | j                  ddt        j                  |             d{   }t        j                   di |j#                         S 7 'w)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 to provide feedback for.
            feedback_key: The name of the metric or aspect this feedback is about.
            expiration: The expiration time of the pre-signed URL.

                Either a datetime or a timedelta offset from now.

                Default to 3 hours.
            feedback_config: `FeedbackConfig` or `None`.

                If creating a feedback_key for the first time, this defines how the
                metric should be interpreted, such as a continuous score (w/ optional
                bounds), or distribution over categorical values.
            feedback_id: The ID of the feedback to create.

                If not provided, a new feedback will be created.

        Returns:
            The pre-signed URL for uploading feedback data.
        )r   feedback_keyr  r   Nr   r   )dayshoursminutes
expires_in
expires_ati  <   zInvalid expiration type: z3. Expected datetime.datetime or datetime.timedelta.rx   z/feedback/tokensr~   r   )rE   r   r   r   TimeDeltaInputr'   datetimer   	timedeltar  secondsr   typerl   r$   r   FeedbackIngestTokenrs   )r+   r   r  r  r  r  rz   rj   s           r5   create_presigned_feedback_tokenz+AsyncClient.create_presigned_feedback_token  s=    H (.2TZZ\!2	 
 !+!:!:"D
 
H$5$56!+!5!5!7D
H$6$67!+!:!:__ ((D0#++d2r9"D +D,<+= >D D 
 44))$/ 5 
 

 --@@@
s   DD>D<(D>c                   K   | j                  ddt        j                  |              d{   }t        j                  di |j                         S 7 'w)zRead feedback.rq   
/feedback/Nr   )rl   r$   r   r   r  rs   r+   r  rj   s      r5   read_feedbackzAsyncClient.read_feedback0  sV      44Z	 2 2; ?@A
 
 ""5X]]_55
r   )r   r  feedback_source_typero   c              J  K   |r,|D cg c]   }t        t        j                  |            " c}nd|t        |d      ndd|}|||d<   |||d<   d}| j	                  d|      2 3 d{   }	t        j                  d
i |	 |d	z  }|)||k\  s/ yc c}w 7 16 yw)zList feedback.Nrp   )r   ro   r  sourcer   r  rr   rN   r   )rE   r$   r   minrw   r   r  )
r+   r   r  r)  ro   re   r   rL   r   feedbacks
             r5   list_feedbackzAsyncClient.list_feedback9  s      FMA#Y'',-ARV(-(9S_s	

 
 #(F5M+3F8"77F7S 	 	(%%111!GB R5[ B	Ss?   B#%B;B#)B!-B.B!1 B#B#B#B!!B#c                   K   | j                  ddt        j                  |d              d{   }t        j                  |       y7 w)z~Delete a feedback by ID.

        Args:
            feedback_id (Union[UUID, str]): The ID of the feedback to delete.
        r   r&  r  Nrl   r$   r   r!   rT   r'  s      r5   delete_feedbackzAsyncClient.delete_feedbackU  sL      44
9#5#5k=#Q"RS
 
 	++H5
s   -AA
A)	queue_idsr   name_containsro   c          
    D  K   |6t        |      D cg c]  \  }}t        j                  |d| d      ! c}}nd|||t        |d      ndd}d}| j	                  d|      2 3 d{   }	t        j                  d
i |	 |d	z  }|)||k\  s/ yc c}}w 7 26 yw)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: The name of the queue to filter by.
            name_contains: The substring that the queue name should contain.
            limit: The maximum number of queues to return.

        Yields:
            The annotation queues.
        Nz
queue_ids[]rp   )idsr   r3  ro   r   /annotation-queuesrr   rN   r   )	enumerater$   r   r,  rw   r   AnnotationQueue)
r+   r2  r   r3  ro   ir   rL   r   r-  s
             r5   list_annotation_queuesz"AsyncClient.list_annotation_queuesb  s     4 ( #,I"63 &&sj1,=>
 *(-(9S_s
 "77  8 
 	 	( ,,8x88!GB R5[%	 
s?   B $B.B %B)B*B- B B B BB )descriptionqueue_idc          
     h  K   |||t        |      nt        t        j                               d}| j                  dd|j	                         D ci c]  \  }}|	|| c}}       d{   }t        j                  |       t        j                  di |j                         S c c}}w 7 Bw)aT  Create an annotation queue on the LangSmith API.

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

        Returns:
            The created annotation queue object.
        N)r   r<  r   rx   r7  rs   r   )
rE   r   r   rl   rQ   r!   rT   r   r9  rs   )r+   r   r<  r=  rz   rf   rg   rj   s           r5   create_annotation_queuez#AsyncClient.create_annotation_queue  s     $ &#+#7#h-S=N

 44 #'::<A41a1=!Q$A 5 
 

 	++H5)) 
mmo
 	
 B
s%   AB2
B*B*!B2-B0.AB2c                `   K   | j                  |g      j                          d{   S 7 w)zRead an annotation queue with the specified `queue_id`.

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

        Returns:
            The annotation queue object.
        )r2  N)r;  	__anext__)r+   r=  s     r5   read_annotation_queuez!AsyncClient.read_annotation_queue  s-      00H:0FPPRRRRs   %.,.)r<  c                  K   | j                  ddt        j                  |d       ||d       d{   }t        j                  |       y7 w)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: The new name for the annotation queue.
            description: The new description for the annotation queue.
        r   /annotation-queues/r=  )r   r<  r?  Nr0  )r+   r=  r   r<  rj   s        r5   update_annotation_queuez#AsyncClient.update_annotation_queue  s]      44!)"4"4Xz"J!KL* 5 
 
 	++H5
s   2AAAc                   K   | j                  ddt        j                  |d       ddi| j                  j                         d{   }t        j                  |       y7 w)zDelete an annotation queue with the specified `queue_id`.

        Args:
            queue_id (Union[UUID, str]): The ID of the annotation queue to delete.
        r   rE  r=  Acceptr   )r   N)rl   r$   r   r   r   r!   rT   )r+   r=  rj   s      r5   delete_annotation_queuez#AsyncClient.delete_annotation_queue  sj      44!)"4"4Xz"J!KL1JT\\5I5IJ 5 
 

 	++H5
   AA&	A$
A&c               (  K   | j                  ddt        j                  |d       dt        |      D cg c](  \  }}t	        t        j                  |d| d            * c}}       d{   }t        j                  |       yc c}}w 7  w)	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.
        rx   rE  r=  r   zrun_ids[r5  r?  N)rl   r$   r   r8  rE   r!   rT   )r+   r=  r   r:  r   rj   s         r5   add_runs_to_annotation_queuez(AsyncClient.add_runs_to_annotation_queue  s      44!)"4"4Xz"J!K5Q (0As I&&shqcO<= 5 
 
 	++H5
s   4B-B
#B/B0!Bc          
        K   | j                  ddt        j                  |d       dt        j                  |d              d{   }t        j                  |       y7 w)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.
        r   rE  r=  r   r   Nr0  )r+   r=  r   rj   s       r5    delete_run_from_annotation_queuez,AsyncClient.delete_run_from_annotation_queue  sd      44!)"4"4Xz"J!K6R[RdRdekmuRvQwx
 
 	++H5	
s   AA#A!A#c                  K   dt        j                  |d       d}| j                  d| d|        d{   }t        j                  |       t        j                  di |j                         S 7 <w)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: The index of the run to retrieve.

        Returns:
            The run at the specified index.

        Raises:
            LangSmithNotFoundError: If the run is not found at the given index.
            LangSmithError: For other API-related errors.
        rE  r=  z/runrq   /Nr   )r$   r   rl   r!   rT   r   RunWithAnnotationQueueInfors   )r+   r=  indexr   rj   s        r5   get_run_from_annotation_queuez)AsyncClient.get_run_from_annotation_queue  ss       )););Hj)Q(RRVW44Uxj%<QRR++H544Gx}}GG Ss   5A6A4=A6latest)tagc                  K   t        j                  |d      }| j                  dd| dt        j                  d|i|             d{   }t	        j
                  |       y7 w)a"  Enable dataset indexing. Examples are indexed by their inputs.

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

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

                If `'latest'` then any updates to the dataset (additions, updates,
                deletions of examples) will be reflected in the index.

        Raises:
            requests.HTTPError: If the request fails.
        r   rx   r   z/indexrU  r~   Nr$   r   rl   r   r!   rT   )r+   r   rU  re   resps        r5   index_datasetzAsyncClient.index_dataset  sp     . ''
LA
00F+))5#*@*@A 1 
 

 	++D1
s   A	A(A&A(c                  K   t        j                  |d      }| j                  dd| dt        j                  i |             d{   }t	        j
                  |       y7 w)a(  Sync dataset index.

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

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

        Raises:
            requests.HTTPError: If the request fails.
        r   rx   r   z/index/syncr~   NrW  )r+   r   re   rX  s       r5   sync_indexed_datasetz AsyncClient.sync_indexed_dataset3  sj     $ ''
LA
00K0))*V*5 1 
 

 	++D1
rJ  )r   c         	     n  K   t        j                  |d      }||d|}|r||d<   | j                  dd| dt        j                  |             d{   }t	        j
                  |       g }|j                         d	   D ]*  }	|j                  t        j                  d
i |	d|i       , |S 7 ]w)a0  Retrieve the dataset examples whose inputs best match the current inputs.

        !!! note

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

        Args:
            inputs: The inputs to use as a search query.

                Must match the dataset input schema.

                Must be JSON serializable.
            limit: The maximum number of examples to return.
            dataset_id (Union[UUID, str]): The ID of the dataset to search over.
            filter: A filter string to apply to the search results.

                Uses the same syntax as the `filter` parameter in `list_runs()`.

                Only a subset of operations are supported.
            kwargs: Additional keyword args to pass as part of request body.

        Returns:
            List of `ExampleSearch` objects.

        Examples:
            ```python
            from langsmith import Client

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

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

        r   )r   ro   r   rx   r   z/searchr~   Nexamplesr   )
r$   r   rl   r   r!   rT   rs   r   r   ExampleSearch)
r+   r   ro   r   r   re   reqrX  r]  exs
             r5   similar_exampleszAsyncClient.similar_examplesM  s     d ''
LA

 

 "CM00G,))#. 1 
 

 	++D1))+j) 	SBOOJ44QrQjQR	S
s   AB5B3AB5c                   K   | j                   W| j                  dd       d{   }t        j                  |       t	        j
                  di |j                         | _         | j                   S 7 Mw)zzGet the settings for the current tenant.

        Returns:
            dict: The settings for the current tenant.
        Nrq   z	/settingsr   )r   rl   r!   rT   r   LangSmithSettingsrs   )r+   rj   s     r5   _get_settingszAsyncClient._get_settings  s`      >>!!88LLH//9'99LHMMOLDN~~	 Ms   "A4A2AA4c                j   K   | j                          d{   }|dk(  xs |j                  |k(  S 7 w)zCheck if the current workspace has the same handle as owner.

        Args:
            owner: The owner to check against.

        Returns:
            bool: `True` if the current tenant is the owner, `False` otherwise.
        N-)rd  tenant_handle)r+   ownersettingss      r5   _current_tenant_is_ownerz$AsyncClient._current_tenant_is_owner  s8      ++--|>x55>> .s   313c                   K   | j                          d {   }t        j                  d| d|j                   d|       S 7 ,w)NzCannot z% for another tenant.
Current tenant: z,
Requested tenant: )rd  r!   LangSmithUserErrorrg  )r+   actionrh  ri  s       r5   _owner_conflict_errorz!AsyncClient._owner_conflict_error  sX      ++--**fX '556 7!!&)
 	
 .s   AA-Ar   c                   K   | j                  dd| d||d       d{   }|j                         d   }|r|d   d	   S dS 7 #w)
aL  Get the latest commit hash for a prompt.

        Args:
            prompt_owner_and_name: The owner and name of the prompt.
            limit: The maximum number of commits to fetch.
            offset: The number of commits to skip.

        Returns:
            The latest commit hash, or `None` if no commits are found.
        rq   	/commits/rP  )ro   rn   rr   Ncommitsr   commit_hash)rl   rs   )r+   prompt_owner_and_namero   rn   rj   rq  s         r5   _get_latest_commit_hashz#AsyncClient._get_latest_commit_hash  sh      44-.a0"f5 5 
 

 --/),,3wqz-(==
s   AA$Ac                    K   t        |t              r|gn|}d fd}t        j                  |D cg c]
  } ||       c}  d{    yc c}w 7 
w)a^  Update tags for a prompt commit.

        Args:
            prompt_owner_and_name: The owner and name of the prompt in the format 'owner/repo'.
            commit_id: The commit ID to tag.
            tags: A single tag or list of tags to apply to the commit.

        Raises:
            requests.exceptions.HTTPError: If the request fails.
        c                   K   | d}j                  dd d|       d {   }t        j                  |       y 7 w)N)tag_name	commit_idrx   /repos/z/tagsr?  )rl   r!   rT   )rU  payloadrj   rx  rs  r+   s      r5   
create_tagz3AsyncClient._create_commit_tags.<locals>.create_tag  sW     &G "88'"7!8>W 9  H //9s   !A?AN)rU  rE   )r'   rE   ra   r   )r+   rs  rx  tagstag_listr{  rU  s   ```    r5   _create_commit_tagszAsyncClient._create_commit_tags  sI      (c2D6	: nn(C3z#CDDDCDs   1AAAAAc                   K   t        j                  |      \  }}}| j                  dd| d| d|i       d{   }|j                          |j	                         S 7 $w)a  Like or unlike a prompt.

        Args:
            prompt_identifier: The identifier of the prompt.
            like: 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.
        rx   z/likes/rP  liker?  N)r!   parse_prompt_identifierrl   raise_for_statusrs   )r+   prompt_identifierr  rh  prompt_name_rj   s          r5   _like_or_unlike_promptz"AsyncClient._like_or_unlike_prompt  sq       !) @ @AR S{A44geWAk]364. 5 
 
 	!!#}}	
s   9A"A %A"c           	       K   t        j                  |      \  }}}| j                  |      s| j                   d| d| d|dd  S | j	                          d{   }| j                   d| d|dd  d|j
                   S 7 (w)zGet a URL for a prompt.

        Args:
            prompt_identifier: The identifier of the prompt.

        Returns:
            The URL for the prompt.

        z/hub/rP  :N   z	/prompts/z?organizationId=)r!   r  rj  rJ   rd  r   )r+   r  rh  r  rr  ri  s         r5   _get_prompt_urlzAsyncClient._get_prompt_url  s      +3*J*J+
'{K ,,U3nn%U5';-qRa@QRR++--~~i}Ak"1o5Fx{{m-	
 .s   ABB)Bc                L   K   | j                  |       d{   }|rdS dS 7 
w)zCheck if a prompt exists.

        Args:
            prompt_identifier: The identifier of the prompt.

        Returns:
            `True` if the prompt exists, `False` otherwise.
        NTF)
get_prompt)r+   r  prompts      r5   _prompt_existszAsyncClient._prompt_exists6  s,      '899t(5( :s   $"$c                D   K   | j                  |d       d{   S 7 w)zLike a prompt.

        Args:
            prompt_identifier: The identifier of the prompt.

        Returns:
            A dictionary with the key `'likes'` and the count of likes as the value.
        Tr  Nr  r+   r  s     r5   like_promptzAsyncClient.like_promptB  s%      001B0NNNN     c                D   K   | j                  |d       d{   S 7 w)zUnlike a prompt.

        Args:
            prompt_identifier: The identifier of the prompt.

        Returns:
            A dictionary with the key `'likes'` and the count of likes as the value.
        Fr  Nr  r  s     r5   unlike_promptzAsyncClient.unlike_promptM  s%      001B0OOOOr  rp   desc)ro   rn   	is_publicis_archived
sort_fieldsort_directionr   c          	        K   |||rdn|dnd|rdndt        |t        j                        r|j                  n||||rdndd}| j	                  ddt        |             d{   }	t        j                  di |	j                         S 7 'w)	aF  List prompts with pagination.

        Args:
            limit: The maximum number of prompts to return.
            offset: The number of prompts to skip.
            is_public: Filter prompts by if they are public.
            is_archived: Filter prompts by if they are archived.
            sort_field (PromptSortField): The field to sort by.

                Defaults to `'updated_at'`.
            sort_direction: The order to sort by.
            query: Filter prompts by a search query.

        Returns:
            A response object containing the list of prompts.
        trueNfalse)ro   rn   r  r  r  r  r   match_prefixrq   ry  rr   r   )r'   r   PromptSortFieldr  rl   _exclude_noneListPromptsResponsers   )
r+   ro   rn   r  r  r  r  r   rL   rj   s
             r5   list_promptszAsyncClient.list_promptsX  s     8 #I4It%06g j**D*DE   ,&+F
" 449]6%: 5 
 
 --@@@
s   A"B$B%(Bc                   K   t        j                  |      \  }}}	 | j                  dd| d|        d{   }t        j                  di |j                         d   S 7 *# t         j                  $ r Y yw xY ww)a  Get a specific prompt by its identifier.

        Args:
            prompt_identifier: The identifier of the prompt.

                The identifier should be in the format `'prompt_name'` or
                `'owner/prompt_name'`.

        Returns:
            The prompt object.

        Raises:
            requests.exceptions.HTTPError: If the prompt is not found or
                another error occurs.
        rq   ry  rP  Nrepor   )r!   r  rl   r   Promptrs   r\   r+   r  rh  r  r  rj   s         r5   r  zAsyncClient.get_prompt  s       !) @ @AR S{A	!88q6 H $$?x}}v'>?? .. 		s8   A>A% A#)A% "A>#A% %A;8A>:A;;A>r<  readmer|  r  c                 K   | j                          d{   }|r!|j                  st        j                  d      t        j                  |      \  }}}	| j                  |       d{   s| j                  d|       d{   ||xs d|xs d|xs g |d}
| j                  dd|
	       d{   }|j                          t        j                  di |j                         d
   S 7 7 7 n7 @w)a  Create a new prompt.

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

        Args:
            prompt_identifier: The identifier of the prompt.

                The identifier should be in the format of `owner/name:hash`,
                `name:hash`, `owner/name`, or `name`
            description: A description of the prompt.
            readme: A readme for the prompt.
            tags: A list of tags for the prompt.
            is_public: Whether the prompt should be public.

        Returns:
            The created `Prompt` object.

        Raises:
            ValueError: If the current tenant is not the owner.
            HTTPError: If the server request fails.
        NCannot 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)rh  zcreate a prompt )repo_handler<  r  r|  r  rx   ry  r?  r  r   )rd  rg  r!   rl  r  rj  rn  rl   r  r   r  rs   )r+   r  r<  r  r|  r  ri  rh  r  r  rs   rj   s               r5   create_promptzAsyncClient.create_prompt  s    < ++--X33--6  !) @ @AR S{A33%3@@@334EuMMN '&,"lJB"<
 44VYT4RR!!#  ;8==?6#:;;/ . AM SsF   C9C1AC9,C3-C9C5/C96C77;C93C95C97C9parent_commit_hashr|  c                 K   | j                  |       d{   st        j                  d      t        j                  |      }t        |t              rd|v rd|v r|}n$	 ddlm}  ||      }t        j                  |      }t        j                  |      \  }	}
}|	 d|
 }|d	k(  s|| j                  |       d{   }||d
}| j                  dd| |       d{   }|j                         d   }|d   }|d   }|r| j                  |||       d{    | j!                  | d|        d{   S 7 *# t        $ r t        d      w xY w7 7 y7 A7 %w)a>  Create a commit for an existing prompt.

        Args:
            prompt_identifier: The identifier of the prompt.
            object: The LangChain object to commit.
            parent_commit_hash: The hash of the parent commit.

                Defaults to latest commit.
            tags: A single tag or list of tags to apply to the commit.

                Defaults to `None`.

        Returns:
            The url of the prompt commit.

        Raises:
            HTTPError: If the server request fails.
            ValueError: If the prompt does not exist.
        Nz0Prompt does not exist, you must create it first.r   lcr   )dumpszvThe client.create_commit function requires the langchain-corepackage to run.
Install with `pip install langchain-core`rP  rT  )parent_commitmanifestrx   rp  r?  commitrr  r  )r  r!   r\   r$   prep_obj_for_pushr'   dictlangchain_core.loadr  ImportErrorrs   loadsr  rt  rl   r~  r  )r+   r  objectr  r|  preppedmanifest_dictr  json_objectrh  r  r  rs  request_dictrj   commit_jsonrr  rx  s                     r5   create_commitzAsyncClient.create_commit  s    6 ))*;<<<11B 
 --f5gt$TW_#M5  .K JJ{3M ( @ @AR S{A#(';- 8)-?-G'+'C'C%( " *<W44i 567l 5 
 
 mmoh/!-0%	**+@)TRRR))-B,C1[M*RSSSQ =  !Q "

 SSsk   E$EA	E$"E (AE$ E#E$$E%9E$E E$<E"=E$EE$E$ E$"E$)r<  r  r|  r  r  c               t  K   | j                          d{   }|r|j                  st        d      i }|||d<   |||d<   |||d<   |||d<   |||d<   t        j                  |      \  }	}
}| j                  dd	|	 d
|
 |       d{   }|j                          |j                         S 7 7 &w)a  Update a prompt's metadata.

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

        Args:
            prompt_identifier: The identifier of the prompt to update.
            description: New description for the prompt.
            readme: New readme for the prompt.
            tags: New list of tags for the prompt.
            is_public: New public status for the prompt.
            is_archived: New archived status for the prompt.

        Returns:
            The updated prompt data as returned by the server.

        Raises:
            ValueError: If the `prompt_identifier` is empty.
            HTTPError: If the server request fails.
        Nr  r<  r  r  r  r|  r   ry  rP  r?  )rd  rg  r   r!   r  rl   r  rs   )r+   r  r<  r  r|  r  r  ri  rs   rh  r  r  rj   s                r5   update_promptzAsyncClient.update_prompt  s     : ++--X336  <>""-D#DN  )D""-DDL ( @ @AR S{A44wugQ{m44 5 
 
 	!!#}}7 ..
s"   B8B4A8B8B6%B86B8c                  K   t        j                  |      \  }}}| j                  |       d{   s| j                  d|       d{   | j	                  dd| d|        d{   }|j                          y7 O7 77 w)a.  Delete a prompt.

        Args:
            prompt_identifier: The identifier of the prompt to delete.

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

        Raises:
            ValueError: If the current tenant is not the owner of the prompt.
        Nzdelete a promptr   ry  rP  )r!   r  rj  rn  rl   r  r  s         r5   delete_promptzAsyncClient.delete_promptX  s      !) @ @AR S{A33E:::334EuMMN44wa}5
 
 	!!# ;M
s3   .BB B
BB*B+BBBc                    |rdnd}| | S )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  r   )r+   r  include_modelsuffixs       r5   _get_cache_keyzAsyncClient._get_cache_keym  s     #0R#$VH--rG   c           
        K   t        j                  |      \  }}}| j                  dd| d| d| |rdnd        d{   }t        j                  di ||d|j                         S 7 ,w)	zFetch a prompt from the API (no caching).

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

        Returns:
            The `PromptCommit` object.
        rq   rp  rP  z?include_model=truer  Nrh  r  r   )r!   r  rl   r   PromptCommitrs   )r+   r  r  rh  r  rr  rj   s          r5   _afetch_prompt_from_apiz#AsyncClient._afetch_prompt_from_api|  s      +3*J*J+
'{K 44E7!K=+,9(rBD
 
 && 
{FhmmoF
 	

s   >A/ A--A/r  
skip_cachec               <  K   |s=| j                   1| j                  ||      }| j                   j                  |      }||S | j                  ||       d{   }|s:| j                   .| j                  ||      }| j                   j	                  ||       |S 7 Bw)a  Pull a prompt object from the LangSmith API.

        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`.

        Returns:
            The prompt object.

        Raises:
            ValueError: If no commits are found for the prompt.
        N)r   r  rP   r  set)r+   r  r  r  	cache_keycachedr   s          r5   pull_prompt_commitzAsyncClient.pull_prompt_commit  s     . dkk5++,=}MI[[__Y/F! 334E}UU dkk5++,=}MIKKOOIv. Vs   ABBABro   rn   r  c                K   t        j                  |      \  }}}|t        d|      n|||d}d}		 ||d<   | j                  dd| d| d|	       d{   }
|
j	                         }|d
   }|d   }|sy|D ]-  }||	|k\  r yt        j                  di ||d| |	dz  }	/ |t        |      z  }||k\  ry7 hw)a  List commits for a given prompt.

        Args:
            prompt_identifier: The identifier of the prompt in the format `owner/repo_name`.
            limit: The maximum number of commits to return.

                If `None`, returns all commits.
            offset: The number of commits to skip before starting to return results.
            include_model: 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.
        Nrp   r  r   rn   rq   rp  rP  rr   rq  totalr  rN   r   )r!   r  r,  rl   rs   r   ListedPromptCommitrt   )r+   r  ro   rn   r  rh  r  r  rL   r:  rj   valrQ   r  its                  r5   list_prompt_commitszAsyncClient.list_prompt_commits  s    4 !) @ @AR S{A ).(9Se_u*

 %F8!88E7!K=2 9  H
 --/C	NELE $e 33  %{AbA  Q c%j F/ s   ACB?A)C)r  secretssecrets_from_envr  c               x   K   | j                  |||       d{   }t        j                  ||||      S 7 w)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`.

        Returns:
            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.
        r  N)r  r  r  )r  r$   _process_prompt_manifest)r+   r  r  r  r  r  prompt_objects          r5   pull_promptzAsyncClient.pull_prompt  sP     b #55]z 6 
 
 11'-	
 	

s   :8:)r  r  r  r<  r  r|  commit_tagsc               t  K   | j                  |       d{   r5t        d ||||fD              rA| j                  |||||       d{    n"| j                  |||nd|||       d{    || j	                  |       d{   S | j                  ||||       d{   }	|	S 7 7 d7 C7 )7 w)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: The identifier of the prompt.
            object: The LangChain object to push.
            parent_commit_hash: The parent commit hash.
            is_public: 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: A description of the prompt.

                Defaults to an empty string.
            readme: A readme for the prompt.

                Defaults to an empty string.
            tags: A list of tags for the prompt.

                Defaults to an empty list.
            commit_tags: A single tag or list of tags for the prompt commit.

                Defaults to an empty list.

        Returns:
            The URL of the prompt.
        Nc              3  $   K   | ]  }|d u 
 y wrD   r   ).0params     r5   	<genexpr>z*AsyncClient.push_prompt.<locals>.<genexpr>g  s      &+T!s   r  F)r  r<  r  r|  )r  r  )r  anyr  r  r  r  )
r+   r  r  r  r  r<  r  r|  r  urls
             r5   push_promptzAsyncClient.push_prompt5  s    b $$%6777 09;PT/U  ((% +!' )    $$!'0'<)%' %    >--@Q-RRR &&1	 ' 
 
 
= 8 S
sW   B8B.3B8B0"B8.B2/B8
B4B8'B6(B80B82B84B86B8)NNNNNF)r,   Optional[str]r-   r  r.   zWOptional[Union[int, tuple[Optional[int], Optional[int], Optional[int], Optional[int]]]]r/   zOptional[Mapping[str, Any]]r0   r  r1   zUnion[AsyncCache, bool])returnr   )r  rE   )rc   rE   rd   rE   re   r   r  zhttpx.ResponserD   )ru   rE   rL   Optional[dict[str, Any]]r  zAsyncIterator[dict[str, Any]])
ru   rE   rz   Optional[dict]r{   rE   r|   rE   r  zAsyncIterator[dict])r   rE   r   dict[str, Any]r   rE   r   r  r   Optional[ls_client.ID_TYPE]re   r   r  None)r   ls_client.ID_TYPEre   r   r  r  )r   r  r  zls_schemas.Run)$r   z?Optional[Union[ls_client.ID_TYPE, Sequence[ls_client.ID_TYPE]]]r   z#Optional[Union[str, Sequence[str]]]r   r  r   r  r   r  r   r  r   r  r   r  r   r  r   Optional[bool]r   r  r   zOptional[datetime.datetime]r   r  r   %Optional[Sequence[ls_client.ID_TYPE]]r   Optional[Sequence[str]]ro   Optional[int]re   r   r  zAsyncIterator[ls_schemas.Run])r   r  r   r  r  rE   )r   r  r  bool)r   r  r  r  )r   rE   re   r   r  ls_schemas.TracerSession)NN)r   r  r   r  r  r  )r   r  r   r  r  r  )r   rE   re   r   r  ls_schemas.Dataset)r   r  r   r  r  r  )r   r  r  r  )re   r   r  z!AsyncIterator[ls_schemas.Dataset])NNN)r   r  r   r  r   r  r   r  re   r   r  ls_schemas.Example)r   r  r  r  )r   r  r   r  re   r   r  z!AsyncIterator[ls_schemas.Example])r   r  r  rE   r  zOptional[float]r  (Union[float, int, bool, str, dict, None]r  r  re   r   r  ls_schemas.Feedback)r  zUnion[str, uuid.UUID]r  zUnion[float, int, bool, None]r  r  r
  zUnion[dict, None]r  zUnion[str, None]r  r  r  r  )r   r  r  rE   r  z0Optional[datetime.datetime | datetime.timedelta]r  z#Optional[ls_schemas.FeedbackConfig]r  r  r  zls_schemas.FeedbackIngestToken)r  r  r  r  )r   r  r  r  r)  z1Optional[Sequence[ls_schemas.FeedbackSourceType]]ro   r  re   r   r  z"AsyncIterator[ls_schemas.Feedback])r  ID_TYPEr  r  )
r2  zOptional[list[ID_TYPE]]r   r  r3  r  ro   r  r  z)AsyncIterator[ls_schemas.AnnotationQueue])r   rE   r<  r  r=  zOptional[ID_TYPE]r  ls_schemas.AnnotationQueue)r=  r  r  r  )r=  r  r   rE   r<  r  r  r  )r=  r  r  r  )r=  r  r   zlist[ID_TYPE]r  r  )r=  r  r   r  r  r  )r=  r  rR  r(   r  z%ls_schemas.RunWithAnnotationQueueInfo)r   r  rU  rE   re   r   r  r  )r   r  re   r   r  r  )r   r  ro   r(   r   r  r   r  re   r   r  zlist[ls_schemas.ExampleSearch])r  zls_schemas.LangSmithSettings)rh  rE   r  r  )rm  rE   rh  rE   r  zls_utils.LangSmithUserError)rN   r   )rs  rE   ro   r(   rn   r(   r  r  )rs  rE   rx  rE   r|  zUnion[str, list[str]]r  r  )r  rE   r  r  r  dict[str, int])r  rE   r  rE   )r  rE   r  r  )r  rE   r  r   )ro   r(   rn   r(   r  r  r  r  r  zls_schemas.PromptSortFieldr  zLiteral['desc', 'asc']r   r  r  zls_schemas.ListPromptsResponse)r  rE   r  zOptional[ls_schemas.Prompt])r  rE   r<  r  r  r  r|  r  r  r  r  zls_schemas.Prompt)
r  rE   r  r   r  r  r|  Optional[str | list[str]]r  rE   )r  rE   r<  r  r  r  r|  r  r  r  r  r  r  r  )r  rE   r  r  )F)r  rE   r  r  r  rE   )r  rE   r  r  r  ls_schemas.PromptCommit)r  rE   r  r  r  r  r  r  )
r  rE   ro   r  rn   r(   r  r  r  z3AsyncGenerator[ls_schemas.ListedPromptCommit, None])r  rE   r  zbool | Noner  zdict[str, str] | Noner  r  r  r  r  r   )r  rE   r  zOptional[Any]r  rE   r  r  r<  r  r  r  r|  r  r  r  r  rE   )L__name__
__module____qualname____doc__	__slots__r6   r:   r@   r<   propertyrF   rJ   rl   rw   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r	  r  r$  r(  r.  r1  r;  r@  rC  rF  rI  rL  rN  rS  ls_beta	warn_betarY  r[  ra  rd  rj  rn  rt  r~  r  r  r  r  r  r   r  
updated_atr  r  r  r  r  r  r  r  r  r  r  r  r   rG   r5   r   r      sc   >OI "&!%
 48!%).99 9
	9 29 9 '9v$ * * C C:
:
 :
 	:

 
:
~ ,0!! )! 
'	!2  $$00 	0
 0 0 
0H '+37

 
 	
 $
 1
 
 

0
!
 
 
	
1 <@"&04<@# $&*%)"&5926 $9=*.#)b
b :b  b .b :b b b $b #b  b 3b  0!b" #b$ 7%b& ('b( )b* +b, 
'-bJ UY:':6Q:	:> 
D.
;
; 
; 
"	
; '+260#0 00 
"	06 04QU
,
AN
	
*
5
5 
5 
	
5 '+26*#* 0* 
	*4
00 
+0 -126&*55 *5 0	5
 $5 5 
545 37&*	0 00 $	0
 0 
+0, "&:>!%&6+&6 &6 	&6
 8&6 &6 &6 
&6V 04-6
 ;?(,$(#'-6+-6 --6
 8-6 &-6 "-6 !-6 
-6h HL?C37BA!BA BA
 EBA =BA 1BA 
(BAH6,6	6 :>04RV# 7 .	
 P   
,8	6  .2"'+#( +( 	(
 %( ( 
3(\ &*&*
 
 #	

 $
 
$
@SS	#S MQ66*-6<I6	6(666-:6	6(66,36	6 HH+.H	.H* 
 	2 &2 	2
 2 
2 2< 2 &2 	2
 
2 22  !%cc
 c &c c c 
(c cJ
?

"%
	$
 IJ>%(>14>BE>	>*E%(E58E@UE	E:!$,0	.
.
)	O	P $(&+1;1K1K1V1V17#/A /A 	/A
 "/A $/A //A //A /A 
(/Ab: &* $(,5<5< #	5<
 5< &5< 5< 
5<x -1*.CTCT CT
 *CT (CT 
CTR &* $(,$(&*88 #	8
 8 &8 "8 $8 
8t$, GL.!$.5C.	.$ ).

 &
 
!	
@ ). %% &	%
 % 
!%V  $#99 	9
 9 9 
=9~ &+)-!& 9
9
 #	9

 '9
 9
 9
 
9
~ !%"*$(%) $(,15OO 	O
  O "O #O O &O /O 
OrG   r   c                \    | j                         D ci c]  \  }}|	|| c}}S c c}}w )z(Exclude `None` values from a dictionary.)rQ   )drf   rg   s      r5   r  r    s(    WWY8TQ!-AqD888s   
(()r  r  r  r  )%r  
__future__r   ra   r  rs   r   r   collections.abcr   r   r   r   typingr   r	   r
   r   r   r*   	langsmithr   r$   r   r   r   r!   langsmith._internalr   r	  langsmith.cacher   r   rE   r  r   r  r   rG   r5   <module>r     sb    ! "      L L   ) + ' : &
		3
f fR;9rG   