
    }
i,T                    ^   d dl mZ d dlZd dlZd dlZd dl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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 d dlmZmZ d dl m!Z!m"Z" d dl#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/m0Z0m1Z1m2Z2 d dl3m4Z4 d dl5m6Z6m7Z7 d dl8m9Z9m:Z:m;Z;m<Z< d dl=m>Z> d dl?m@Z@mAZA dZB G d dee-e/f                   ZCe	 d4ddddd5d'            ZDed6d*            ZDed7d,            ZD	 d4ddddd8d/ZD ed0          ZE ed1          ZF G d2 d3ee>                   ZGdS )9    )annotationsN)	AwaitableCallableSequence)	dataclass)AnyGenericTypeVarcastget_args
get_originoverload)	BaseCache)BaseCheckpointSaver)	BaseStore)Unpack)_serde)CACHE_NS_WRITESPREVIOUS)MISSINGDeprecatedKwargs)EphemeralValue)	LastValue)ENDSTART)Pregel)PSyncAsyncFutureTcallget_runnable_for_entrypoint
identifier)
PregelNode)ChannelWriteChannelWriteEntry)
_DC_KWARGSCachePolicyRetryPolicy
StreamMode)ContextT)LangGraphDeprecatedSinceV05LangGraphDeprecatedSinceV10)task
entrypointc                  6    e Zd ZdddddZddZddZddZdS )_TaskFunctionN)cache_policynamefunc*Callable[P, Awaitable[T]] | Callable[P, T]retry_policySequence[RetryPolicy]r1   ,CachePolicy[Callable[P, str | bytes]] | Noner2   
str | NonereturnNonec                   |@t          |d          r)t          j        |j        |j                  }||_        |}n||_        || _        || _        || _        t          j	        | |           d S )N__func__)
hasattr	functoolspartialr<   __self____name__r3   r5   r1   update_wrapper)selfr3   r5   r1   r2   instance_methods         C:\Users\Dell Inspiron 16\Desktop\tws\AgrotaPowerBi\back-agrota-powerbi\mcp-client-agrota\venv\Lib\site-packages\langgraph/func/__init__.py__init__z_TaskFunction.__init__0   s|     tZ(( 	% #,"3DM4="Q"Q+/(& !%	(( t,,,,,    argsP.argskwargsP.kwargsSyncAsyncFuture[T]c                F    t          | j        g|R | j        | j        d|S )N)r5   r1   )r    r3   r5   r1   )rC   rH   rJ   s      rE   __call__z_TaskFunction.__call__H   sH    I
 	
 
**
 

 
 
 	
rG   cacher   c                z    | j         3|                    t          t          | j                  pdff           dS dS zClear the cache for this task.N__dynamic__)r1   clearr   r"   r3   rC   rO   s     rE   clear_cachez_TaskFunction.clear_cacheQ   sB    (KK/:di+@+@+QMRTUUUUU )(rG   c                   K   | j         9|                    t          t          | j                  pdff           d{V  dS dS rQ   )r1   aclearr   r"   r3   rT   s     rE   aclear_cachez_TaskFunction.aclear_cacheV   so      (,,!:di#8#8#IMJL           )(rG   )
r3   r4   r5   r6   r1   r7   r2   r8   r9   r:   )rH   rI   rJ   rK   r9   rL   )rO   r   r9   r:   )rA   
__module____qualname__rF   rN   rU   rX    rG   rE   r0   r0   /   s|         FJ- - - - - -0
 
 
 
