
    9i              
         d dl mZ 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 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 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 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-m.Z.m/Z/m0Z0 d dl1m2Z2m3Z3m4Z4m5Z5 d dl6m7Z7m8Z8m9Z9 d dl:m;Z; d dl<m=Z= d dl>m?Z?m@Z@mAZA d dlBmCZC d dlDmEZE d dlFmGZG d dlHmIZImJZJ d dlKmLZLmMZM d dlNmOZOmPZPmQZQ d dlRmSZSmTZTmUZUmVZV d dlWmXZX d dlYmZZZm[Z[ d dl\m]Z]m^Z^ d dl_m`Z` d d lambZbmcZc d d!ldmeZemfZfmgZg d d"lhmiZimjZjmkZkmlZlmmZmmnZn d d#lompZpmqZqmrZrmsZsmtZt d d$lumvZvmwZw d%Zx ej                  ez      Z{d&Z|d<d'Z}d=d(Z~ G d) d*eetepeqesf         Z G d+ d,e`etepeqesf   eetepeqesf         Z	 	 	 	 	 	 d>d-Zd?d.Zd@d/Z	 	 	 	 dAd0ZdBd1Z	 	 	 	 dCd2Ze	 	 	 	 	 	 	 	 dDd3       Zed4d5	 	 	 	 	 	 	 dEd6       Zd4d5	 	 	 	 	 	 	 dFd7ZdGd8ZdHd9ZdId:Z	 	 	 	 	 	 	 	 	 	 dJd;Zy)K    )annotationsN)defaultdict)	AwaitableCallableHashableSequence)partial)isclass
isfunctionismethod	signature)FunctionType)NoneType)	AnyGenericLiteralUnioncastget_args
get_originget_type_hintsoverload)RunnableRunnableConfig)	BaseCache)
Checkpoint)	BaseStore)	BaseModelTypeAdapter)NotRequiredRequiredSelfUnpackis_typeddict)	INTERRUPTNS_ENDNS_SEPTASKS)get_cached_annotated_keysget_field_defaultget_update_as_tuples)create_model)coerce_to_runnable)	EMPTY_SEQMISSINGDeprecatedKwargs)BaseChannel)BinaryOperatorAggregate)EphemeralValue)	LastValueLastValueAfterFinish)NamedBarrierValueNamedBarrierValueAfterFinish)ENDSTART
TAG_HIDDEN)	ErrorCodeInvalidUpdateErrorParentCommandcreate_error_message)
BranchSpec)	StateNodeStateNodeSpec)ManagedValueSpecis_managed_value)Pregel)ChannelRead
PregelNode)ChannelWriteChannelWriteEntryChannelWriteTupleEntry)AllCachePolicyCheckpointerCommandRetryPolicySend)ContextTInputT
NodeInputTOutputTStateT)LangGraphDeprecatedSinceV05LangGraphDeprecatedSinceV10)
StateGraphCompiledStateGraphzbranch:to:{}c                    t        | t              ry t        j                  |       ry t	        j
                  d|  d       y )NzInvalid state_schema: z. Expected a type or Annotated[type, reducer]. Please provide a valid schema to ensure correct updates.
 See: https://langchain-ai.github.io/langgraph/reference/graphs/#stategraph)
isinstancetypetypingr   warningswarn)schemas    _/var/www/html/backtest/airagagent/rag_env/lib/python3.12/site-packages/langgraph/graph/state.py_warn_invalid_state_schemara   \   s=    &$vMM
  )V 	V    c                    	 t        | d| j                  j                        S # t        $ r t	        dt        |              w xY w)N__name__zUnsupported node type: )getattr	__class__rd   AttributeError	TypeErrorr[   )nodes    r`   _get_node_namerj   h   sI    @tZ)@)@AA @1$t*>??@s	    # !Ac                     e Zd ZU dZded<   ded<   ded<   ded	<   d
ed<   ded<   ded<   ded<   ded<   ded<   ded<   ded<   	 d0ddd	 	 	 	 	 	 	 	 	 	 	 d1dZed2d       Zd3d4dZe	ddddddd 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d5d!       Z
e	dddddd"	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d6d#       Z
e	ddddddd 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d7d$       Z
e		 d0dddddd"	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d8d%       Z
	 d0ddddddd 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d9d&Z
d:d'Z	 d0	 	 	 	 	 	 	 d;d(Z	 	 	 	 d<d)Zd=d*Z	 d0	 	 	 	 	 d>d+Zd=d,Zd0d?d-Z	 d0ddddddd.	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d@d/Zy)ArW   a	  A graph whose nodes communicate by reading and writing to a shared state.

    The signature of each node is `State -> Partial<State>`.

    Each state key can optionally be annotated with a reducer function that
    will be used to aggregate the values of that key received from multiple nodes.
    The signature of a reducer function is `(Value, Value) -> Value`.

    !!! warning

        `StateGraph` is a builder class and cannot be used directly for execution.
        You must first call `.compile()` to create an executable graph that supports
        methods like `invoke()`, `stream()`, `astream()`, and `ainvoke()`. See the
        `CompiledStateGraph` documentation for more details.

    Args:
        state_schema: The schema class that defines the state.
        context_schema: The schema class that defines the runtime context.

            Use this to expose immutable context data to your nodes, like `user_id`, `db_conn`, etc.
        input_schema: The schema class that defines the input to the graph.
        output_schema: The schema class that defines the output from the graph.

    !!! 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:
        ```python
        from langchain_core.runnables import RunnableConfig
        from typing_extensions import Annotated, TypedDict
        from langgraph.checkpoint.memory import InMemorySaver
        from langgraph.graph import StateGraph
        from langgraph.runtime import Runtime


        def reducer(a: list, b: int | None) -> list:
            if b is not None:
                return a + [b]
            return a


        class State(TypedDict):
            x: Annotated[list, reducer]


        class Context(TypedDict):
            r: float


        graph = StateGraph(state_schema=State, context_schema=Context)


        def node(state: State, runtime: Runtime[Context]) -> dict:
            r = runtime.context.get("r", 1.0)
            x = state["x"][-1]
            next_value = x * r * (1 - x)
            return {"x": next_value}


        graph.add_node("A", node)
        graph.set_entry_point("A")
        graph.set_finish_point("A")
        compiled = graph.compile()

        step1 = compiled.invoke({"x": 0.5}, context={"r": 3.0})
        # {'x': [0.5, 0.75]}
        ```
    set[tuple[str, str]]edgesz'dict[str, StateNodeSpec[Any, ContextT]]nodesz'defaultdict[str, dict[str, BranchSpec]]brancheszdict[str, BaseChannel]channelszdict[str, ManagedValueSpec]managedz:dict[type[Any], dict[str, BaseChannel | ManagedValueSpec]]schemasz set[tuple[tuple[str, ...], str]]waiting_edgesboolcompiledtype[StateT]state_schematype[ContextT] | Nonecontext_schemaztype[InputT]input_schemaztype[OutputT]output_schemaN)rz   r{   c                  |j                  dt              x}t        ur5t        j                  dt        d       |t        t        t           |      }|j                  dt              x}t        ur5t        j                  dt        d       |t        t        t           |      }|j                  dt              x}t        ur5t        j                  dt        d       |t        t        t           |      }i | _        t               | _        t        t              | _        i | _        i | _        i | _        d	| _        t               | _        || _        t        t        t           |xs |      | _        t        t        t           |xs |      | _        || _        | j5                  | j,                         | j5                  | j.                  d	
       | j5                  | j0                  d	
       y )Nconfig_schemazW`config_schema` is deprecated and will be removed. Please use `context_schema` instead.   )category
