
    c
id                        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 )
z/Async client for managing threads in LangGraph.    )annotations)AsyncIteratorMappingSequence)Any)
HttpClient)
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ddWdddXdjd]ZdS )kThreadsClienta  Client for managing threads in LangGraph.

    A thread maintains the state of a graph across multiple interactions/invocations (aka runs).
    It accumulates and persists the graph's state, allowing for continuity between separate
    invocations of the graph.

    ???+ example "Example"

        ```python
        client = get_client(url="http://localhost:2024"))
        new_thread = await 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/_async/threads.py__init__zThreadsClient.__init__*   s    			    N)includeheadersparams	thread_idstrr!   Sequence[str] | Noner"   Mapping[str, str] | Noner#   QueryParamTypes | Noner   c                  K   i }|rd                     |          |d<   |r|                    |           | j                            d| ||pd           d{V 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_client(url="http://localhost:2024")
            thread = await 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ThreadsClient.get-   s      T (* 	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                 K   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|	||           d{V S )a  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.
            params: Optional query parameters to include with the request.

        Returns:
            The created thread.

        ???+ example "Example Usage"

            ```python
            client = get_client(url="http://localhost:2024")
            thread = await 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>z3ThreadsClient.create.<locals>.<listcomp>.<listcomp>   sN           	 '(k'(uuY'7'7'(|      r     )rA   ss     r   rC   z(ThreadsClient.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ThreadsClient.createb   s     V #% 	-#,GK  	x 	#>r#-5=J))2#GJ  	-#,GK  	% % $% % %GL! ?#U|,, %),(!C!C!$Y^^Wgf $ 
 
 
 
 
 
 
 
 	
r    )r5   r"   r#   Mapping[str, Any]c                  K   d|i}|*t          |t          t          f          r	|dd|d<   n||d<   | j                            d| |||           d{V S )am  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_client(url="http://localhost:2024")
            thread = await 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ThreadsClient.update   s      D $.x"8?#U|,, %),(!C!C!$Y__#	##	 % 
 
 
 
 
 
 
 
 	
