
    A'hWH                     <   d dl Z d dlZd dlZd dlZd dlmZ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 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mZmZm Z  d d
l!m"Z" d dl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) d dl*m+Z+ d dl,m-Z-m.Z. d dl/m0Z0 d dl1m2Z2m3Z3m4Z4m5Z5  G d dee$e&f         Z6edddddee7   deee4ee4   f      dee3ee$ee7e8f   f         deeee$ee&   f   ee$e&f   f   ge6e$e&f   f   fd       Z9edeee$ee&   f   ee$e&f   f   de6e$e&f   fd       Z9	 ddddddeeee$ee&   f   ee$e&f   f      dee7   deee4ee4   f      dee3ee$ee7e8f   f         deeeee$ee&   f   ee$e&f   f   ge6e$e&f   f   e6e$e&f   f   f
dZ9 ed      Z: ed      Z; G d d      Z<y)     N)	AwaitableSequence)	dataclass)	AnyCallableGenericOptionalTypeVarUnionget_args
get_originoverload)	BaseCache)EphemeralValue)	LastValue)BaseCheckpointSaver)CACHE_NS_WRITESENDPREVIOUSSTART)Pregel)PSyncAsyncFutureTcallget_runnable_for_entrypoint
identifier)
PregelNode)ChannelWriteChannelWriteEntry)	BaseStore)
_DC_KWARGSCachePolicyRetryPolicy
StreamModec                       e Zd Zdddddeeef   deee      dee	eee
eef   f         dee   ddf
d	Zd
ej                  dej                  dee   fdZdeddfdZdeddfdZy)TaskFunction Nretrycache_policynamefuncr*   r+   r,   returnc                    |Gt        |d      r4t        j                  |j                  |j                        }||_        |}n||_        || _        || _        || _        t        j                  | |       y )N__func__)
hasattr	functoolspartialr0   __self____name__r-   r*   r+   update_wrapper)selfr-   r*   r+   r,   instance_methods         ^/home/kushmeetdev/Regenta/Chatbot/venv/lib/python3.12/site-packages/langgraph/func/__init__.py__init__zTaskFunction.__init__(   sl     tZ( #,"3"3DMM4=="Q+/(& !%	
(  t,    argskwargsc                 b    t        | j                  g|| j                  | j                  d|S )N)r*   r+   )r   r-   r*   r+   )r7   r<   r=   s      r9   __call__zTaskFunction.__call__@   s:    II
JN
!ZZd6G6G
RX
 	
r;   cachec                 |    | j                   0|j                  t        t        | j                        xs dff       yyzClear the cache for this task.N__dynamic__)r+   clearr   r   r-   r7   r@   s     r9   clear_cachezTaskFunction.clear_cacheE   s5    (KK/:dii+@+QMRTU )r;   c                    K   | j                   8|j                  t        t        | j                        xs dff       d{    yy7 wrB   )r+   aclearr   r   r-   rE   s     r9   aclear_cachezTaskFunction.aclear_cacheJ   sK     (,,!:dii#8#IMJL   )s   ?A
AA
)r5   
__module____qualname__r   r   r   r	   r   r$   r#   r   strbytesr:   r<   r=   r   r?   r   rF   rI   r(   r;   r9   r'   r'   '   s    
 24NR"-q!tn- -.	-
 {8AuS%Z7H4H+IJK- sm- 
-0
aff 
 
_Q=O 

V Vt V
	 d r;   r'   r,   r*   r+   r,   r*   r+   r.   c                      y Nr(   rN   s      r9   taskrQ   R   s     r;   __func_or_none__c                      y rP   r(   )rR   s    r9   rQ   rQ   ^   s     r;   c          	      v   t        |t              r|fn|dt        t        t        t
        t           f   t        t        t        f   f   dt        t        t        t        j                  j                  t           f   t        t        t        j                  t           f   f   ffd}|  ||       S |S )aK  Define a LangGraph task using the `task` decorator.

    !!! important "Requires python 3.11 or higher for async functions"
        The `task` decorator supports both sync and async functions. To use async
        functions, ensure that you are using Python 3.11 or higher.

    Tasks can only be called from within an [entrypoint][langgraph.func.entrypoint] or
    from within a StateGraph. A task can be called like a regular function with the
    following differences:

    - When a checkpointer is enabled, the function inputs and outputs must be serializable.
    - The decorated function can only be called from within an entrypoint or StateGraph.
    - Calling the function produces a future. This makes it easy to parallelize tasks.

    Args:
        retry: An optional retry policy to use for the task in case of a failure.

    Returns:
        A callable function when used as a decorator.

    Example: Sync Task
        ```python
        from langgraph.func import entrypoint, task

        @task
        def add_one(a: int) -> int:
            return a + 1

        @entrypoint()
        def add_one(numbers: list[int]) -> list[int]:
            futures = [add_one(n) for n in numbers]
            results = [f.result() for f in futures]
            return results

        # Call the entrypoint
        add_one.invoke([1, 2, 3])  # Returns [2, 3, 4]
        ```

    Example: Async Task
        ```python
        import asyncio
        from langgraph.func import entrypoint, task

        @task
        async def add_one(a: int) -> int:
            return a + 1

        @entrypoint()
        async def add_one(numbers: list[int]) -> list[int]:
            futures = [add_one(n) for n in numbers]
            return asyncio.gather(*futures)

        # Call the entrypoint
        await add_one.ainvoke([1, 2, 3])  # Returns [2, 3, 4]
        ```
    r-   r.   c                 "    t        |       S )Nr)   )r'   )r-   r+   r,   retry_policiess    r9   	decoratorztask.<locals>.decorator   s    
 \
 	