stacklevelinputM`input` is deprecated and will be removed. Please use `input_schema` instead.outputzO`output` is deprecated and will be removed. Please use `output_schema` instead.Fallow_managed)getr/   r]   r^   rV   r   r[   rP   rU   rQ   rS   rn   setrm   r   dictro   rr   rp   rq   ru   rs   rw   rz   r{   ry   _add_schema)	selfrw   ry   rz   r{   kwargsr}   input_r   s	            r`   __init__zStateGraph.__init__   s    $ZZAAM'QMMi4
 %!%d8nm!Djj'22F7BMM_4
 ##DL&9jj733FGCMMa4
 $ $T']F ;
U
#D) U( f|/K|L!$w-1N,O,**+**%@++5Arb   c           	     ~    | j                   | j                  D ch c]  \  }}|D ]  }||f  c}}}z  S c c}}}w N)rm   rs   )r   startsendstarts       r`   
_all_edgeszStateGraph._all_edges   sP    zz,0,>,>
 
(VSF
CHUCL

 
 	
 
s   8
c               d   || j                   vr!t        |       t        |      \  }}}|r2|s0dj                  |      }t	        |dd      }t        d| d| d      i ||| j                   |<   |j                         D ]U  \  }}	|| j                  v r3| j                  |   |	k7  s't        |	t              r8t        d| d      |	| j                  |<   W |j                         D ]D  \  }}|| j                  v r"| j                  |   |k7  s't        d	| d      || j                  |<   F y y )
Nz, rd    z%Invalid managed channels detected in z: z<. Managed channels are not permitted in Input/Output schema.z	Channel 'z&' already exists with a different typezManaged value ')rr   ra   _get_channelsjoinre   
ValueErroritemsrp   rZ   r4   rq   )
r   r_   r   rp   rq   
type_hintsnamesschema_namekeychannels
             r`   r   zStateGraph._add_schema   s^   %&v.,9&,A)Hgz}		'*%fj"= ;K=5' RR R  $;h#:'#:DLL  ( 0 
1W$--'}}S)W4%gy9 ","+C50V W#  *1DMM#&
1 !( 0W$,,&||C(G3(-cU2XY  )0DLL%0- &rb   F)defermetadatarz   retry_policycache_policydestinationsc                    y)zAdd a new node to the `StateGraph`, input schema is inferred as the state schema.
        Will take the name of the function/runnable as the node name.
        N 	r   ri   r   r   rz   r   r   r   r   s	            r`   add_nodezStateGraph.add_node         	rb   )r   r   r   r   r   c                    y)zAdd a new node to the `StateGraph`, input schema is specified.
        Will take the name of the function/runnable as the node name.
        Nr   r   s	            r`   r   zStateGraph.add_node2  r   rb   c                    y)zQAdd a new node to the `StateGraph`, input schema is inferred as the state schema.Nr   
r   ri   actionr   r   rz   r   r   r   r   s
             r`   r   zStateGraph.add_nodeD       	rb   c                    y)z>Add a new node to the `StateGraph`, input schema is specified.Nr   r   s
             r`   r   zStateGraph.add_nodeU  r   rb   c                  |	j                  dt              x}
t        urt        j                  dt               ||
}|	j                  dt              x}t        ur7t        j                  dt               |t        t        t           dz  |      }t        |t              sQ|}t        |t              r|j                         }n!t        |d|j                  j                        }|t        d      | j                   rt"        j%                  d	       t        |t              s5|}t        t        t        |d
t        |dd                  }|t        d      |t&        || j(                  v rt        d| d      |t*        k(  s	|t,        k(  rt        d| d      t.        t0        fD ]  }||v st        d| d       d}t2        }	 t5        |      s"t7        |      st7        t        |dd            r0t9        t        |d            xs t9        |      x}r|}t;        t=        t?        j@                  t        tB        |            jD                  jG                                     }|j                  |      x}rt        |t              rt9        |      r|}|j                  d      x}rytI        |      }|tJ        u r+tM        |      }|D ]  }tI        |      }|tN        u s|}|} n |tN        u r3tM        |      x}r&tI        |d         tP        u rtM        |d         x}r|}||}|9tY        t        tZ        f   t]        ||d      ||||||      | j(                  |<   np|,tY        t]        ||d      ||||||      | j(                  |<   nBtY        t^        tZ        f   t]        ||d      || j`                  ||||      | j(                  |<   |xs |}|| jc                  |       | S # tR        tT        tV        f$ r Y w xY w)a	  Add a new node to the `StateGraph`.

        Args:
            node: The function or runnable this node will run.

                If a string is provided, it will be used as the node name, and action will be used as the function or runnable.
            action: The action associated with the node.
                Will be used as the node function or runnable if `node` is a string (node name).
            defer: Whether to defer the execution of the node until the run is about to end.
            metadata: The metadata associated with the node.
            input_schema: The input schema for the node. (Default: the graph's state schema)
            retry_policy: The retry policy for the node.

                If a sequence is provided, the first matching policy will be applied.
            cache_policy: The cache policy for the node.
            destinations: Destinations that indicate where a node can route to.

                Useful for edgeless graphs with nodes that return `Command` objects.

                If a `dict` is provided, the keys will be used as the target node names and the values will be used as the labels for the edges.

                If a `tuple` is provided, the values will be used as the target node names.

                !!! note

                    This is only used for graph rendering and doesn't have any effect on the graph execution.

        Example:
            ```python
            from typing_extensions import TypedDict

            from langchain_core.runnables import RunnableConfig
            from langgraph.graph import START, StateGraph


            class State(TypedDict):
                x: int


            def my_node(state: State, config: RunnableConfig) -> State:
                return {"x": state["x"] + 1}


            builder = StateGraph(State)
            builder.add_node(my_node)  # node name will be 'my_node'
            builder.add_edge(START, "my_node")
            graph = builder.compile()
            graph.invoke({"x": 1})
            # {'x': 2}
            ```

        Example: Customize the name:
            ```python
            builder = StateGraph(State)
            builder.add_node("my_fair_node", my_node)
            builder.add_edge(START, "my_fair_node")
            graph = builder.compile()
            graph.invoke({"x": 1})
            # {'x': 2}
            ```

        Returns:
            Self: The instance of the `StateGraph`, allowing for method chaining.
        retryzM`retry` is deprecated and will be removed. Please use `retry_policy` instead.)r   Nr   r   rd   z6Node name must be provided if action is not a functionzjAdding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.namezNode `z` already present.z` is reserved.'z?' is a reserved character and is not allowed in the node names.__call__returnr   Fr   trace)rz   r   r   endsr   )2r   r/   r]   r^   rU   r   r[   rR   rZ   strr   get_namere   rf   rd   r   ru   loggerwarningRuntimeErrorrn   r8   r9   r'   r&   r.   r   r   r   nextiterinspectr   r   
parameterskeysr   r   r   rM   r   	NameErrorrh   StopIterationrA   rP   r-   rT   rw   r   )r   ri   r   r   r   rz   r   r   r   r   r   r   	characterinferred_input_schemar   hintsfirst_parameter_name
input_hintrtn
rtn_originrtn_argsarg
arg_originrargsvalss                            r`   r   zStateGraph.add_nodef  s-   Z ZZ11E'AMM_4 #$jj'22F7BMM_4 ##D$4t$;VD$$F&(+(vz63C3C3L3LM| L  ==NN: $$FWVVWVZQU5VWXD| L  >4::vdV+=>??3;$%-vdV>:;; &) 	ID  	{"ab 	 !%1:*	6"F#GFJ=>'
(CD *!&)* *  '+/#-- $\6 :(j,( &+YY/C%DDzD%j$7N:<V4>1))H--3-!+CJ!U*#+C=#+ &C)3CJ)W4&)-7
 %& #g-&.sm3U3&uQx0G;%-eAh%77T7# #D#,Z-AB"6EB))) DJJt #.,"6EB2)) DJJt  -VX-=>"6EB!..)) DJJt $<'<#\*S 9m4 		s   DO4 (AO4 4P
