
    (GgJA                        d dl Z d dlZd dlZd dl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 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$ d d
l%m&Z& d dl'm(Z(m)Z) d dl*m+Z+ d dl,m-Z-m.Z.m/Z/ eddddee0   dee.   de
ee
e e	e"   f   e
e e"f   f   ge
e e!e"   f   f   fd       Z1edee
e e	e"   f   e
e e"f   f   de
e e!e"   f   fd       Z1	 dddddeee
e e	e"   f   e
e e"f   f      dee0   dee.   dee
ee
e e	e"   f   e
e e"f   f   ge
e e!e"   f   f   e
e e!e"   f   f   fdZ1 ed      Z2 ed      Z3 G d d      Z4y)    N)	dataclass)
Any	AwaitableCallableGenericOptionalTypeVarUnionget_args
get_originoverload)EphemeralValue)	LastValue)BaseCheckpointSaver)ENDPREVIOUSSTART
TAG_HIDDEN)Pregel)PSyncAsyncFutureTcallget_runnable_for_entrypoint)
PregelNode)ChannelWriteChannelWriteEntry)	BaseStore)
_DC_KWARGSRetryPolicy
StreamModenameretryr#   r$   returnc                      y N r"   s     t/home/kushmeetdev/apache_webroot/langgraph_flaskproject/venv/lib/python3.12/site-packages/langgraph/func/__init__.pytaskr*   %   s         __func_or_none__c                      y r'   r(   )r,   s    r)   r*   r*   0   s     '*r+   c          	      F   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]
        ```
    funcr%   c                 (   Gt        | d      r4t        j                  | j                  | j                        }|_        |} n| _        t        j                  t        |       }t        j                  |dd       t        j                  ||       S )N__func__)r$   _is_pregel_taskT)
hasattr	functoolspartialr1   __self____name__r   object__setattr__update_wrapper)r/   instance_method	call_funcr#   r$   s      r)   	decoratorztask.<locals>.decorator{   s    
 tZ( #,"3"3DMM4=="Q+/(& !%%%dD>	9&7>''	488r+   )	r
   r   r   r   r   
concurrentfuturesFutureasyncio)r,   r#   r$   r=   s    `` r)   r*   r*   6   s    J9HQ	!_-x1~=>9	J&&--a0018Aw~~a?P<P3QQ
9* #)**r+   RSc            	           e Zd ZdZ	 	 	 ddee   dee   deee      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 (str): 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)
        ```
    Ncheckpointerstoreconfig_schemar%   c                 .    || _         || _        || _        y)z$Initialize the entrypoint decorator.N)rF   rG   rH   )selfrF   rG   rH   s       r)   __init__zentrypoint.__init__7  s     )
*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)r7   
__module____qualname____doc__rB   __annotations__rC   r(   r+   r)   finalrM   B  s    	: R	r+   rT   r/   .c                 B   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t<        g      g      it2        t?        |      t8        tA        |	t8              t:        tA        |
t:              it2        t8        t8        |d| jB                  | jD                  | jF                  
      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 parameterrN   r%   c                 R    t        | t        j                        r| j                  S | S )zEExtract the return_ value the entrypoint.final object or passthrough.)
isinstancerE   rT   rN   rN   s    r)   _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   rE   rT   rO   rY   s    r)   _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)tags)boundtriggerschannelswritersT)
nodesrb   input_channelsoutput_channelsstream_channelsstream_modestream_eagerrF   rG   config_type)$inspectisgeneratorfunctionisasyncgenfunctionNotImplementedErrorr   	signaturenextiter
parameterskeys
ValueError
annotation	Signatureemptyr   return_annotationrE   rT   r   r   len	TypeErrorr   r7   r   r   r   r   r   r   r   r   r   rF   rG   rH   )rJ   r/   r`   rh   sigfirst_parameter_name
input_typerZ   r\   output_type	save_typeorigintype_annotationss                r)   __call__zentrypoint.__call__i  s_    &&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+   )NNNr(   )r7   rP   rQ   rR   r   r   r   typer   rK   r   r   r   rB   rC   rT   r   r   r   r(   r+   r)   rE   rE      s    Vt 7;%)-1		+23	+ 	"	+  S	*		+
 
	+ $1 $ $LZ
Xc3h/ Z
F Z
r+   rE   r'   )5rA   concurrent.futuresr>   r4   rk   dataclassesr   typingr   r   r   r   r   r	   r
   r   r   r   "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   langgraph.pregel.readr   langgraph.pregel.writer   r   langgraph.store.baser   langgraph.typesr   r    r!   strr*   rB   rC   rE   r(   r+   r)   <module>r      s       !   > 3 9 @ @ #  - B * ? ? 
 #'
3- K  
8Ay|O$hq!tn456Q""#%	 
 
*HQ	!_5x1~EF*a##$* 
* TX] #'	]uXa1o%>A%NOP] 3-] K 	]
 	x9Q<((1a4.8	9:OA&&'	) Q""#	%]@ CLCLe
 e
r+   