V V V V
     rG   r0   )r2   r5   r1   __func_or_none__r:   r2   r8   r5   *RetryPolicy | Sequence[RetryPolicy] | Noner1   r7   rJ   Unpack[DeprecatedKwargs]r9   KCallable[[Callable[P, Awaitable[T]] | Callable[P, T]], _TaskFunction[P, T]]c                   d S Nr[   )r\   r2   r5   r1   rJ   s        rE   r-   r-   ^   s	     3rG   Callable[P, Awaitable[T]]_TaskFunction[P, T]c                    d S ra   r[   r\   s    rE   r-   r-   l   s    NQcrG   Callable[P, T]c                    d S ra   r[   re   s    rE   r-   r-   p   s    CF3rG   1Callable[P, Awaitable[T]] | Callable[P, T] | NoneaCallable[[Callable[P, Awaitable[T]] | Callable[P, T]], _TaskFunction[P, T]] | _TaskFunction[P, T]c                   |                     dt                    x}t          ur t          j        dt          d           ||}|dnt          |t                    r|fn|dfd}|  ||           S |S )aS  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:
        name: An optional name for the task. If not provided, the function name will be used.
        retry_policy: An optional retry policy (or list of policies) to use for the task in case of a failure.
        cache_policy: An optional cache policy to use for the task. This allows caching of the task results.

    Returns:
        A callable function when used as a decorator.

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


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


        @entrypoint()
        def add_one(numbers: list[int]) -> list[int]:
            futures = [add_one_task(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_task(a: int) -> int:
            return a + 1


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


        # Call the entrypoint
        await add_one.ainvoke([1, 2, 3])  # Returns [2, 3, 4]
        ```
    retryM`retry` is deprecated and will be removed. Please use `retry_policy` instead.   category
stacklevelNr[   r3   r4   r9   Callable[P, SyncAsyncFuture[T]]c                *    t          |           S )N)r5   r1   r2   )r0   )r3   r1   r2   retry_policiess    rE   	decoratorztask.<locals>.decorator   s%     ~Lt
 
 
 	
rG   )r3   r4   r9   rq   )getr   warningswarnr+   
isinstancer(   )r\   r2   r5   r1   rJ   rk   rt   rs   s    ` `   @rE   r-   r-   t   s    V GW---g==[0	
 	
 	
 	

  L  	 lK00l__ 
 
 
 
 
 
 
 
 #y)***rG   RSc                  x    e Zd ZdZ	 	 	 	 	 	 dddZ edi e G d deee	f                               Z
ddZdS )r.   a  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                                                                                          |
    |------------------|------------------------------------------------------------------------------------------------------|
    | **`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).     |
    | **`runtime`**    | A `Runtime` object that contains information about the current run, including context, store, writer |

    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.
        cache: A cache to use for caching the results of the workflow.
        context_schema: Specifies the schema for the context object that will be
            passed to the workflow.
        cache_policy: A cache policy to use for caching the results of the workflow.
        retry_policy: A retry policy (or list of policies) to use for the workflow in case of a failure.

    !!! warning "`config_schema` Deprecated"
        The `config_schema` parameter is deprecated in v0.6.0 and support will be removed in v2.0.0.
        Please use `context_schema` instead to specify the schema for run-scoped context.


    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 InMemorySaver

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

        @entrypoint(checkpointer=InMemorySaver())
        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 typing import Optional

        from langgraph.checkpoint.memory import MemorySaver

        from langgraph.func import entrypoint


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


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

    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 typing import Any

        from langgraph.checkpoint.memory import MemorySaver

        from langgraph.func import entrypoint


        @entrypoint(checkpointer=InMemorySaver())
        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BaseCheckpointSaver | NonestoreBaseStore | NonerO   BaseCache | Nonecontext_schematype[ContextT] | Noner1   CachePolicy | Noner5   r]   rJ   r^   r9   r:   c                   |                     dt                    x}t          ur>t          j        dt          d           | t          t          t                   |          }|                     dt                    x}	t          ur.t          j        dt          d           |t          d|	          }|| _	        || _
        || _        || _        || _        || _        dS )	z$Initialize the entrypoint decorator.config_schemazW`config_schema` is deprecated and will be removed. Please use `context_schema` instead.rm   rn   Nrk   rl   z#RetryPolicy | Sequence[RetryPolicy])ru   r   rv   rw   r,   r   typer*   r+   r|   r~   rO   r1   r5   r   )
rC   r|   r~   rO   r   r1   r5   rJ   r   rk   s
             rE   rF   zentrypoint.__init__  s     $ZZAAAM'QQMi4   
 %!%d8nm!D!DZZ111E'AAM_4   
 ##$I5QQ(