Pc                   | j                   rt        j                  d       t        |t              r|t
        k(  rt        d      |t        k(  rt        d      t        | d      s-|t        d | j                  D              v rt        d| d      | j                  j                  ||f       | S |D ]3  }|t
        k(  rt        d      || j                  vs&t        d| d	       |t        k(  rt        d      |t
        k7  r|| j                  vrt        d| d	      | j                  j                  t        |      |f       | S )
a  Add a directed edge from the start node (or list of start nodes) to the end node.

        When a single start node is provided, the graph will wait for that node to complete
        before executing the end node. When multiple start nodes are provided,
        the graph will wait for ALL of the start nodes to complete before executing the end node.

        Args:
            start_key: The key(s) of the start node(s) of the edge.
            end_key: The key of the end node of the edge.

        Raises:
            ValueError: If the start key is `'END'` or if the start key or end key is not present in the graph.

        Returns:
            Self: The instance of the `StateGraph`, allowing for method chaining.
        kAdding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.zEND cannot be a start nodezSTART cannot be an end noderp   c              3  &   K   | ]	  \  }}|  y wr   r   ).0r   _s      r`   	<genexpr>z&StateGraph.add_edge.<locals>.<genexpr>[  s      B"%Bs   zAlready found path for node 'zB'.
For multiple edges, use StateGraph with an Annotated state key.zNeed to add_node `z` first)ru   r   r   rZ   r   r8   r   r9   hasattrr   rm   addrn   rs   tuple)r   	start_keyend_keyr   s       r`   add_edgezStateGraph.add_edge=  s`   " ==NN:
 i%C !=>>% !>?? 4,c B&*jjB ? 2 !3I; ?V V 
 JJNNIw/0K 	FE| !=>>DJJ& #5eWG!DEE		F
 e:;;c>gTZZ71''BCCi 0':;rb   c                   | j                   rt        j                  d       t        |dd      }|j                  xs d}|| j
                  |   v rt        d|j                   d| d      t        j                  ||d      | j
                  |   |<   | j
                  |   |   j                  x}r| j                  |       | S )	a  Add a conditional edge from the starting node to any number of destination nodes.

        Args:
            source: The starting node. This conditional edge will run when
                exiting this node.
            path: The callable that determines the next node or nodes.

                If not specifying `path_map` it should return one or more nodes.

                If it returns `'END'`, the graph will stop execution.
            path_map: Optional mapping of paths to node names.

                If omitted the paths returned by `path` should be node names.

        Returns:
            Self: The instance of the graph, allowing for method chaining.

        !!! warning
            Without type hints on the `path` function's return value (e.g., `-> Literal["foo", "__end__"]:`)
            or a path_map, the graph visualization assumes the edge could transition to any node in the graph.

        r   NTr   	conditionzBranch with name `z` already exists for node ``)ru   r   r   r-   r   ro   r   r?   	from_pathrz   r   )r   sourcepathpath_mapr   r_   s         r`   add_conditional_edgesz StateGraph.add_conditional_edgess  s    < ==NN: "$T>yy'K4==(($TYYK/J6(RST  '1&:&:44&Pfd#]]6*40===6=V$rb   c                2   t        |      dk  rt        d      d}|D ]v  }t        |t              rt        |      dk(  r|\  }}nt	        |      }|| j
                  v rt        d| d      | j                  ||       || j                  ||       |}x | S )a  Add a sequence of nodes that will be executed in the provided order.

        Args:
            nodes: A sequence of `StateNode` (callables that accept a `state` arg) or `(name, StateNode)` tuples.

                If no names are provided, the name will be inferred from the node object (e.g. a `Runnable` or a `Callable` name).

                Each node will be executed in the order provided.

        Raises:
            ValueError: If the sequence is empty.
            ValueError: If the sequence contains duplicate node names.

        Returns:
            Self: The instance of the `StateGraph`, allowing for method chaining.
           z$Sequence requires at least one node.Nr~   z/Node names must be unique: node with the name 'z' already exists. If you need to use two different runnables/callables with the same name (for example, using `lambda`), please provide them as tuples (name, runnable/callable).)lenr   rZ   r   rj   rn   r   r   )r   rn   previous_nameri   r   s        r`   add_sequencezStateGraph.add_sequence  s    . u:>CDD$( 	!D$&3t9>!
d%d+tzz! EdV Lv v 
 MM$%(mT2 M!	!$ rb   c                .    | j                  t        |      S )a+  Specifies the first node to be called in the graph.

        Equivalent to calling `add_edge(START, key)`.

        Parameters:
            key (str): The key of the node to set as the entry point.

        Returns:
            Self: The instance of the graph, allowing for method chaining.
        )r   r9   r   r   s     r`   set_entry_pointzStateGraph.set_entry_point  s     }}UC((rb   c                0    | j                  t        ||      S )a  Sets a conditional entry point in the graph.

        Args:
            path: The callable that determines the next node or nodes.

                If not specifying `path_map` it should return one or more nodes.

                If it returns END, the graph will stop execution.
            path_map: Optional mapping of paths to node names.

                If omitted the paths returned by `path` should be node names.

        Returns:
            Self: The instance of the graph, allowing for method chaining.
        )r   r9   )r   r   r   s      r`   set_conditional_entry_pointz&StateGraph.set_conditional_entry_point  s    , ))%x@@rb   c                .    | j                  |t              S )a0  Marks a node as a finish point of the graph.

        If the graph reaches this node, it will cease execution.

        Parameters:
            key (str): The key of the node to set as the finish point.

        Returns:
            Self: The instance of the graph, allowing for method chaining.
        )r   r8   r   s     r`   set_finish_pointzStateGraph.set_finish_point  s     }}S#&&rb   c                   | j                   D ch c]  \  }}|	 }}}| j                  j                         D ]  \  }}|j                  |        | j                  j                         D ]#  \  }}|j
                  s|j                  |       % |D ])  }	|	| j                  vs|	t        k7  st        d|	 d       t        |vrt        d      | j                   D 
