
    c
i`                        d Z ddlmZ ddlmZmZmZ ddlmZ ddl	m
Z
 ddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZ  G d d          Zd	S )
z5Synchronous client for managing threads in LangGraph.    )annotations)IteratorMappingSequence)Any)SyncHttpClient)
CheckpointJsonOnConflictBehaviorPruneStrategyQueryParamTypes	SortOrder
StreamPartThreadThreadSelectFieldThreadSortByThreadStateThreadStatusThreadStreamModeThreadUpdateStateResponsec                      e Zd ZdZd^dZddddd_dZdddddddddd`dZdddddad!Zddd"dbd#Zddddd$d%ddddddd&dcd7Z	dddddd8ddd9Z
ddd"dbd:Zd;ddd<dedBZ	 	 dfdCdddDdgdKZddddddLdhdPZd$ddddddQdidVZdWddddXdjd]ZdS )kSyncThreadsClienta}  Synchronous client for managing threads in LangGraph.

    This class provides methods to create, retrieve, and manage threads,
    which represent conversations or stateful interactions.

    ???+ example "Example"

        ```python
        client = get_sync_client(url="http://localhost:2024")
        thread = client.threads.create(metadata={"user_id": "123"})
        ```
    httpr   returnNonec                    || _         d S )N)r   )selfr   s     C:\Users\Dell Inspiron 16\Desktop\tws\AgrotaPowerBi\back-agrota-powerbi\mcp-client-agrota\venv\Lib\site-packages\langgraph_sdk/_sync/threads.py__init__zSyncThreadsClient.__init__)   s    			    N)includeheadersparams	thread_idstrr!   Sequence[str] | Noner"   Mapping[str, str] | Noner#   QueryParamTypes | Noner   c                   i }|rd                     |          |d<   |r|                    |           | j                            d| ||pd          S )a  Get a thread by ID.

        Args:
            thread_id: The ID of the thread to get.
            include: Additional fields to include in the response.
                Supported values: `"ttl"`.
            headers: Optional custom headers to include with the request.
            params: Optional query parameters to include with the request.

        Returns:
            `Thread` object.

        ???+ example "Example Usage"

            ```python
            client = get_sync_client(url="http://localhost:2024")
            thread = client.threads.get(
                thread_id="my_thread_id"
            )
            print(thread)
            ```
            ```shell
            -----------------------------------------------------

            {
                'thread_id': 'my_thread_id',
                'created_at': '2024-07-18T18:35:15.540834+00:00',
                'updated_at': '2024-07-18T18:35:15.540834+00:00',
                'metadata': {'graph_id': 'agent'}
            }
            ```

        ,r!   	/threads/Nr"   r#   )joinupdater   get)r   r$   r!   r"   r#   query_paramss         r   r/   zSyncThreadsClient.get,   sw    R (* 	8&)hhw&7&7L# 	('''y}}#	##'4  
 
 	
r    )metadatar$   	if_exists
superstepsgraph_idttlr"   r#   r1   r
   
str | Noner2   OnConflictBehavior | Noner3   4Sequence[dict[str, Sequence[dict[str, Any]]]] | Noner4   r5   int | Mapping[str, Any] | Nonec                  i }	|r||	d<   |s|ri |pi |rd|ini |	d<   |r||	d<   |rd |D             |	d<   |*t          |t          t          f          r	|dd	|	d
<   n||	d
<   | j                            d|	||          S )aR  Create a new thread.

        Args:
            metadata: Metadata to add to thread.
            thread_id: ID of thread.
                If `None`, ID will be a randomly generated UUID.
            if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
                Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing thread).
            supersteps: Apply a list of supersteps when creating a thread, each containing a sequence of updates.
                Each update has `values` or `command` and `as_node`. Used for copying a thread between deployments.
            graph_id: Optional graph ID to associate with the thread.
            ttl: Optional time-to-live in minutes for the thread. You can pass an
                integer (minutes) or a mapping with keys `ttl` and optional
                `strategy` (defaults to "delete").
            headers: Optional custom headers to include with the request.

        Returns:
            The created `Thread`.

        ???+ example "Example Usage"

            ```python
            client = get_sync_client(url="http://localhost:2024")
            thread = client.threads.create(
                metadata={"number":1},
                thread_id="my-thread-id",
                if_exists="raise"
            )
            ```
            )
        r$   r4   r1   r2   c                6    g | ]}d d |d          D             iS )updatesc                X    g | ]'}|d          |                     d          |d         d(S )valuescommandas_node)r>   r?   r@   )r/   ).0us     r   