r;   )
isinstancer$   r   r   r   r   r   
concurrentfuturesFutureasyncio)rR   r,   r*   r+   rW   rV   s    ` ` @r9   rQ   rQ   d   s    J %%;@(
HQ	!_-x1~=>
	J&&--a0018Aw~~a?P<P3QQ

 #)**r;   RSc                       e Zd ZdZ	 	 	 	 	 	 ddee   dee   dee   deee	      dee
   d	eeee   f   d
dfdZ edi e G d deeef                Zdede	f   d
efdZy)
entrypointa  Define a LangGraph workflow using the `entrypoint` decorator.

    ### Function signature

    The decorated function must accept a **single parameter**, which serves as the input
    to the function. This input parameter can be of any type. Use a dictionary
    to pass **multiple parameters** to the function.

    ### Injectable parameters

    The decorated function can request access to additional parameters
    that will be injected automatically at run time. These parameters include:

    | Parameter        | Description                                                                                        |
    |------------------|----------------------------------------------------------------------------------------------------|
    | **`store`**      | An instance of [BaseStore][langgraph.store.base.BaseStore]. Useful for long-term memory.           |
    | **`writer`**     | A [StreamWriter][langgraph.types.StreamWriter] instance for writing custom data to a stream.       |
    | **`config`**     | A configuration object (aka RunnableConfig) that holds run-time configuration values.              |
    | **`previous`**   | The previous return value for the given thread (available only when a checkpointer is provided).   |

    The entrypoint decorator can be applied to sync functions or async functions.

    ### State management

    The **`previous`** parameter can be used to access the return value of the previous
    invocation of the entrypoint on the same thread id. This value is only available
    when a checkpointer is provided.

    If you want **`previous`** to be different from the return value, you can use the
    `entrypoint.final` object to return a value while saving a different value to the
    checkpoint.

    Args:
        checkpointer: Specify a checkpointer to create a workflow that can persist
            its state across runs.
        store: A generalized key-value store. Some implementations may support
            semantic search capabilities through an optional `index` configuration.
        config_schema: Specifies the schema for the configuration object that will be
            passed to the workflow.

    Example: Using entrypoint and tasks
        ```python
        import time

        from langgraph.func import entrypoint, task
        from langgraph.types import interrupt, Command
        from langgraph.checkpoint.memory import MemorySaver

        @task
        def compose_essay(topic: str) -> str:
            time.sleep(1.0)  # Simulate slow operation
            return f"An essay about {topic}"

        @entrypoint(checkpointer=MemorySaver())
        def review_workflow(topic: str) -> dict:
            """Manages the workflow for generating and reviewing an essay.

            The workflow includes:
            1. Generating an essay about the given topic.
            2. Interrupting the workflow for human review of the generated essay.

            Upon resuming the workflow, compose_essay task will not be re-executed
            as its result is cached by the checkpointer.

            Args:
                topic: The subject of the essay.

            Returns:
                dict: A dictionary containing the generated essay and the human review.
            """
            essay_future = compose_essay(topic)
            essay = essay_future.result()
            human_review = interrupt({
                "question": "Please provide a review",
                "essay": essay
            })
            return {
                "essay": essay,
                "review": human_review,
            }

        # Example configuration for the workflow
        config = {
            "configurable": {
                "thread_id": "some_thread"
            }
        }

        # Topic for the essay
        topic = "cats"

        # Stream the workflow to generate the essay and await human review
        for result in review_workflow.stream(topic, config):
            print(result)

        # Example human review provided after the interrupt
        human_review = "This essay is great."

        # Resume the workflow with the provided human review
        for result in review_workflow.stream(Command(resume=human_review), config):
            print(result)
        ```

    Example: Accessing the previous return value
        When a checkpointer is enabled the function can access the previous return value
        of the previous invocation on the same thread id.

        ```python
        from langgraph.checkpoint.memory import MemorySaver
        from langgraph.func import entrypoint

        @entrypoint(checkpointer=MemorySaver())
        def my_workflow(input_data: str, previous: Optional[str] = None) -> str:
            return "world"

        config = {
            "configurable": {
                "thread_id": "some_thread"
            }
        }
        my_workflow.invoke("hello")
        ```

    Example: Using entrypoint.final to save a value
        The `entrypoint.final` object allows you to return a value while saving
        a different value to the checkpoint. This value will be accessible
        in the next invocation of the entrypoint via the `previous` parameter, as
        long as the same thread id is used.

        ```python
        from langgraph.checkpoint.memory import MemorySaver
        from langgraph.func import entrypoint

        @entrypoint(checkpointer=MemorySaver())
        def my_workflow(number: int, *, previous: Any = None) -> entrypoint.final[int, int]:
            previous = previous or 0
            # This will return the previous value to the caller, saving
            # 2 * number to the checkpoint, which will be used in the next invocation
            # for the `previous` parameter.
            return entrypoint.final(value=previous, save=2 * number)

        config = {
            "configurable": {
                "thread_id": "some_thread"
            }
        }

        my_workflow.invoke(3, config)  # 0 (previous was None)
        my_workflow.invoke(1, config)  # 6 (previous was 3 * 2 from the previous invocation)
        ```
    Nr(   checkpointerstorer@   config_schemar+   r*   r.   c                 X    || _         || _        || _        || _        || _        || _        y)z$Initialize the entrypoint decorator.N)ra   rb   r@   r+   r*   rc   )r7   ra   rb   r@   rc   r+   r*   s          r9   r:   zentrypoint.__init__^  s1     )