ch c]  \  }}
|
	 }}}
| j                  j                         D ]  \  }}|j                         D ]  \  }}|j
                  ]|j
                  j                         D ]?  }
|
| j                  vr|
t        k7  rt        d| d| d|
 d      |j                  |
       A o|j                  t               | j                  D ]  }||k7  s	|j                  |          | j                  j                         D ]-  \  }}|j
                  s|j                  |j
                         / |D ])  }|| j                  vs|t        k7  st        d| d       |r$|D ]  }|| j                  vst        d	| d
       d| _        | S c c}}w c c}
}w )Nz%Found edge starting at unknown node 'r   zOGraph must have an entrypoint: add at least one edge from START to another nodezAt 'z	' node, 'z' branch found unknown target 'z#Found edge ending at unknown node `r   zInterrupt node `z` not foundT)r   ro   r   r   rn   r   r9   r   valuesr8   updateru   )r   	interruptsrcr   all_sourcesr   ro   r   specr   r   all_targetscondbranchri   targets                   r`   validatezStateGraph.validate  s   )-9vsAs99#}}224 	#OE8OOE"	#****, 	&JD$yy%	& " 	TFTZZ'FeO #HPQ!RSS	T #a 
 *.9vq#s99#}}224 	2OE8 ( 0 2f;;*%{{113 -djj0SCZ","&ugYtf<[\_[``a b#  $,-  OOC( $

 25='OOD122	2 ****, 	.JD$yy""499-	. " 	RFTZZ'FcM #Fvha!PQQ	R ! Ktzz)$'7v[%IJJK [ :" :s   I8"I>)cachestoreinterrupt_beforeinterrupt_afterdebugr   c          
     ^   |xs g }|xs g }| j                  |dk7  r|dk7  r|ng |z   ng        t        | j                  | j                           dk(  rd| j                  | j                     v rdnD| j                  | j                     j	                         D 	cg c]  \  }}	t        |	      s| c}	}}