<listcomp>z7SyncThreadsClient.create.<locals>.<listcomp>.<listcomp>   sN           	 '(k'(uuY'7'7'(|      r     )rA   ss     r   rC   z,SyncThreadsClient.create.<locals>.<listcomp>   sQ     % % %       "#9     	% % %r    r3   Ndeleter5   strategyr5   z/threadsjsonr"   r#   )
isinstanceintfloatr   post)
r   r1   r$   r2   r3   r4   r5   r"   r#   payloads
             r   createzSyncThreadsClient.create`   s    V #% 	-#,GK  	x 	#>r#-5=J))2#GJ  	-#,GK  	% % $% % %GL! ?#U|,, %),(!C!C!$y~~jwPV~WWWr    )r5   r"   r#   Mapping[str, Any]c                   d|i}|*t          |t          t          f          r	|dd|d<   n||d<   | j                            d| |||          S )an  Update a thread.

        Args:
            thread_id: ID of thread to update.
            metadata: Metadata to merge with existing thread metadata.
            ttl: Optional time-to-live in minutes for the thread. You can pass an
                integer (minutes) or a mapping with keys `ttl` and optional
                `strategy` (defaults to "delete").
            headers: Optional custom headers to include with the request.
            params: Optional query parameters to include with the request.

        Returns:
            The created `Thread`.

        ???+ example "Example Usage"

            ```python
            client = get_sync_client(url="http://localhost:2024")
            thread = client.threads.update(
                thread_id="my-thread-id",
                metadata={"number":1},
                ttl=43_200,
            )
            ```
        r1   NrF   rG   r5   r+   rI   )rK   rL   rM   r   patch)r   r$   r1   r5   r"   r#   rO   s          r   r.   zSyncThreadsClient.update   sw    D $.x"8?#U|,, %),(!C!C!$y#	##	  
 
 	
r    r,   c               F    | j                             d| ||           dS )a  Delete a thread.

        Args:
            thread_id: The ID of the thread to delete.
            headers: Optional custom headers to include with the request.
            params: Optional query parameters to include with the request.

        Returns:
            `None`

        ???+ example "Example Usage"

            ```python
            client.threads.delete(
                thread_id="my_thread_id"
            )
            ```

        r+   r,   N)r   rF   r   r$   r"   r#   s       r   rF   zSyncThreadsClient.delete   s0    4 		0Y00'&QQQQQr    
   r   )r1   r>   idsstatuslimitoffsetsort_by
sort_orderselectextractr"   r#   r>   rW   rX   ThreadStatus | NonerY   rL   rZ   r[   ThreadSortBy | Noner\   SortOrder | Noner]   list[ThreadSelectField] | Noner^   dict[str, str] | Nonelist[Thread]c                   ||d}|r||d<   |r||d<   |r||d<   |r||d<   |r||d<   |r||d<   |	r|	|d<   |
r|
|d	<   | j                             d
|||          S )a  Search for threads.

        Args:
            metadata: Thread metadata to filter on.
            values: State values to filter on.
            ids: List of thread IDs to filter by.
            status: Thread status to filter on.
                Must be one of 'idle', 'busy', 'interrupted' or 'error'.
            limit: Limit on number of threads to return.
            offset: Offset in threads table to start search from.
            sort_by: Sort by field.
            sort_order: Sort order.
            select: List of fields to include in the response.
            extract: Dictionary mapping aliases to JSONB paths to extract
                from thread data. Paths use dot notation for nested keys and
                bracket notation for array indices (e.g.,
                `{"last_msg": "values.messages[-1]"}`). Extracted values are
                returned in an `extracted` field on each thread. Maximum 10
                paths per request.
            headers: Optional custom headers to include with the request.
            params: Optional query parameters to include with the request.

        Returns:
            List of the threads matching the search parameters.

        ???+ example "Example Usage"

            ```python
            client = get_sync_client(url="http://localhost:2024")
            threads = client.threads.search(
                metadata={"number":1},
                status="interrupted",
                limit=15,
                offset=5
            )
            ```
        )rY   rZ   r1   r>   rW   rX   r[   r\   r]   r^   z/threads/searchrI   r   rN   )r   r1   r>   rW   rX   rY   rZ   r[   r\   r]   r^   r"   r#   rO   s                 r   searchzSyncThreadsClient.search   s    l #
 #
  	+"*GJ 	' &GH 	! GEN 	' &GH 	)!(GI 	/$.GL! 	' &GH 	)!(GIy~~GWV  
 
 	
r    )r1   r>   rX   r"   r#   c               l    i }|r||d<   |r||d<   |r||d<   | j                             d|||          S )a  Count threads matching filters.

        Args:
            metadata: Thread metadata to filter on.
            values: State values to filter on.
            status: Thread status to filter on.
            headers: Optional custom headers to include with the request.
            params: Optional query parameters to include with the request.

        Returns:
            int: Number of threads matching the criteria.
        r1   r>   rX   z/threads/countrI   rf   )r   r1   r>   rX   r"   r#   rO   s          r   countzSyncThreadsClient.countC  se    * #% 	+"*GJ 	' &GH 	' &GHy~~7GF  
 
 	
r    c               F    | j                             d| dd||          S )a  Copy a thread.

        Args:
            thread_id: The ID of the thread to copy.
            headers: Optional custom headers to include with the request.
            params: Optional query parameters to include with the request.

        Returns:
            `None`

        ???+ example "Example Usage"

            ```python
            client = get_sync_client(url="http://localhost:2024")
            client.threads.copy(
                thread_id="my_thread_id"
            )
            ```

        r+   z/copyNrI   rf   rU   s       r   copyzSyncThreadsClient.copyc  s5    6 y~~(	(((tWV  
 
 	
r    rF   )rH   r"   r#   
thread_idsSequence[str]rH   r   dict[str, Any]c               \    d|i}|dk    r||d<   | j                             d|||          S )aX  Prune threads by ID.

        Args:
            thread_ids: List of thread IDs to prune.
            strategy: The prune strategy. `"delete"` removes threads entirely.
                `"keep_latest"` prunes old checkpoints but keeps threads and their
                latest state. Defaults to `"delete"`.
            headers: Optional custom headers to include with the request.
            params: Optional query parameters to include with the request.

        Returns:
            A dict containing `pruned_count` (number of threads pruned).

        ???+ example "Example Usage"

            ```python
            client = get_sync_client(url="http://localhost:2024")
            result = client.threads.prune(
                thread_ids=["thread_1", "thread_2"],
            )
            print(result)  # {'pruned_count': 2}
            ```

        rl   rF   rH   z/threads/prunerI   rf   )r   rl   rH   r"   r#   rO   s         r   prunezSyncThreadsClient.prune  sN    B *#
 x"*GJy~~7GF  
 
 	
r    F)	subgraphsr"   r#   
checkpointCheckpoint | Nonecheckpoint_idrq   boolr   c               @   |r%| j                             d| d||d||          S |r<d|i}|ri |t          |          }| j                             d| d| ||          S d|i}|ri |t          |          }| j                             d| d||          S )	ab  Get the state of a thread.

        Args:
            thread_id: The ID of the thread to get the state of.
            checkpoint: The checkpoint to get the state of.
            subgraphs: Include subgraphs states.
            headers: Optional custom headers to include with the request.

        Returns:
            The thread of the state.

        ???+ example "Example Usage"

            ```python
            client = get_sync_client(url="http://localhost:2024")
            thread_state = client.threads.get_state(
                thread_id="my_thread_id",
                checkpoint_id="my_checkpoint_id"
            )
            print(thread_state)
            ```

            ```shell
            ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

            {
                'values': {
                    'messages': [
                        {
                            'content': 'how are you?',
                            'additional_kwargs': {},
                            'response_metadata': {},
                            'type': 'human',
                            'name': None,
                            'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10',
                            'example': False
                        },
                        {
                            'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
                            'additional_kwargs': {},
                            'response_metadata': {},
                            'type': 'ai',
                            'name': None,
                            'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
                            'example': False,
                            'tool_calls': [],
                            'invalid_tool_calls': [],
                            'usage_metadata': None
                        }
                    ]
                },
                'next': [],
                'checkpoint':
                    {
                        'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                        'checkpoint_ns': '',
                        'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1'
                    }
                'metadata':
                    {
                        'step': 1,
                        'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2',
                        'source': 'loop',
                        'writes':
                            {
                                'agent':
                                    {
                                        'messages': [
                                            {
                                                'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
                                                'name': None,
                                                'type': 'ai',
                                                'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
                                                'example': False,
                                                'tool_calls': [],
                                                'usage_metadata': None,
                                                'additional_kwargs': {},
                                                'response_metadata': {},
                                                'invalid_tool_calls': []
                                            }
                                        ]
                                    }
                            },
                'user_id': None,
                'graph_id': 'agent',
                'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                'created_by': 'system',
                'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'},
                'created_at': '2024-07-25T15:35:44.184703+00:00',
                'parent_config':
                    {
                        'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                        'checkpoint_ns': '',
                        'checkpoint_id': '1ef4a9b8-d80d-6fa7-8000-9300467fad0f'
                    }
            }
            ```

        r+   z/state/checkpoint)rr   rq   rI   rq   z/state/)r#   r"   /state)r   rN   dictr/   )r   r$   rr   rt   rq   r"   r#   
get_paramss           r   	get_statezSyncThreadsClient.get_state  s
   Z  	9>>8I888$.YGG	 "     	%y1J <;
;d6ll;
9===I==m==! !    &y1J <;
;d6ll;
9==-I---! !   r    )r@   rr   rt   r"   r#   &dict[str, Any] | Sequence[dict] | Noner@   r   c               x    d|i}|r||d<   |r||d<   |r||d<   | j                             d| d|||          S )a  Update the state of a thread.

        Args:
            thread_id: The ID of the thread to update.
            values: The values to update the state with.
            as_node: Update the state as if this node had just executed.
            checkpoint: The checkpoint to update the state of.
            headers: Optional custom headers to include with the request.

        Returns:
            Response after updating a thread's state.

        ???+ example "Example Usage"

            ```python

            response = await client.threads.update_state(
                thread_id="my_thread_id",
                values={"messages":[{"role": "user", "content": "hello!"}]},
                as_node="my_node",
            )
            print(response)

            ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

            {
                'checkpoint': {
                    'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
                    'checkpoint_ns': '',
                    'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1',
                    'checkpoint_map': {}
                }
            }
            ```

        r>   rt   rr   r@   r+   rw   rI   rf   )	r   r$   r>   r@   rr   rt   r"   r#   rO   s	            r   update_statezSyncThreadsClient.update_state2  s{    ` f#
  	5'4GO$ 	/$.GL! 	)!(GIy~~)	)))QW  
 
 	
