
    g3fiQ                    F   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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-m.Z.m/Z/m0Z0 d dl1m2Z2 d dl3m4Z4m5Z5 d dl6m7Z7m8Z8m9Z9m:Z: d dl;m<Z< d dl=m>Z>m?Z? dZ@ G d dee+e-f         ZAe	 d"dddd	 	 	 	 	 	 	 	 	 	 	 d#d       ZBed$d       ZBed%d       ZB	 d"dddd	 	 	 	 	 	 	 	 	 	 	 d&dZB ed      ZC ed      ZD G d  d!ee<         ZEy)'    )annotationsN)	AwaitableCallableSequence)	dataclass)AnyGenericTypeVarcastget_args
get_originoverload)	BaseCache)BaseCheckpointSaver)	BaseStore)Unpack)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                  F    e Zd Zddd	 	 	 	 	 	 	 	 	 ddZddZd	dZd	dZy)
_TaskFunctionN)cache_policynamec                   |Gt        |d      r4t        j                  |j                  |j                        }||_        |}n||_        || _        || _        || _        t        j                  | |       y )N__func__)
hasattr	functoolspartialr3   __self____name__funcretry_policyr0   update_wrapper)selfr9   r:   r0   r1   instance_methods         U/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langgraph/func/__init__.py__init__z_TaskFunction.__init__/   sm     tZ( #,"3"3DMM4=="Q+/(& !%	((  t,    c                b    t        | j                  g|| j                  | j                  d|S )N)r:   r0   )r   r9   r:   r0   )r<   argskwargss      r>   __call__z_TaskFunction.__call__G   sA    II
 	
****

 
 	
r@   c                |    | j                   0|j                  t        t        | j                        xs dff       yyzClear the cache for this task.N__dynamic__)r0   clearr   r!   r9   r<   caches     r>   clear_cachez_TaskFunction.clear_cacheP   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rF   )r0   aclearr   r!   r9   rI   s     r>   aclear_cachez_TaskFunction.aclear_cacheU   sK     (,,!:dii#8#IMJL   )s   ?A
AA
)
r9   *Callable[P, Awaitable[T]] | Callable[P, T]r:   zSequence[RetryPolicy]r0   ,CachePolicy[Callable[P, str | bytes]] | Noner1   
str | NonereturnNone)rB   zP.argsrC   zP.kwargsrR   zSyncAsyncFuture[T])rJ   r   rR   rS   )r8   
__module____qualname__r?   rD   rK   rN    r@   r>   r/   r/   .   sR     FJ-8- ,	-
 C- - 
-0
V
r@   r/   )r1   r:   r0   c                    y NrV   )__func_or_none__r1   r:   r0   rC   s        r>   r,   r,   ]   s     r@   c                     y rX   rV   rY   s    r>   r,   r,   k   s    NQr@   c                     y rX   rV   r[   s    r>   r,   r,   o   s    CFr@   c                   |j                  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
stacklevelrV   c                "    t        |       S )N)r:   r0   r1   )r/   )r9   r0   r1   retry_policiess    r>   	decoratorztask.<locals>.decorator   s     ~Lt
 	
r@   )r9   rO   rR   zCallable[P, SyncAsyncFuture[T]])getr   warningswarnr*   
isinstancer'   )rY   r1   r:   r0   rC   r^   rf   re   s    ` `   @r>   r,   r,   s   s    V GW--g=[0	

  L  	 lK0 _ 