t        | j                        dk(  rd| j                  v rdn8| j                  j	                         D 	cg c]  \  }}	t        |	      r| c}	}}t        t        t        t        t        f   di d| di d| j                  di d	i | j                  | j                  t        t        | j                         id
t        ddd|
d|d|d|d|ddd|d|d|d|xs d}|j#                  t        d       | j$                  j	                         D ]  \  }}|j#                  ||        | j&                  D ]  \  }}|j)                  ||        | j*                  D ]  \  }}|j)                  ||        | j,                  j	                         D ]0  \  }}|j	                         D ]  \  }}|j/                  |||        2 |j                         S c c}	}w c c}	}w )a  Compiles the `StateGraph` into a `CompiledStateGraph` object.

        The compiled graph implements the `Runnable` interface and can be invoked,
        streamed, batched, and run asynchronously.

        Args:
            checkpointer: A checkpoint saver object or flag.

                If provided, this `Checkpointer` serves as a fully versioned "short-term memory" for the graph,
                allowing it to be paused, resumed, and replayed from any point.

                If `None`, it may inherit the parent graph's checkpointer when used as a subgraph.

                If `False`, it will not use or inherit any checkpointer.
            interrupt_before: An optional list of node names to interrupt before.
            interrupt_after: An optional list of node names to interrupt after.
            debug: A flag indicating whether to enable debug mode.
            name: The name to use for the compiled graph.

        Returns:
            CompiledStateGraph: The compiled `StateGraph`.
        *)r   r   __root__builderschema_to_mapperry   rn   rp   input_channelsstream_modeupdatesoutput_channelsstream_channelscheckpointerinterrupt_before_nodesinterrupt_after_nodesauto_validateFr   r   r   r   	LangGraphNr   )r   r   rr   r{   r   rC   rp   rX   rT   rP   rQ   rS   ry   rq   r9   r3   rz   attach_nodern   rm   attach_edgers   ro   attach_branch)r   r  r   r   r   r   r   r   r   valr	  r
  ru   ri   r   r   r   ro   r   s                      r`   compilezStateGraph.compile7  s   D ,1r)/R 	 #c) &6%<!"W	 	 	
 4<< 2 2349dll4+=+=>> 
 !%T-?-? @ F F HC', 	 	 4==!Q&:+F  %)MM$7$7$9 SAQRUAV 	 &fh&GH 


  ..
 	

--,, ~d&7&78
 !
 "
 ,
 ,
 &
 $4
  #2!
"  #
$ %
& '
( )
* $+
0 	UD)))+ 	,IC  d+	, ** 	-JE3  ,	-  -- 	.KFC  -	.  $}}224 	<OE8 ( 0 <f&&udF;<	<   ""is   J#<J)J)r   )rw   rv   ry   rx   rz   ztype[InputT] | Noner{   ztype[OutputT] | Noner   Unpack[DeprecatedKwargs]r   None)r   rl   )T)r   rt   r_   	type[Any]r   r  )ri   StateNode[NodeInputT, ContextT]r   rt   r   dict[str, Any] | Nonerz   r  r   *RetryPolicy | Sequence[RetryPolicy] | Noner   CachePolicy | Noner   'dict[str, str] | tuple[str, ...] | Noner   r  r   r"   )ri   r  r   rt   r   r  rz   type[NodeInputT]r   r  r   r  r   r  r   r  r   r"   )ri   r   r   r  r   rt   r   r  rz   r  r   r  r   r  r   r  r   r  r   r"   )ri   %str | StateNode[NodeInputT, ContextT]r   &StateNode[NodeInputT, ContextT] | Noner   rt   r   r  rz   r  r   r  r   r  r   r  r   r  r   r"   )ri   r  r   r  r   rt   r   r  rz   ztype[NodeInputT] | Noner   r  r   r  r   r  r   r  r   r"   )r   zstr | list[str]r   r   r   r"   )r   r   r   Callable[..., Hashable | Sequence[Hashable]] | Callable[..., Awaitable[Hashable | Sequence[Hashable]]] | Runnable[Any, Hashable | Sequence[Hashable]]r   &dict[Hashable, str] | list[str] | Noner   r"   )rn   zWSequence[StateNode[NodeInputT, ContextT] | tuple[str, StateNode[NodeInputT, ContextT]]]r   r"   )r   r   r   r"   )r   r   r   r!  r   r"   )r   zSequence[str] | Noner   r"   )r  rL   r   zBaseCache | Noner   zBaseStore | Noner   All | list[str] | Noner   r"  r   rt   r   z
str | Noner   z5CompiledStateGraph[StateT, ContextT, InputT, OutputT])rd   
__module____qualname____doc____annotations__r   propertyr   r   r   r   r   r   r   r   r   r   r   r  r   rb   r`   rW   rW   o   s   DL  2255$$((GG33N))  
 154B
 -1.24B"4B .4B
 *4B ,4B +4B 
4Bl 
 

0@ 
 *.!CG+/@D- 	
 (  A ) > + 
 " 
 *.CG+/@D- 	
 ( ' A ) > + 
 "  *.!CG+/@D 0
  (  A ) > + 
    :>
 *.CG+/@D3 7
  ( ' A ) > + 
 & :>U
 *.04CG+/@DU3U 7U
 U (U .U AU )U >U +U 
Un4x <@0070 90 
0d-
- 
-^)$ <@A7A
 9A 
A0'/f &*g# #'"&3726g#"g#  	g#
  g# 1g# 0g# g# g# 
?g#rb   rW   c                       e Zd ZU ded<   ded<   	 	 	 	 	 	 	 	 d fdZ	 d	 	 	 ddZ	 d	 	 	 ddZddZdd	Zd
d	 	 	 	 	 	 	 	 	 ddZ	d fdZ
 xZS )rX   -StateGraph[StateT, ContextT, InputT, OutputT]r  ,dict[type[Any], Callable[[Any], Any] | None]r  c               @    t        |   di | || _        || _        y Nr   )superr   r  r  )r   r  r  r   rf   s       r`   r   zCompiledStateGraph.__init__  s$     	"6" 0rb   c                    t        | j                  j                  | j                  j                  | j                  j                  | j                  d            S )NInputtyprr   rp   r   )_get_json_schemar  rz   rr   rp   r   r   configs     r`   get_input_jsonschemaz'CompiledStateGraph.get_input_jsonschema  sD      ))LL((\\**w'	
 	