(
*r;   c                   (    e Zd ZU dZeed<   	 eed<   y)entrypoint.finala  A primitive that can be returned from an entrypoint.

        This primitive allows to save a value to the checkpointer distinct from the
        return value from the entrypoint.

        Example: Decoupling the return value and the save value
            ```python
            from langgraph.checkpoint.memory import MemorySaver
            from langgraph.func import entrypoint

            @entrypoint(checkpointer=MemorySaver())
            def my_workflow(number: int, *, previous: Any = None) -> entrypoint.final[int, int]:
                previous = previous or 0
                # This will return the previous value to the caller, saving
                # 2 * number to the checkpoint, which will be used in the next invocation
                # for the `previous` parameter.
                return entrypoint.final(value=previous, save=2 * number)

            config = {
                "configurable": {
                    "thread_id": "1"
                }
            }

            my_workflow.invoke(3, config)  # 0 (previous was None)
            my_workflow.invoke(1, config)  # 6 (previous was 3 * 2 from the previous invocation)
            ```
        valuesaveN)r5   rJ   rK   __doc__r]   __annotations__r^   r(   r;   r9   finalrf   o  s    	: R	r;   rk   r-   .c                 v   t        j                  |      st        j                  |      rt        d      t	        |      }d}t        j
                  |      }t        t        |j                  j                               d      }|st        d      |j                  |   j                  t         j                  j                  ur|j                  |   j                  nt        }dt        dt        fd}dt        dt        fd}t        t        }
}	|j                  t         j                  j                  ur|j                  t         j"                  u r	t        x}	}
n|t%        |j                        }|t         j"                  u rGt'        |j                        }t)        |      d	k7  rt+        d
      t'        |j                        \  }	}