8
	(
 #)**r@   RSc                      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y)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)
        ```
    Nc                   |j                  dt              x}t        ur5t        j                  dt        d       |t        t        t           |      }|j                  dt              x}	t        ur*t        j                  dt        d       |t        d|	      }|| _	        || _
        || _        || _        || _        || _        y)	z$Initialize the entrypoint decorator.config_schemazW`config_schema` is deprecated and will be removed. Please use `context_schema` instead.r`   ra   Nr^   r_   z#RetryPolicy | Sequence[RetryPolicy])rg   r   rh   ri   r+   r   typer)   r*   checkpointerstorerJ   r0   r:   context_schema)
r<   rq   rr   rJ   rs   r0   r:   rC   ro   r^   s
             r>   r?   zentrypoint.__init__  s     $ZZAAM'QMMi4
 %!%d8nm!DZZ11E'AMM_4
 ##$I5Q(

((,r@   c                  (    e Zd ZU dZded<   	 d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 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)
            ```
        rk   valuerl   saveN)r8   rT   rU   __doc____annotations__rV   r@   r>   finalru     s    	> T	r@   rz   c                L   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d}d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        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                  xs d| 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 parameterc                R    t        | t        j                        r| j                  S | S )zEExtract the return_ value the entrypoint.final object or passthrough.)rj   r-   rz   rv   rv   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.)rj   r-   rz   rw   r~   s    r>   _pluck_save_valuez.entrypoint.__call__.<locals>._pluck_save_value  s     !+E:3C3C!D5::O%Or@   r`   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writersTrV   )nodesr   input_channelsoutput_channelsstream_channelsstream_modestream_eagerrq   rr   rJ   r0   r:   rs   )rv   r   rR   r   )&inspectisgeneratorfunctionisasyncgenfunctionNotImplementedErrorr    	signaturenextiter
parameterskeys
ValueError
annotation	Signatureemptyr   return_annotationr-   rz   r   r   len	TypeErrorr   r8   r"   r   r#   r$   r   r   r   r   rq   rr   rJ   r0   r:   rs   )r<   r9   r   r   sigfirst_parameter_name
input_typer   r   output_type	save_typeorigintype_annotationss                r>   rD   zentrypoint.__call__  sT    &&t,0J0J40P%E  ,D1"+ %#D)<)<)>$?F#STT ~~23>>$$**+ NN/0;; 	 		Q	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"$ 1#>Q R 1(CT U	   ~j1Y{C0)Ix8
 !#**********0b..? 
  	
r@   )NNNNNN)rq   zBaseCheckpointSaver | Nonerr   zBaseStore | NonerJ   zBaseCache | Noners   ztype[ContextT] | Noner0   zCachePolicy | Noner:   *RetryPolicy | Sequence[RetryPolicy] | NonerC   Unpack[DeprecatedKwargs]rR   rS   rV   )r9   zCallable[..., Any]rR   r   )r8   rT   rU   rx   r?   r   r%   r	   rk   rl   rz   rD   rV   r@   r>   r-   r-      s    cN 48"&"&04+/CG"-0"-  "-  	"-
 ."- )"- A"- +"- 
"-H &1 & &P\
r@   r-   rX   )rY   rS   r1   rQ   r:   r   r0   rP   rC   r   rR   zKCallable[[Callable[P, Awaitable[T]] | Callable[P, T]], _TaskFunction[P, T]])rY   zCallable[P, Awaitable[T]]rR   _TaskFunction[P, T])rY   zCallable[P, T]rR   r   )rY   z1Callable[P, Awaitable[T]] | Callable[P, T] | Noner1   rQ   r:   r   r0   rP   rC   r   rR   zaCallable[[Callable[P, Awaitable[T]] | Callable[P, T]], _TaskFunction[P, T]] | _TaskFunction[P, T])F
__future__r   r5   r   rh   collections.abcr   r   r   dataclassesr   typingr   r	   r
   r   r   r   r   langgraph.cache.baser   langgraph.checkpoint.baser   langgraph.store.baser   typing_extensionsr   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__r/   r,   rk   rl   r-   rV   r@   r>   <module>r      s   "    9 9 !   + 9 * $ D A = 3 * #  . C L L % W
 ,GAqDM ,^ 
!
 ?CAE

 
 =	

 ?
 '

 

 
 Q 
 Q 
 F 
 F KOf ?CAEfGf f =	f
 ?f 'ffR CLCLO
" O
r@   