rb   c                    t        | j                  j                  | j                  j                  | j                  j                  | j                  d            S )NOutputr0  )r2  r  r{   rr   rp   r   r3  s     r`   get_output_jsonschemaz(CompiledStateGraph.get_output_jsonschema  sD      **LL((\\**x(	
 	
rb   c           
     @   |t         k(  rZ| j                  j                  | j                  j                     j	                         D cg c]  \  }}t        |      s| c}}nWt        | j                  j                        | j                  j                  j	                         D cg c]  \  }}|	 c}}z   	 	 	 	 d
fdt        dgk(  rt        n      t        t        |!|j                  t        |j                        nd       f}|t         k(  r5t        t        gt         gt         t!        |      g      | j"                  |<   y |9|r|j                  n| j                  j$                  }t        | j                  j                  |         }t'        |      dk(  xr d|v }|| j(                  v r| j(                  |   }	nt+        ||      }	|	| j(                  |<   t,        j/                  |      }
|j0                  rt3        t4              nt7        t4        d      | j                  |
<   t        |
g|rdn||	t!        |      g|j8                  |j:                  |j<                  |j>                  	      | j"                  |<   y t@        c c}}w c c}}w )Nc                .   | y t        | t              r*| j                         D cg c]  \  }}|v s||f c}}S t        | t              rH| j                  t        j
                  k(  ry | j                         D cg c]  \  }}|v s||f c}}S t        | t        t        f      r| rt        d | D              r}g }| D ]t  }t        |t              rG|j                  t        j
                  k(  r1|j                  fd|j                         D               Z|j                   |      xs d       v |S t        |       x}rt        |      rt        |       S t        d|  t        j                         }t#        |      c c}}w c c}}w )Nc              3  <   K   | ]  }t        |t                y wr   rZ   rM   r   is     r`   r   zGCompiledStateGraph.attach_node.<locals>._get_updates.<locals>.<genexpr>  s     >1
1g.>   c              3  6   K   | ]  \  }}|v s||f  y wr   r   )r   kvoutput_keyss      r`   r   zGCompiledStateGraph.attach_node.<locals>._get_updates.<locals>.<genexpr>  s%      ''+q![HXQF's   	r   zExpected dict, got )message
error_code)rZ   r   r   rM   graphPARENT_update_as_tupleslistr   anyextendr[   r)   r+   r>   r;   INVALID_GRAPH_NODE_RETURN_VALUEr<   )	r   rA  rB  r  r>  tmsg_get_updatesrC  s	          r`   rO  z4CompiledStateGraph.attach_node.<locals>._get_updates  su    }E4(+0;;=M41aA<LAMME7+;;'..0','>'>'@#q!ADTQF  54-0>>>13 >A!!W-77gnn4$ '/0/B/B/D'   |A'<"=> E{"!"(A!(D+E;??*1%9(HH )--= Ns   FF FFr  )mapper)rP  static)tagstriggersrp   writersr   F)guard)rS  rp   rP  rT  r   r   r   bound)r   zNone | dict | Anyr    Sequence[tuple[str, Any]] | None)!r9   r  rr   rz   r   rC   rI  rp   rq   rI   	_get_root_control_branchr   _control_staticrF   r:   rG   rn   rw   r   r  _pick_mapper_CHANNEL_BRANCH_TOformatr   r5   r   r3   r   r   r   runnabler   )r   r   ri   rA  rB  write_entriesrz   r  is_single_inputrP  branch_channelrO  rC  s              @@r`   r  zCompiledStateGraph.attach_node  sW   %< !LL001J1JKQQSAq'* K t||445"ll2288:9a9 K$	.$$	.-$	.P #$/J<$?y\ #&#		(= 'tyy1		
Q
 %<( \%m45	DJJsO 044,,$,,:S:SL!$,,"6"6|"DEN!.1Q6W:;WOt444..|<%nlC6<%%l3/66s;N :: %S)#Cu5 MM.)
 )()(7*^%m45!..!..mmDJJsO G9s   
J+Jc           	        t        |t              rZ|t        k7  rP| j                  |   j                  j                  t        t        t        j                  |      d       f             y y |t        k7  rddj                  |       d| }| j                  j                  |   j                  r't        t        t        |            | j                  |<   n&t!        t        t        |            | j                  |<   | j                  |   j"                  j                  |       |D ]>  }| j                  |   j                  j                  t        t        ||      f             @ y y )Nzjoin:+:)rZ   r   r8   rn   rT  appendrG   rH   r\  r]  r   r  r   r7   r   rp   r6   rS  )r   r   r   channel_namer   s        r`   r  zCompiledStateGraph.attach_edge.  s+   fc"cz

6"**11 *+=+D+DS+I4PR  CZ"388F#3"4AcU;L||!!#&,,.JV/l+ /@S[.Ql+JJsO$$++L9 

5!))00 "3L%"H!JK rb   T)with_readerc               X   	 d	 	 	 	 	 dd}|r|j                   xsQ || j                  j                  v r#| j                  j                  |   j                   n| j                  j                  }t	        | j                  j
                  |         }|| j                  v r| j                  |   }nt        ||      }|| j                  |<   t        t        j                  |dgk(  r|d   n|d|      }	nd }	| j                  |   j                  j                  |j                  ||	             y )Nc                    | D cg c]J  }|rn	|t         k7  r<t        |t              s*t        |t         k(  r|nt        j                  |      d       n|L }}|sg S |S c c}w r   )r8   rZ   rO   rH   r\  r]  )packetsrQ  pwritess       r`   
get_writesz4CompiledStateGraph.attach_branch.<locals>.get_writesK  sv     !
 "DS	 &a. &#X+=+D+DQ+G 	
F 
 	M
s   AAr  r   T)selectfreshrP  )F)rj  zSequence[str | Send]rQ  rt   r   z"Sequence[ChannelWriteEntry | Send])rz   r  rn   rw   rI  rr   r  r[  r	   rE   do_readrT  re  run)
r   r   r   r   rg  rm  r_   rp   rP  readers
             r`   r  z CompiledStateGraph.attach_branchH  s'    ;@	)	37	/	$ (( DLL... ""5)66\\.. 
 DLL0089H.....v6%h706%%f-=D##&.:,&>x{H>F F 	

5!!((J)GHrb   c                   t         |   |       |d   }|d   }|d   }|sy|d   dk\  ryt        |      D ]  }|j                  d      s|j	                  d      d	   }|| j
                  vr8d