n|j                  x}	}
t-        |j.                  t1        |t2        gt2        gt5        t7        t8        |      t7        t:        |      g      g      it2        t=        |      t8        t?        |	t8              t:        t?        |
t:              it2        t8        t8        |d| j@                  | jB                  | jD                  | jF                  | jH                  | jJ                        S )zConvert a function into a Pregel graph.

        Args:
            func: The function to convert. Support both sync and async functions.

        Returns:
            A Pregel graph.
        z3Generators are not supported in the Functional API.updatesNz4Entrypoint function must have at least one parameterrg   r.   c                 R    t        | t        j                        r| j                  S | S )zEExtract the return_ value the entrypoint.final object or passthrough.)rX   r`   rk   rg   rg   s    r9   _pluck_return_valuez0entrypoint.__call__.<locals>._pluck_return_value  s     ",UJ4D4D"E5;;P5Pr;   c                 R    t        | t        j                        r| j                  S | S )z?Get save value from the entrypoint.final object or passthrough.)rX   r`   rk   rh   ro   s    r9   _pluck_save_valuez.entrypoint.__call__.<locals>._pluck_save_value  s     !+E:3C3C!D5::O%Or;      zPlease an annotation for both the return_ and the save values.For example, `-> entrypoint.final[int, str]` would assign a return_ a type of `int` and save the type `str`.)mapper)boundtriggerschannelswritersT)nodesrw   input_channelsoutput_channelsstream_channelsstream_modestream_eagerra   rb   r@   r+   retry_policyconfig_type)&inspectisgeneratorfunctionisasyncgenfunctionNotImplementedErrorr   	signaturenextiter
parameterskeys
ValueError
annotation	Signatureemptyr   return_annotationr`   rk   r   r   len	TypeErrorr   r5   r   r   r   r    r   r   r   r   ra   rb   r@   r+   r*   rc   )r7   r-   ru   r}   sigfirst_parameter_name
input_typerp   rr   output_type	save_typeorigintype_annotationss                r9   r?   zentrypoint.__call__  so    &&t,0J0J40P%E  ,D1"+ %#D)<)<)>$?F#STT ~~23>>$$**+ NN/0;; 	 		Qs 	Qs 	Q	PS 	PS 	P "%cY  (9(9(?(?? %%)9)99*--i#C$9$9:Z---'/0E0E'F$+,1'O  .6c6K6K-L*K.1.C.CCK)z#W#W$ 1#>Q R 1(CT U	   ~j1Y{C0)Ix8
 !#**********? 
  	
r;   )NNNNNr(   )r5   rJ   rK   ri   r	   r   r!   r   typer   r#   r   r$   r   r:   r   r"   r   r]   r^   rk   r   r   r?   r(   r;   r9   r`   r`      s    Vt 7;%)%)-1.2;=+23+ 	"+ 	"	+
  S	*+ {++ [(;"778+ 
+" $1 $ $L\
Xc3h/ \
F \
r;   r`   rP   )=r\   concurrent.futuresrY   r2   r   collections.abcr   r   dataclassesr   typingr   r   r   r	   r
   r   r   r   r   langgraph.cache.baser   "langgraph.channels.ephemeral_valuer   langgraph.channels.last_valuer   langgraph.checkpoint.baser   langgraph.constantsr   r   r   r   langgraph.pregelr   langgraph.pregel.callr   r   r   r   r   r   langgraph.pregel.readr   langgraph.pregel.writer   r    langgraph.store.baser!   langgraph.typesr"   r#   r$   r%   r'   rL   rM   rQ   r]   r^   r`   r(   r;   r9   <module>r      s       / !
 
 
 + = 3 9 E E #  - B * L L(71a4= (V 
 AEJN	
3- E+x'<<=> ;x5e3D0D'EFG	
 
8Ay|O$hq!tn456A 
 
HQ	!_5x1~EF!Q$ 
 TXV AEJNVuXa1o%>A%NOPV 3-V E+x'<<=>	V
 ;x5e3D0D'EFGV 	x9Q<((1a4.8	9:QT	 A	Vr CLCLm
 m
r;   