r    )rY   beforer1   rr   r"   r#   r~   str | Checkpoint | NoneMapping[str, Any] | Nonelist[ThreadState]c               x    d|i}|r||d<   |r||d<   |r||d<   | j                             d| d|||          S )aC  Get the state history of a thread.

        Args:
            thread_id: The ID of the thread to get the state history for.
            checkpoint: Return states for this subgraph. If empty defaults to root.
            limit: The maximum number of states to return.
            before: Return states before this checkpoint.
            metadata: Filter states by metadata key-value pairs.
            headers: Optional custom headers to include with the request.

        Returns:
            The state history of the `Thread`.

        ???+ example "Example Usage"

            ```python

            thread_state = client.threads.get_history(
                thread_id="my_thread_id",
                limit=5,
                before="my_timestamp",
                metadata={"name":"my_name"}
            )
            ```

        rY   r~   r1   rr   r+   z/historyrI   rf   )	r   r$   rY   r~   r1   rr   r"   r#   rO   s	            r   get_historyzSyncThreadsClient.get_historyn  s}    L U#
  	' &GH 	+"*GJ 	/$.GL!y~~+	+++	  
 
 	
r    	run_modes)stream_modelast_event_idr"   r#   r   -ThreadStreamMode | Sequence[ThreadStreamMode]r   Iterator[StreamPart]c                   d|i}|r|                     |           | j                            d| ddi |rd|ini |pi |          S )a  Get a stream of events for a thread.

        Args:
            thread_id: The ID of the thread to get the stream for.
            last_event_id: The ID of the last event to get.
            headers: Optional custom headers to include with the request.
            params: Optional query parameters to include with the request.

        Returns:
            An iterator of stream parts.

        ???+ example "Example Usage"

            ```python

            for chunk in client.threads.join_stream(
                thread_id="my_thread_id",
                last_event_id="my_event_id",
                stream_mode="run_modes",
            ):
                print(chunk)
            ```

        r   r+   z/streamGETzLast-Event-IDr,   )r.   r   stream)r   r$   r   r   r"   r#   r0   s          r   join_streamzSyncThreadsClient.join_stream  s    D ;
  	('''y*	***7DLO]33"=b     
 
 	
r    )r   r   r   r   )
r$   r%   r!   r&   r"   r'   r#   r(   r   r   )r1   r
   r$   r6   r2   r7   r3   r8   r4   r6   r5   r9   r"   r'   r#   r(   r   r   )r$   r%   r1   rQ   r5   r9   r"   r'   r#   r(   r   r   )r$   r%   r"   r'   r#   r(   r   r   )r1   r
   r>   r
   rW   r&   rX   r_   rY   rL   rZ   rL   r[   r`   r\   ra   r]   rb   r^   rc   r"   r'   r#   r(   r   rd   )r1   r
   r>   r
   rX   r_   r"   r'   r#   r(   r   rL   )
rl   rm   rH   r   r"   r'   r#   r(   r   rn   )NN)r$   r%   rr   rs   rt   r6   rq   ru   r"   r'   r#   r(   r   r   )r$   r%   r>   r{   r@   r6   rr   rs   rt   r6   r"   r'   r#   r(   r   r   )r$   r%   rY   rL   r~   r   r1   r   rr   rs   r"   r'   r#   r(   r   r   )r$   r%   r   r   r   r6   r"   r'   r#   r(   r   r   )__name__
__module____qualname____doc__r   r/   rP   r.   rF   rg   ri   rk   rp   rz   r}   r   r   rD   r    r   r   r      s            )-,0)-2
 2
 2
 2
 2
 2
n  $/3KO#.2,0)-IX IX IX IX IX IX` /3,0)--
 -
 -
 -
 -
 -
f -1)-R R R R R R> $(&*'+'+15)-,0)-K
 K
 K
 K
 K
 K
` &*,0)-
 
 
 
 
 
H -1)-
 
 
 
 
 
F #+,0)-'
 '
 '
 '
 '
 '
X )-$(	E  ,0)-E E E E E EX #(,$(,0)-:
 :
 :
 :
 :
 :
@ *.-1(,,0)-3
 3
 3
 3
 3
 3
r FQ$(,0)-.
 .
 .
 .
 .
 .
 .
 .
r    r   N)r   
__future__r   collections.abcr   r   r   typingr   langgraph_sdk._sync.httpr   langgraph_sdk.schemar	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   rD   r    r   <module>r      s;   ; ; " " " " " " 7 7 7 7 7 7 7 7 7 7       3 3 3 3 3 3                               $v

 v

 v

 v

 v

 v

 v

 v

 v

 v

r    