| }||v rt        ||   |j                  |            n|j                  |      }|j                  |i       |j                  t        i       fD ]4  }	||	v s|	j                  |      }
||	v rt        |
|	|         |	|<   0|
|	|<   6 ||vr||v r|j                  |      ||<   |||<    t        |      D ]  }|j                  d      s|j                  d      dk(  s+|j	                  d      d   }|| j
                  vrNd
| }||v rt        ||   |j                  |            n|j                  |      }|j                  |i       |j                  t        i       fD ]4  }	||	v s|	j                  |      }
||	v rt        |
|	|         |	|<   0|
|	|<   6 ||vr||v r|j                  |      ||<   |||<    t        | j
                        j                  |      sgt        t              }| j                  j                  D ]-  \  }}|t         k7  s|t"        k7  s||   j%                  |       / t        |      D ]  }|t         k(  r|| j
                  v s|j                  |      }|j                  |t&              }||   D ]  }d
| }||v rt        ||   |      n|}|j                  |i       |j                  t        i       fD ]4  }	||	v s|	j                  |      }
||	v rt        |
|	|         |	|<   0|
|	|<   6 ||vr|t&        ur|||<   |||<    t        |v s|t           j                  |t&                yy)z+Migrate a checkpoint to new channel layout.channel_valueschannel_versionsversions_seenNrB     zstart:rd  r   z
branch:to:zbranch:)r-  _migrate_checkpointrI  
startswithsplitrn   maxpopr   r%   countr   
isdisjointr   r  rm   r9   r8   re  r/   )r   
checkpointr   versionsseenrA  ri   new_knew_vssssource_to_targetr   r   rB  crf   s                   r`   ry  z&CompiledStateGraph._migrate_checkpointy  s   #J/,-01/*  c?a h 	(A||H%wws|Atzz)$TF+ ( a9!a   88D"-txx	2/FG *BBwFF1I B;(+Ar%y(9BuI()BuI* &1;$*JJqMF5M"'3	(8 h 	(A||I&1773<1+<wws|B'tzz)$TF+ ( a9!a   88D"-txx	2/FG *BBwFF1I B;(+Ar%y(9BuI()BuI* &1;$*JJqMF5M"'3	(6 4::))(3*40"ll00 8
sE>cSj$U+22378 (^ 8:

? QA

1g.A/2 0",SE 2;@H;LHUOQ 7RS#'88C#4dhhy"6M"N 2B Bw$&FF1I#(B;03Ar%y0ABuI01BuI2 !.1G3C,-F5M*/!0$ !D(Y++Aw738 4rb   )r  r)  r  r*  r   r   r   r  r   )r4  zRunnableConfig | Noner   dict[str, Any])r   r   ri   z#StateNodeSpec[Any, ContextT] | Noner   r  )r   zstr | Sequence[str]r   r   r   r  )
r   r   r   r   r   r?   rg  rt   r   r  )r  r   r   r  )rd   r#  r$  r&  r   r5  r8  r  r  r  ry  __classcell__)rf   s   @r`   rX   rX     s     ;:BB	1 ?	1 G		1
 	1 
	1 /3
+
	
 /3
+
	
eN6 QU/I/I #/I-7/IIM/I	/Ibg8 g8rb   rX   c                h    | dgk(  ry t        |      rt        |t              ry t        t        |      S )Nr  )r
   
issubclassr   r	   _coerce_state)
state_keysr_   s     r`   r[  r[    s1     j\!v:fd3=&))rb   c                     | di |S r,  r   )r_   r   s     r`   r  r    s    ?E?rb   c                   t        | t              r	t        | ffS g }t        | t              r|j	                  |        n?t        | t
        t        f      r)| D ]$  }t        |t              s|j	                  |       & g }|D ]  }|j                  t        j                  k(  rt        |      t        |j                  t        t        f      r|j                  gn|j                  }|D ]k  }t        |t              r|j	                  t        |f       +t        |t              s<|t        k7  sF|j	                  t        j                  |      d f       m  |S r   )rZ   rO   r(   rM   re  rI  r   rF  rG  r=   gotor   r8   r\  r]  )valuecommandscmdr   commandgoto_targetsgos          r`   rY  rY    s$   %   H%!	ED%=	) 	%C#w'$	% "$C B==GNN*(( )c{CW\\N 	  	BB"d#

E2;'B$s 

.55b94@A	BB Jrb   c                "   t        | t              rD| j                         D cg c](  \  }}|t        k(  r|nt        j                  |      d |f* c}}S | D cg c]%  }|t        k(  r|nt        j                  |      d d f' c}S c c}}w c c}w r   )rZ   r   r   r8   r\  r]  )r   rA  labeles       r`   rZ  rZ    s     $ !JJL
5 s(Q 2 9 9! <dEJ
 	
 TX
NO!s(Q 2 9 9! <dDI
 	



s   -B*Bc                   t        | t              r.| j                  t        j                  k(  ry| j	                         S t        | t
        t        f      r| r~t        d | D              rlg }| D ]c  }t        |t              r>|j                  t        j                  k(  r1|j                  |j	                                Q|j                  d|f       e |S | d| fgS y )Nr   c              3  <   K   | ]  }t        |t                y wr   r<  r=  s     r`   r   z_get_root.<locals>.<genexpr>$  s     61
1g&6r?  r  )
rZ   rM   rF  rG  rH  rI  r   rJ  rK  re  )r   r  r>  s      r`   rX  rX    s    %!;;'..(&&((54-(666)+ 	0A!W%77gnn,q2245
A/	0 		U#$$ 
rb   c           	        t        | d      sdt        d| d      ii i fS t        | d      }|j                         D ci c]  \  }}|dk7  r|t        ||       }}}|j                         D ci c]  \  }}t	        |t
              s|| c}}|j                         D ci c]  \  }}t        |      s|| c}}|fS c c}}w c c}}w c c}}w )Nr&  r  Fr   T)include_extras	__slots__)r   _get_channelr   r   rZ   r1   rC   )r_   r   r   r1  all_keysrA  rB  s          r`   r   r   3  s     6,-j&NO
 	
  t<J $))+D#; 	l4%%H  #..*I$!QjK.HAI"..*B$!Q.>q.AAB  	JBs    C2CC&C:Cc                    y r   r   r   
annotationr   s      r`   r  r  J  s     rb   Tr   c                    y r   r   r  s      r`   r  r  P  s     &)rb   c               *   t        |d      r'|j                  t        t        fv r|j                  d   }t        | |      x}r|r|S t        d| d      t        |      x}r	| |_        |S t        |      x}r	| |_        |S t        |      }| |_        |S )N
__origin__r   zThis z not allowed in this position)r   r  r!   r    __args___is_field_managed_valuer   _is_field_channelr   _is_field_binopr4   )r   r  r   managerr   fallbacks         r`   r  r  V  s     z<(Z-B-BG .  ((+
)$
;;w;NuZL0MNOO%j1	1	1#J/	/	/#J/HHLOrb   c                    t        | d      rk| j                  }|D ]Z  }t        |t              r|c S t	        |      s#t        |t              s4 |t        | d      r| j                        c S |       c S  y )N__metadata__r  )r   r  rZ   r1   r
   r  r  )r1  metaitems      r`   r  r  p  sn    sN# 	SD$,:dK#@ gc<.HCNNRRcRR	S rb   c                2   t        | d      r| j                  }t        |      dk\  rqt        |d         rct	        |d         }t        |j                  j                               }t        d |D              dk(  rt        | |d         S t        d|       y )Nr  r   rx  c              3  d   K   | ](  }|j                   |j                  |j                  fv  * y wr   )kindPOSITIONAL_ONLYPOSITIONAL_OR_KEYWORD)r   rk  s     r`   r   z"_is_field_binop.<locals>.<genexpr>  s2       FFq00!2I2IJJs   .0r~   z5Invalid reducer signature. Expected (a, b) -> c. Got )r   r  r   callabler   rI  r   r   sumr2   r   )r1  r  sigparamss       r`   r  r  ~  s    sN#t9>htBx0DH%C#..//12F #  	 /sDH== KC5Q  rb   c                    t        |d      r<|j                  }t        |      dk\  r"t        |d         xs |d   }t	        |      r|S t        |       t        |      x}r|d   x}rt        | |      S y )Nr  r   rx  r   )r   r  r   r   rC   r   r  )r   r1  r  