((,rG   c                  *    e Zd ZU dZded<   	 ded<   dS )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 InMemorySaver
            from langgraph.func import entrypoint


            @entrypoint(checkpointer=InMemorySaver())
            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)
            ```
        ry   valuerz   saveN)rA   rY   rZ   __doc____annotations__r[   rG   rE   finalr     s7         	 	> 	T	 	rG   r   r3   Callable[..., Any]r   c                   t          j        |          st          j        |          rt          d          t	          |          }d}t          j        |          }t          t          |j        	                                          d          }|st          d          |j        |         j        t           j        j        ur|j        |         j        nt          }dd}dd	}t          t          }
}	|j        t           j        j        ur|j        t           j        u r
t          x}	}
nyt%          |j                  }|t           j        u rNt'          |j                  }t)          |          d
k    rt+          d          t'          |j                  \  }	}
n	|j        x}	}
t-          |j        t1          |t2          gt2          t5          t7          t8          |          t7          t:          |          g          g          it2          t=          |          t8          t?          |	t8                    t:          t?          |
t:                    it2          t8          t8          |d| j         | j!        | j"        | j#        | j$        pd| j%                  }tL          j'        rVtM          j(        ||	|
g| j%        | j%        gng z   |j)                  }||_*        tM          j+        |j         |          |_         |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 parameterr   r   r9   c                H    t          | t          j                  r| j        n| S )zEExtract the return_ value the entrypoint.final object or passthrough.)rx   r.   r   r   r   s    rE   _pluck_return_valuez0entrypoint.__call__.<locals>._pluck_return_value  s     ",UJ4D"E"EP5;;5PrG   c                H    t          | t          j                  r| j        n| S )z?Get save value from the entrypoint.final object or passthrough.)rx   r.   r   r   r   s    rE   _pluck_save_valuez.entrypoint.__call__.<locals>._pluck_save_value  s     !+E:3C!D!DO5::%OrG   rm   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writersTr[   )nodesr   input_channelsoutput_channelsstream_channelsstream_modestream_eagerr|   r~   rO   r1   r5   r   )schemasr   )r   r   r9   r   ),inspectisgeneratorfunctionisasyncgenfunctionNotImplementedErrorr!   	signaturenextiter
parameterskeys
ValueError
annotation	Signatureemptyr   return_annotationr.   r   r   r   len	TypeErrorr   rA   r#   r   r$   r%   r   r   r   r   r|   r~   rO   r1   r5   r   r   STRICT_MSGPACK_ENABLEDbuild_serde_allowlistr   _serde_allowlistapply_checkpointer_allowlist)rC   r3   r   r   sigfirst_parameter_name
input_typer   r   output_type	save_typeorigintype_annotationsgraphserde_allowlists                  rE   rN   zentrypoint.__call__  s-    &t,, 	0J40P0P 	%E   ,D11"+ %%#D)<)<)>)>$?$?FF# 	USTTT ~23>$*+ + N/0;; 	 		Q 	Q 	Q 	Q	P 	P 	P 	P "%cY (9(??? %)999*--ii#C$9::Z---'/0E'F'F$+,,11'O   .6c6K-L-L*K.1.CCK)17z#W"$ 1#>Q R R R 1(CT U U U 	       ~j11Y{C00)Ix88
 !#*****0b.? 2
  2
  2
B ( 		$:#[)<,0,?,KD'((QSU  O
 &5E"!'!D"O" "E rG   )NNNNNN)r|   r}   r~   r   rO   r   r   r   r1   r   r5   r]   rJ   r^   r9   r:   r[   )r3   r   r9   r   )rA   rY   rZ   r   rF   r   r&   r	   ry   rz   r   rN   r[   rG   rE   r.   r.      s        c cN 48"&"&04+/CG"- "- "- "- "-H Y& & & & &1 & & &Pg g g g g grG   r.   ra   )r\   r:   r2   r8   r5   r]   r1   r7   rJ   r^   r9   r_   )r\   rb   r9   rc   )r\   rf   r9   rc   )r\   rh   r2   r8   r5   r]   r1   r7   rJ   r^   r9   ri   )H
__future__r   r>   r   rv   collections.abcr   r   r   dataclassesr   typingr   r	   r
   r   r   r   r   langgraph.cache.baser   langgraph.checkpoint.baser   langgraph.store.baser   typing_extensionsr   langgraph._internalr   langgraph._internal._constantsr   r   langgraph._internal._typingr   r   "langgraph.channels.ephemeral_valuer   langgraph.channels.last_valuer   langgraph.constantsr   r   langgraph.pregelr   langgraph.pregel._callr   r   r   r    r!   r"   langgraph.pregel._readr#   langgraph.pregel._writer$   r%   langgraph.typesr&   r'   r(   r)   langgraph.typingr*   langgraph.warningsr+   r,   __all__r0   r-   ry   rz   r.   r[   rG   rE   <module>r      s   " " " " " "       9 9 9 9 9 9 9 9 9 9 ! ! ! ! ! !                  + * * * * * 9 9 9 9 9 9 * * * * * * $ $ $ $ $ $ & & & & & & D D D D D D D D A A A A A A A A = = = = = = 3 3 3 3 3 3 * * * * * * * * # # # # # #                . - - - - - C C C C C C C C L L L L L L L L L L L L % % % % % % W W W W W W W W
 , , , , ,GAqDM , , ,^ 
!
 ?CAE
 
 
 
 
 

 
 Q Q Q 
 Q 
 F F F 
 F KOf ?CAEf f f f f fR GCLLGCLLZ Z Z Z Z" Z Z Z Z ZrG   