r    r,   c               V   K   | j                             d| ||           d{V  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 = get_client(url="http://localhost2024)
            await client.threads.delete(
                thread_id="my_thread_id"
            )
            ```

        r+   r,   N)r   rF   r   r$   r"   r#   s       r   rF   zThreadsClient.delete   sG      6 i6966PVWWWWWWWWWWWr    
   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                  K   ||d}|r||d<   |r||d<   |r||d<   |r||d<   |r||d<   |r||d<   |	r|	|d<   |
r|
|d	<   | j                             d
|||           d{V 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_client(url="http://localhost:2024")
            threads = await 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   Nr   rN   )r   r1   r>   rW   rX   rY   rZ   r[   r\   r]   r^   r"   r#   rO   s                 r   searchzThreadsClient.search   s      n #
 #
  	+"*GJ 	' &GH 	! GEN 	' &GH 	)!(GI 	/$.GL! 	' &GH 	)!(GIY^^	 $ 
 
 
 
 
 
 
 
 	
r    )r1   r>   rX   r"   r#   c               |   K   i }|r||d<   |r||d<   |r||d<   | j                             d|||           d{V 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   Nrf   )r   r1   r>   rX   r"   r#   rO   s          r   countzThreadsClient.countL  s      * #% 	+"*GJ 	' &GH 	' &GHY^^7GF $ 
 
 
 
 
 
 
 
 	
r    c               V   K   | j                             d| dd||           d{V 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_client(url="http://localhost:2024)
            await client.threads.copy(
                thread_id="my_thread_id"
            )
            ```

        r+   z/copyNrI   rf   rU   s       r   copyzThreadsClient.copyl  sW      6 Y^^(	(((tWV $ 
 
 
 
 
 
 
 
 	
r    rF   )rH   r"   r#   
thread_idsSequence[str]rH   r   dict[str, Any]c               l   K   d|i}|dk    r||d<   | j                             d|||           d{V S )aY  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_client(url="http://localhost:2024")
            result = await client.threads.prune(
                thread_ids=["thread_1", "thread_2"],
            )
            print(result)  # {'pruned_count': 2}
            ```

        rl   rF   rH   z/threads/prunerI   Nrf   )r   rl   rH   r"   r#   rO   s         r   prunezThreadsClient.prune  sp      B *#
 x"*GJY^^7GF $ 
 
 
 
 
 
 
 
 	
r    F)	subgraphsr"   r#   
checkpointCheckpoint | Nonecheckpoint_idrq   boolr   c               h  K   |r+| j                             d| d||d||           d{V S |rBd|i}|ri |t          |          }| j                             d| d| ||           d{V S d|i}|ri |t          |          }| j                             d| d	||           d{V S )
a  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.
            checkpoint_id: (deprecated) The checkpoint ID to get the state of.
            subgraphs: Include subgraphs states.
            headers: Optional custom headers to include with the request.
            params: Optional query parameters to include with the request.

        Returns:
            The thread of the state.

        ???+ example "Example Usage"

            ```python
            client = get_client(url="http://localhost:2024)
            thread_state = await 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   Nrq   z/state/)r#   r"   /state)r   rN   dictr/   )r   r$   rr   rt   rq   r"   r#   
get_paramss           r   	get_statezThreadsClient.get_state  sh     \  	8I888$.YGG	 (           	%y1J <;
;d6ll;
=I==m==! '          &y1J <;
;d6ll;
-I---! '         r    )r@   rr   rt   r"   r#   &dict[str, Any] | Sequence[dict] | Noner@   r   c                  K   d|i}|r||d<   |r||d<   |r||d<   | j                             d| d|||           d{V 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.
            checkpoint_id: (deprecated) The checkpoint ID to update the state of.
            headers: Optional custom headers to include with the request.
            params: Optional query parameters to include with the request.

        Returns:
            Response after updating a thread's state.

        ???+ example "Example Usage"

            ```python
            client = get_client(url="http://localhost:2024)
            response = await client.threads.update_state(
                thread_id="my_thread_id",
                values={"messages":[{"role": "user", "content": "hello!"}]},
                as_node="my_node",
            )
            print(response)
            ```
            ```shell

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

            {
                '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   Nrf   )	r   r$   r>   r@   rr   rt   r"   r#   rO   s	            r   update_statezThreadsClient.update_state<  s      f f#
  	5'4GO$ 	/$.GL! 	)!(GIY^^)	)))QW $ 
 
 
 
 
 
 
 
 	
r    )rY   beforer1   rr   r"   r#   r~   str | Checkpoint | NoneMapping[str, Any] | Nonelist[ThreadState]c                  K   d|i}|r||d<   |r||d<   |r||d<   | j                             d| d|||           d{V S )	az  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.
            params: Optional query parameters to include with the request.

        Returns:
            The state history of the thread.

        ???+ example "Example Usage"

            ```python
            client = get_client(url="http://localhost:2024)
            thread_state = await client.threads.get_history(
                thread_id="my_thread_id",
                limit=5,
            )
            ```

        rY   r~   r1   rr   r+   z/historyrI   Nrf   )	r   r$   rY   r~   r1   rr   r"   r#   rO   s	            r   get_historyzThreadsClient.get_history{  s      J U#
  	' &GH 	+"*GJ 	/$.GL!Y^^+	+++	 $ 
 
 
 
 
 
 
 
 	
r    	run_modes)last_event_idstream_moder"   r#   r   r   -ThreadStreamMode | Sequence[ThreadStreamMode]AsyncIterator[StreamPart]c                  K   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",
            ):
                print(chunk)
            ```

        r   r+   z/streamGETzLast-Event-IDr,   )r.   r   stream)r   r$   r   r   r"   r#   r0   s          r   join_streamzThreadsClient.join_stream  s      B ;
  	('''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   r6   r   r   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)-3
 3
 3
 3
 3
 3
p  $/3KO#.2,0)-K
 K
 K
 K
 K
 K
d /3,0)--
 -
 -
 -
 -
 -
f -1)-X X X X X X@ $(&*'+'+15)-,0)-O
 O
 O
 O
 O
 O
h &*,0)-
 
 
 
 
 
H -1)-
 
 
 
 
 
F #+,0)-'
 '
 '
 '
 '
 '
X )-$(	F  ,0)-F F F F F FZ #(,$(,0)-=
 =
 =
 =
 =
 =
F *.-1(,,0)-2
 2
 2
 2
 2
 2
p %)EP,0)--
 -
 -
 -
 -
 -
 -
 -
r    r   N)r   
__future__r   collections.abcr   r   r   typingr   langgraph_sdk._async.httpr   langgraph_sdk.schemar	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   rD   r    r   <module>r      s;   5 5 " " " " " " < < < < < < < < < <       0 0 0 0 0 0                               $A
 A
 A
 A
 A
 A
 A
 A
 A
 A
r    