decorationargs
inner_types         r`   r  r    s    sN#t9>#DH-9bJ
+!! 	3#c]"T"7"Z"&tZ88rb   c                >   t        |       r t        | t              r| j                         S t	        |       rt        |       j                         S t        ||    j                               }t        |      dk(  r5|d   dk(  r-t        |||d      j                  d f      j                         S t        |||    D ci c]C  }||v r=t        ||   t              r*|||   j                  t        |||   j                  |       fE c}      j                         S c c}w )Nr   r   r  )root)field_definitions)r
   r  r   model_json_schemar$   r   json_schemarI  r   r   r,   
UpdateTyperZ   r1   r*   )r1  rr   rp   r   r   rA  s         r`   r2  r2    s$    s|
3	2$$&&	c	3++--GCL%%'(t9>d1g3tAw'22D9  !"
   %S\# H}HQK)M  ..- ! ( 6 6 #	 	#   !!"#s   <AD
)r_   ztype[Any] | Anyr   r  )ri   zStateNode[Any, ContextT]r   r   )r  zSequence[str]r_   r  r   zCallable[[Any], Any] | None)r_   r  r   r  r   r  )r  r   r   zSequence[tuple[str, Any]])r   z tuple[str, ...] | dict[str, str]r   z%Sequence[tuple[str, Any, str | None]])r   r   r   rW  )r_   z
type[dict]r   zJtuple[dict[str, BaseChannel], dict[str, ManagedValueSpec], dict[str, Any]])r   r   r  r   r   zLiteral[False]r   r1   )r   r   r  r   r   zLiteral[True]r   BaseChannel | ManagedValueSpec)r   r   r  r   r   rt   r   r  )r1  r  r   zBaseChannel | None)r1  r  r   zBinaryOperatorAggregate | None)r   r   r1  r  r   zManagedValueSpec | None)
r1  r[   rr   r   rp   r   r   r   r   r  )
__future__r   r   loggingr\   r]   collectionsr   collections.abcr   r   r   r   	functoolsr	   r
   r   r   r   typesr   r   r   r   r   r   r   r   r   r   r   langchain_core.runnablesr   r   langgraph.cache.baser   langgraph.checkpoint.baser   langgraph.store.baser   pydanticr   r   typing_extensionsr    r!   r"   r#   r$   langgraph._internal._constantsr%   r&   r'   r(   langgraph._internal._fieldsr)   r*   r+   langgraph._internal._pydanticr,   langgraph._internal._runnabler-   langgraph._internal._typingr.   r/   r0   langgraph.channels.baser1   langgraph.channels.binopr2   "langgraph.channels.ephemeral_valuer3   langgraph.channels.last_valuer4   r5   &langgraph.channels.named_barrier_valuer6   r7   langgraph.constantsr8   r9   r:   langgraph.errorsr;   r<   r=   r>   langgraph.graph._branchr?   langgraph.graph._noder@   rA   langgraph.managed.baserB   rC   langgraph.pregelrD   langgraph.pregel._readrE   rF   langgraph.pregel._writerG   rH   rI   langgraph.typesrJ   rK   rL   rM   rN   rO   langgraph.typingrP   rQ   rR   rS   rT   langgraph.warningsrU   rV   __all__	getLoggerrd   r   r\  ra   rj   rW   rX   r[  r  rY  rZ  rX  r   r  r  r  r  r2  r   rb   r`   <module>r     sm   "     # C C  < <  &
 
 
 > * 0 * + O O  
 7 < L L / < = I 7 6  / : $ : 
  K J W
.			8	$# 	@o#67:; o#d8
68VW,-FHfg-.8D
**'0* *:

*
*
%.O. 

2@ 

 
BF)
))2?)#) 
) :>
26#4*&""	"""" "" 	""
 ""rb   