
    (Gg                     &   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 d dl mZm	Z	m
Z
mZ d dlmZ d dlmZmZmZmZmZmZ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' d dl(m)Z) d dl*m+Z+ d dl,m-Z-m.Z. d dl/m0Z0 d dl1m2Z2 d dl3m4Z4 d dl5m6Z6 d dl7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z> d dl?m@Z@mAZAmBZBmCZC d dlDmEZE d dlFmGZGmHZHmIZImJZJmKZK d dlLmMZM d dlNmOZOmPZPmQZQmRZRmSZSmTZT d dlUmVZVmWZW d dlXmYZYmZZZm[Z[ d dl\m]Z] d dl^m_Z_m`Z`maZambZb d dlcmdZd d dlemfZf d dlgmhZhmiZimjZj  ej                  el      Zmdeee   ef   d dfd!Znd"eid eofd#Zp G d$ d%e      Zq G d& d'eJ      Zr G d( d)eI      Zsd*erdee   d eegef   fd+Ztd,eeo   dee   d-eeueoef      d eeegef      fd.Zvdee   d/eueoef   d eueoef   fd0Zwd1ed eeeoeKf      fd2Zxd1ed eeeoeKf      fd3Zy ehexeye>gd4d4d45      Zz eEezd      Z{deeu   d e|eueoe)f   eueoeRf   eueoef   f   fd6Z}ed7eod8ed9ed4   d e)fd:       Z~ed;d<d7eod8ed9ed;   d ee)eRf   fd=       Z~d;d<d7eod8ed9ed ee)eRf   fd>Z~d?ee   d ee)   fd@Zd?ee   d ee+   fdAZd7eod?ee   d eeR   fdBZd?edCeudDeud7eod ee!   f
dEZdFZy)G    N)defaultdict)partial)isclass
isfunctionismethod	signature)FunctionType)Any	AwaitableCallableHashableLiteral
NamedTupleOptionalSequenceTypeUnioncastget_args
get_originget_type_hintsoverload)RunnableRunnableConfig)	BaseModel)Self)LangGraphDeprecationWarning)BaseChannel)BinaryOperatorAggregate)DynamicBarrierValueWaitForNames)EphemeralValue)	LastValue)NamedBarrierValue)
Checkpoint)	EMPTY_SEQ	INTERRUPTMISSINGNS_ENDNS_SEPSELF
TAG_HIDDEN)	ErrorCodeInvalidUpdateErrorParentCommandcreate_error_message)Branch)ENDSTARTCompiledGraphGraphSend)SchemaCoercionMapper)ChannelKeyPlaceholderChannelTypePlaceholderConfiguredManagedValueManagedValueSpecis_managed_valueis_writable_managed_value)ChannelRead
PregelNode)ChannelWriteChannelWriteEntryChannelWriteTupleEntry)	BaseStore)AllCheckpointerCommandRetryPolicy)get_field_default)create_model)RunnableCallableRunnableLikecoerce_to_runnableschemareturnc                     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)rM   s    r/home/kushmeetdev/apache_webroot/langgraph_flaskproject/venv/lib/python3.12/site-packages/langgraph/graph/state.py_warn_invalid_state_schemarV   W   s=    &$vMM
  )V 	V    nodec                     t        | t              r| j                         S t        |       r!t	        | d| j
                  j                        S t        dt        |              )N__name__zUnsupported node type: )	rP   r   get_namecallablegetattr	__class__rZ   	TypeErrorrQ   )rX   s    rU   _get_node_namer`   c   sO    $!}}	$tZ)@)@AA1$t*>??rW   c                       e Zd ZU eed<   eeeef      ed<   e	e   ed<   ee
   ed<   eZeeeedf   eeef   f      ed<   y)StateNodeSpecrunnablemetadatainputretry_policy.endsN)rZ   
__module____qualname__r   __annotations__r   dictstrr
   r   rG   r&   rg   r   tuple rW   rU   rb   rb   l   sY    tCH~&&9;''=FD(5sCx$sCx.89
:FrW   rb   c                       e Zd ZU dZeeef   ed<   eeef   ed<   eee	f   ed<   ee
e   eeeee	f   f   f   ed<   	 	 d/ddddee
e      d	ee
e      d
ee
e      dee
e      ddf
 fdZedeeeef      fd       Zd0dede
e   ddfdZeddddddedeeeef      d
ee
e      dee   deeeeef   eedf   f      defd       Zeddddddededeeeef      d
ee
e      dee   deeeeef   eedf   f      defd       Z	 d1ddddddeeef   dee   deeeef      d
ee
e      dee   deeeeef   eedf   f      defdZdeeee   f   dedef fdZ	 	 d/ded eedeeee   f   f   edeeeee   f      f   eeeeee   f   f   f   d!eeeeef   ee   f      d"ee   def
d#Z de!eeeeef   f      defd$Z"	 d1dddd%dd&d'e#d(ee$   d)eee%ee   f      d*eee%ee   f      d+ed,ee   dd-fd.Z& xZ'S )2
StateGrapha  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.

    Args:
        state_schema (Type[Any]): The schema class that defines the state.
        config_schema (Optional[Type[Any]]): The schema class that defines the configuration.
            Use this to expose configurable parameters in your API.

    Examples:
        >>> from langchain_core.runnables import RunnableConfig
        >>> from typing_extensions import Annotated, TypedDict
        >>> from langgraph.checkpoint.memory import MemorySaver
        >>> from langgraph.graph import StateGraph
        >>>
        >>> 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 ConfigSchema(TypedDict):
        ...     r: float
        >>>
        >>> graph = StateGraph(State, config_schema=ConfigSchema)
        >>>
        >>> def node(state: State, config: RunnableConfig) -> dict:
        ...     r = config["configurable"].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()
        >>>
        >>> print(compiled.config_specs)
        [ConfigurableFieldSpec(id='r', annotation=<class 'float'>, name=None, description=None, default=None, is_shared=False, dependencies=None)]
        >>>
        >>> step1 = compiled.invoke({"x": 0.5}, {"configurable": {"r": 3.0}})
        >>> print(step1)
        {'x': [0.5, 0.75]}nodeschannelsmanagedschemasN)re   outputstate_schemaconfig_schemare   ru   rN   c                   t         |           |.||t        d      |}t        j                  dt
        d       n||}||}i | _        i | _        i | _        i | _	        || _
        || _        || _        | j                  |       | j                  |d       | j                  |d       || _        t               | _        y )Nz-Must provide state_schema or input and outputzInitializing StateGraph without state_schema is deprecated. Please pass in an explicit state_schema instead of just an input and output schema.   )
stacklevelFallow_managed)super__init__
ValueErrorrS   rT   r   rt   rr   rs   
type_hintsrM   re   ru   _add_schemarw   setwaiting_edges)selfrv   rw   re   ru   r^   s        rU   r~   zStateGraph.__init__   s     	} !PQQ LMMf+	 }$~%;="
&e4u5*?BurW   c           	      ~    | j                   | j                  D ch c]  \  }}|D ]  }||f  c}}}z  S c c}}}w N)edgesr   )r   startsendstarts       rU   
_all_edgeszStateGraph._all_edges   sP    zz,0,>,>
 
(VSF
CHUCL

 
 	
 
s   8
r|   rM   c                   || j                   vr0t        |       t        |      \  }}}|r2|s0dj                  |      }t	        |dd      }t        d| d| d      i ||| j                   |<   || 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, rZ    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 ')rt   rV   _get_channelsjoinr]   r   r   itemsrr   rP   r#   rs   )
r   rM   r|   rr   rs   r   namesschema_namekeychannels
             rU   r   zStateGraph._add_schema   sl   %&v.,9&,A)Hgz}		'*%fj"= ;K=5' RR R  $;h#:'#:DLL &0DOOF# ( 0 
1W$--'}}S)W4%gy9 ","+C50V W#  *1DMM#&
1 !( 0W$,,&||C(G3(-cU2XY  )0DLL%0/ &rW   )rd   re   retrydestinationsrX   rd   r   r   .c                     y)a  Adds a new node to the state graph.
        Will take the name of the function/runnable as the node name.

        Args:
            node (RunnableLike): The function or runnable this node will run.

        Raises:
            ValueError: If the key is already being used as a state key.

        Returns:
            Self: The instance of the state graph, allowing for method chaining.
        Nrn   )r   rX   rd   re   r   r   s         rU   add_nodezStateGraph.add_node   s    , 	rW   actionc                     y)am  Adds a new node to the state graph.

        Args:
            node (str): The key of the node.
            action (RunnableLike): The action associated with the node.

        Raises:
            ValueError: If the key is already being used as a state key.

        Returns:
            Self: The instance of the state graph, allowing for method chaining.
        Nrn   )r   rX   r   rd   re   r   r   s          rU   r   zStateGraph.add_node  s    . 	rW   c                   t        |t              sQ|}t        |t              r|j                         }n!t	        |d|j
                  j                        }|t        d      || j                  v rt        d| 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"        t$        fD ]#  }|t        t        |      v st        d| d       t&        }	 t)        |      s"t+        |      st+        t	        |dd            r0t-        t	        |d            xs t-        |      x}	r|}t/        t1        t3        j4                  t        t6        |            j8                  j;                                     }
|	j=                  |
      x}rt        |t>              rt-        |      r|}|	j=                  d      x}rytA        |      }|tB        u r+tE        |      }|D ]  }tA        |      }|tF        u s|}|} n |tF        u r3tE        |      x}r&tA        |d         tH        u rtE        |d         x}r|}||}|| jQ                  |       tS        tU        |t        t        |      d      ||xs | jV                  ||      | j                  t        t        |      <   | S # tJ        tL        tN        f$ r Y w xY w)a  Adds a new node to the state graph.

        Will take the name of the function/runnable as the node name.

        Args:
            node (Union[str, RunnableLike]): The function or runnable this node will run.
            action (Optional[RunnableLike]): The action associated with the node. (default: None)
            metadata (Optional[dict[str, Any]]): The metadata associated with the node. (default: None)
            input (Optional[Type[Any]]): The input schema for the node. (default: the graph's input schema)
            retry (Optional[RetryPolicy]): The policy for retrying the node. (default: None)
            destinations (Optional[Union[dict[str, str], tuple[str, ...]]]): Destinations that indicate where a node can route to.
                This is 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.
        Raises:
            ValueError: If the key is already being used as a state key.

        Examples:
            ```pycon
            >>> from langgraph.graph import START, StateGraph
            ...
            >>> def my_node(state, config):
            ...    return {"x": state["x"] + 1}
            ...
            >>> builder = StateGraph(dict)
            >>> 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}
            ```
            Customize the name:

            ```pycon
            >>> builder = StateGraph(dict)
            >>> 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 state graph, allowing for method chaining.
        rZ   Nz6Node name must be provided if action is not a function'z&' is already being used as a state keyzjAdding 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__rN   r   Fr   trace)re   rf   rg   ),rP   rl   r   r[   r]   r^   rZ   r   rr   compiledloggerwarningr   RuntimeErrorrq   r2   r3   r*   r)   r&   r   r   r   nextiterinspectr   r	   
parameterskeysgetrQ   r   r   r   rF   r   	NameErrorr_   StopIterationr   rb   rL   rM   )r   rX   r   rd   re   r   r   	characterrg   hintsfirst_parameter_name
input_hintrtn
rtn_originrtn_argsarg
arg_originrargsvalss                      rU   r   zStateGraph.add_node(  sE   p $$F&(+(vz63C3C3L3LM| L  4== q&LMNN==NN: $$FWVVWVZQU5VWXD| L  >4::vdV+=>??3;$%-vdV>:;; &) 	IDdO+ 	{"ab 	 8A*	6"F#GFJ=>'
(CD *!&)* * =+/#-- $\6 :(j,( &+YY/C%DDzD%j$7N:<V$.E))H--3-!+CJ!U*#+C=#+ &C)3CJ)W4&)-7
 %& #g-&.sm3U3&uQx0G;%-eAh%77T7# #DU#&3vDdO5I&4;;'


4T?#  9m4 		s   $DL- ?AL- -MM	start_keyend_keyc                    t        |t              rt        |   ||      S | j                  rt
        j                  d       |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  Adds 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 (Union[str, list[str]]): The key(s) of the start node(s) of the edge.
            end_key (str): 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 state graph, 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Need to add_node `z` firstzSTART cannot be an end node)rP   rl   r}   add_edger   r   r   r2   r   rq   r3   r   addrm   )r   r   r   r   r^   s       rU   r   zStateGraph.add_edge  s    " i%7#Iw77==NN:  	FE| !=>>DJJ& #5eWG!DEE		F
 e:;;c>gTZZ71''BCCi 0':;rW   sourcepathpath_mapthenc                    | 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 )	a0  Add a conditional edge from the starting node to any number of destination nodes.

        Args:
            source (str): The starting node. This conditional edge will run when
                exiting this node.
            path (Union[Callable, Runnable]): 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[dict[Hashable, str]]): Optional mapping of paths to node
                names. If omitted the paths returned by `path` should be node names.
            then (Optional[str]): The name of a node to execute after the nodes
                selected by `path`.

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

        Note: Without typehints 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 ``)r   r   r   rL   r   branchesr   r1   	from_pathinput_schemar   )r   r   r   r   r   r   rM   s          rU   add_conditional_edgesz StateGraph.add_conditional_edges  s    > ==NN: "$T>yy'K4==(($TYYK/NvhVWX  '-&6&6tXtT&Rfd#]]6*40===6=V$rW   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 RunnableLike objects (e.g. a LangChain Runnable or a callable) or (name, RunnableLike) 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 state graph, allowing for method chaining.
           z$Sequence requires at least one node.Nry   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   rP   rm   r`   rq   r   r   )r   rq   previous_namerX   r   s        rU   add_sequencezStateGraph.add_sequence  s    $ u:>CDD'+ 	!D$&3t9>!
d%d+tzz! EdV Lv v 
 MM$%(mT2 M!	!$ rW   F)storeinterrupt_beforeinterrupt_afterdebugr   checkpointerr   r   r   r   r   CompiledStateGraphc          
         |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        di d| d| j                  dt        | j                        dkD  rAt        | j                        r,t        | j                  t        t        f      r| j                  ndd	i d
i | j                  | j                  t        t!        | j                        idt        ddd|	d|
d|d|d|ddd|d|d|xs d}|j#                  t        d       | j$                  j	                         D ]  \  }}|j#                  ||        |j'                  t        t(        t*        d       | j$                  j	                         D ]"  \  }}|j'                  |t(        t*        d       $ | j,                  D ]  \  }}|j/                  ||        | j0                  D ]  \  }}|j/                  ||        | j2                  j	                         D ]0  \  }}|j	                         D ]  \  }}|j'                  |||        2 |j                         S c c}}w c c}}w )a  Compiles the state graph into a `CompiledGraph` object.

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

        Args:
            checkpointer (Optional[Union[Checkpointer, Literal[False]]]): 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 (Optional[Sequence[str]]): An optional list of node names to interrupt before.
            interrupt_after (Optional[Sequence[str]]): An optional list of node names to interrupt after.
            debug (bool): A flag indicating whether to enable debug mode.

        Returns:
            CompiledStateGraph: The compiled state graph.
        *)	interruptr   __root__builderconfig_typeinput_modelNrq   rr   input_channelsstream_modeupdatesoutput_channelsstream_channelsr   interrupt_before_nodesinterrupt_after_nodesauto_validateFr   r   r   	LangGraphwith_readerrn   )validater   rt   ru   r   r<   rr   r   rw   r   re   
issubclassr   BaseModelV1rs   r3   r"   attach_noderq   attach_branchr+   CONTROL_BRANCHr   attach_edger   r   )r   r   r   r   r   r   r   r   valr   r   r   rX   r   r   r   r   branchs                     rU   compilezStateGraph.compileC  s   : ,1r)/R 	 #c) &6%<!"W	 	 	
 4<<,-2dll4;;77 
 !%T[[ 9 ? ? AC', 	 	 4==!Q&:+F  %)MM$7$7$9 SAQRUAV 	 & 

**

 t}}%)DJJ'tzzI{+CD 

 
 
--,, ~djj1
  !!
" "#
$ ,%
& ,'
( &)
* $4+
, #2-
.  /
0 1
2 3
4 $5
: 	UD)))+ 	,IC  d+	, 	udNN))+ 	QIC""3n%"P	Q ** 	-JE3  ,	-  -- 	.KFC  -	.  $}}224 	<OE8 ( 0 <f&&udF;<	<   ""{s   M<MM)NN)Tr   )(rZ   rh   ri   __doc__rk   rl   rb   rj   r   r;   r   r
   r   r   r~   propertyr   rm   r   boolr   r   rK   rG   r   r   listr   r   r   r   r   r   r   r   rE   rC   rD   r   __classcell__)r^   s   @rU   rp   rp   t   s   /b ]"##3#$$#''(($s)T#u[:J-J'K"KLLMM -1-1#E
 &*&*#EtCy)#E  S	*#E
 S	"#E c##E 
#EJ 
Cc3h0 
 

0t 0$s) 0t 0B 
 .2%)'+IM 4S>*	
 S	" $ uT#s(^U38_%DEF 
 .  .2%)'+IM 
 4S>* S	" $ uT#s(^U38_%DEF 
 6 *.V
 .2%)'+IMVC%&V &V
 4S>*V S	"V $V uT#s(^U38_%DEFV 
Vp$%T#Y"7 $# $$ $\ EI"11 S%$x. 899:S)E(DN*B$CDDES%$x. 899:<
1 5hm!4d3i!?@A1 sm1 
1f(lE#|2C,DDEF( 
(X &*k# &*<@;?"k#"k# 	"	k#
 #5d3i#89k# "%T#Y"78k# k# smk# 
k#rW   rp   c                       e Zd ZU eed<   	 ddee   dee   fdZ		 ddee   dee   fdZ
dedee   ddfd	Zd
eeee   f   deddfdZdddededededdf
dZdeddfdZy)r   r   NconfigrN   c                     t        | j                  j                  | j                  j                  | j                  j                  | j                  d            S )NInputtyprt   rr   r   )_get_schemar   re   rt   rr   r[   r   r   s     rU   get_input_schemaz#CompiledStateGraph.get_input_schema  sD     ""LL((\\**w'	
 	
rW   c                     t        | j                  j                  | j                  j                  | j                  j                  | j                  d            S )NOutputr   )r   r   ru   rt   rr   r[   r   s     rU   get_output_schemaz$CompiledStateGraph.get_output_schema  sD     ##LL((\\**x(	
 	
rW   r   rX   c           
      |   |t         k(  rZ| j                  j                  | j                  j                     j	                         D cg c]  \  }}t        |      s| c}}nbt        | j                  j                        | j                  j                  j	                         D cg c]  \  }}t        |      r| c}}z   dt        dt        t        t        t        t        f         fd}dt        d t         t        f   dt        t        t        t        t        f         ffdt#        dgk(  r|n      f}|t         k(  r=t%        t&        gt         gt         gt)        |t&        g      g      | j*                  |<   y ||r|j                  n| j                  j,                  }| j                  j                  |   D ci c]  }|| }}t/        |      d	k(  xr d|v }	t0        j3                  |      }
t5        t        d
      | j                  |
<   t%        |
g|	rt        |      n|t7        t        |      || j                  j8                  |         t)        |t&        g      g|j:                  |j<                  |j>                        | j*                  |<   y t@        c c}}w c c}}w c c}w )Nre   rN   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 )Nrn   c              3   <   K   | ]  }t        |t                y wr   rP   rF   .0is     rU   	<genexpr>zDCompiledStateGraph.attach_node.<locals>._get_root.<locals>.<genexpr>       >1
1g.>   r   )
rP   rF   graphPARENT_update_as_tuplesr   rm   anyextendappend)re   r   r  s      rU   	_get_rootz1CompiledStateGraph.attach_node.<locals>._get_root  s    %);;'..0..0054-0>>>13 8A!!W-77gnn4$q':':'<=
A78 "#U+,, #rW   c                 $   | 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        |      rt        | t              rD| j                  }| j                  j                         D ci c]  \  }}||j                    }}}nXt        | t"              rD| j$                  }|j&                  j                         D ci c]  \  }}||j                    }}}nd }i }D cg c]=  }t)        | |t*              x}t*        ur"||j-                  |t*              |||v r||f? c}S t/        d|  t0        j2                        }	t5        |	      c c}}w c c}}w c c}}w c c}}w c c}w )Nc              3   <   K   | ]  }t        |t                y wr   r  r  s     rU   r  zGCompiledStateGraph.attach_node.<locals>._get_updates.<locals>.<genexpr>  r	  r
  c              3   6   K   | ]  \  }}|v s||f  y wr   rn   )r  kvoutput_keyss      rU   r  zGCompiledStateGraph.attach_node.<locals>._get_updates.<locals>.<genexpr>  s%      ''+q![HXQF's   	rn   zExpected dict, got )message
error_code)rP   rk   r   rF   r  r  r  r   rm   r  r  rQ   r   r   model_fields_setmodel_fieldsdefaultr   __fields_set__
__fields__r]   r(   r   r0   r-   INVALID_GRAPH_NODE_RETURN_VALUEr.   )re   r  r  r   r  tkeepdefaultsvaluemsg_get_updatesr  s             rU   r%  z4CompiledStateGraph.attach_node.<locals>._get_updates  sc    }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{"!"q(9eY//4/E/ED9>9K9K9Q9Q9STA199THT{3 //D9:9K9K9MNA199NHND!H )	!(7!;;GK)#<<73? ,d J	 	 +1%9(HH )--o N.  U  O	s)   I5I5 I;I;J$JAJr   )mappertags)r(  triggersrr   writersr   F)guard)r)  rr   r&  r*  rd   rf   bound)!r3   r   rt   re   r   r<   r   rr   rs   r=   r
   r   r   rm   rl   r   rk   rB   r?   r,   r@   rq   rM   r   CHANNEL_BRANCH_TOformatr"   _pick_mapperr   rd   rf   rc   r   )r   r   rX   r  r  r  write_entriesr   input_valuesis_single_inputbranch_channelr%  r  s              @@rU   r   zCompiledStateGraph.attach_node  sa   %< !LL001C1CDJJLAq'* K t||445 LL006689Aq,Q/ 9 K	-S 	-XhuS#X.G%H 	-,=	.tS)=	.huS#X/0=	.B #$/J<$?y\W
 %<( \%m:,GH	DJJsO )-4::4<<3F3FL*.,,*>*>|*LMQAqDMLM!,/14S|9SO.55c:N,:3e,LDMM.)(()0?$|,\#& LL++L9 &m:,GH!..mmDJJsO" Q9X Ns   
J-+J3
J9r   r   c           	      J   t        |t              rZ|t        k7  rP| j                  |   j                  j                  t        t        t        j                  |      d       f             y y |t        k7  rddj                  |       d| }t        t        t        |            | j                  |<   | j                  |   j                  j                  |       |D ]E  }| j                  |   j                  j                  t        t        ||      ft        g             G y y )Nzjoin:+:r'  )rP   rl   r2   rq   r*  r  r@   rA   r-  r.  r   r$   r   rr   r)  r,   )r   r   r   channel_namer   s        rU   r   zCompiledStateGraph.attach_edgeT  s    fc"cz

6"**11 *+<+C+CC+H$OQ  CZ"388F#3"4AcU;L*;CV*MDMM,'JJsO$$++L9 

5!))00 *<?A rW   Tr   r   r   r   r   c          	         dt         t        t        t        f      dt        dd ffd}j
                  xsQ | j                  j                  v r#| j                  j                     j                  n| j                  j                  }| j                     j                  j                  j                  ||rt        | j                  |      nd              j                  rj                  t        k7  rj                   rj                   j#                         n3| j                  j                  D cg c]  }|j                  k7  s| c}}d d d}	t%        t              | j&                  |	<   | j                  j                     j(                  j                  |	       |D ]O  }
|
t        k7  s| j                  |
   j                  j                  t+        t-        |	|
      gt.        g             Q y y y c c}w )	Npacketsr   rN   c                 2   | D cg c]  }|t         k7  s| c}x}r|D cg c]3  }t        |t              st        t        j                  |      d       n|5 }}j                  rhj                  t         k7  rU|j                  t        d d dt        |D ch c]   }t        |t              r|j                  n|" c}                   t        j                  |t        t        t        t        t        f      |             y y c c}w c c}w c c}w )Nbranch:r6  ::then)r2   rP   r6   rA   r-  r.  r   r  r!   rX   r@   do_writer   r   r   )r9  r   pfilteredwritesr   r   r   s        rU   branch_writerz7CompiledStateGraph.attach_branch.<locals>.branch_writern  s
    (/;!!s(A;;x; &   *!T2 **;*B*B1*EtL  ;;6;;##5MM)%eWAdV6:(OW X!:a+>A!E X %%D%6G0G*H!I6R% <; !Ys   D
D
8D%Dr;  r6  r<  r'  )r   r   rl   r6   r   r   r   rq   re   rM   r*  r  run_get_state_readerr   r2   rg   valuesr    rr   r)  r@   rA   r,   )r   r   r   r   r   rA  rM   rX   rg   r7  r   s    ```       rU   r   z CompiledStateGraph.attach_branchk  s   	eCI./	9G		2 $$ 
*** LLu%++$$ 	 	

5!!((JJ;F!$,,7D	
 ;;6;;#- ;; ""$'+||'9'9QtTV[[=PdQ 
 %UG1TF&9L*=c*BDMM,'JJv{{#,,33LA #:JJsO++22$.|SAB* .; Rs   <HH
checkpointc                 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_seenNr     zstart:r6  r   z
branch:to:r;  )r   
startswithsplitrq   maxpopr   r'   countr   
isdisjointr   r   r   r3   r2   r  r(   )r   rE  rD  versionsseenr  rX   new_knew_vssssource_to_targetr   r   r  cs                   rU   _migrate_checkpointz&CompiledStateGraph._migrate_checkpoint  s    ,-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 4rW   r   )rZ   rh   ri   rp   rj   r   r   rQ   r   r   r   rl   rb   r   r   r   r   r1   r   r   r%   rZ  rn   rW   rU   r   r     s     26
~.
	i
 26
~.
	i
Js J(=*A Jd JX%Xc](:"; # $ 0 MQ:: #:-3:EI:	:xf8j f8T f8rW   r   r   c                     t        | j                        }t        | j                  |         }t        t        j
                  |dgk(  r|d   n|dt        ||| j                  |               S )Nr   r   T)selectfreshr&  )r   rr   rt   r   r>   do_readr/  r   )r   rM   
state_keysr\  s       rU   rC  rC    si     g&&'J'//&)*F"zl2vayJ0B0B60JK rW   r_  r   c                     | dgk(  ry t        |      r3t        |t              ry t        |t        t        f      rt        ||      S t        t        |      S )Nr   )r   r   rk   r   r   r7   r   _coerce_state)r_  rM   r   s      rU   r/  r/    sN     j\!vfd#fy+67'
;;=&))rW   re   c                      | di |S )Nrn   rn   )rM   re   s     rU   ra  ra  +  s    ?E?rW   r#  c                 b   t        | t              r| g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              r|j                  |j                         at        |j                  t              r|j                  |j                         |j                  |j                          |S r   rP   r6   rF   r  r   rm   r  r  r/   gotorl   r  r#  commandscmdr   commands        rU   _control_branchrj  /  s    %w H%!	ED%=	) 	%C#w'$	% #%C %==GNN*((gllD)JJw||$c*JJw||$JJw||$% JrW   c                 j  K   t        | t              r| g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              r|j                  |j                         at        |j                  t              r|j                  |j                         |j                  |j                          |S wr   rd  rf  s        rU   _acontrol_branchrl  F  s     %w H%!	ED%=	) 	%C#w'$	% #%C %==GNN*((gllD)JJw||$c*JJw||$JJw||$% Js   A#D3&CD3F)r(  r   recursefunc_accepts_configc           	         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 )Nrj   r   Fr{   T)include_extras	__slots__)hasattr_get_channelr   r   rP   r   r<   )rM   r   r   r   all_keysr  r  s          rU   r   r   h  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r   
annotationr|   c                     y r   rn   r   ru  r|   s      rU   rs  rs    s     rW   Tr{   c                     y r   rn   rw  s      rU   rs  rs    s     ,/rW   c                    t        | |      x}r|r|S t        d| d      t        |      x}r	| |_        |S t	        |      x}r	| |_        |S t        |      }| |_        |S )NzThis z not allowed in this position)_is_field_managed_valuer   _is_field_channelr   _is_field_binopr#   )r   ru  r|   managerr   fallbacks         rU   rs  rs    s     *$
;;w;NuZL0MNOO%j1	1	1#J/	/	/#J/HHLOrW   r   c                 ,   t        | d      r| j                  }t        |      dk\  rt        |d   t              r|d   S t        |      dk\  rHt        |d         r:t        |d   t              r' |d   t        | d      r| j                        S |       S y )N__metadata__r   rK  
__origin__)rr  r  r   rP   r   r   r   r  )r   metas     rU   r{  r{    s    sN#t9>jb;?8OY!^R 1jb;6W48gc<.HCNNRRcRRrW   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   rK  c              3   d   K   | ](  }|j                   |j                  |j                  fv  * y wr   )kindPOSITIONAL_ONLYPOSITIONAL_OR_KEYWORD)r  r>  s     rU   r  z"_is_field_binop.<locals>.<genexpr>  s2       FFq00!2I2IJJs   .0ry   z5Invalid reducer signature. Expected (a, b) -> c. Got )rr  r  r   r\   r   r   r   rD  sumr   r   )r   r  sigparamss       rU   r|  r|    s    sN#t9>htBx0DH%C#..//12F #  	 /sDH== KC5Q  rW   c                 j   t        |d      r|j                  }t        |      dk\  rt        |d         xs |d   }t	        |      rmt        |t              r[|j                  j                         D ]>  \  }}|t        u r| |j                  |<   |t        u s&|j                  |j                  |<   @ |S y )Nr  r   rK  )rr  r  r   r   r<   rP   r:   kwargsr   r8   r9   r  )r   r   r  
decorationr  r  s         rU   rz  rz    s    sN#t9>#DH-9bJ
+j*@A * 1 1 7 7 9 B1 5537J--a0 6636>>J--a0	B
 "!rW   rt   rr   c                    t        |       rt        | t        t        f      r| S t	        ||    j                               }t        |      dk(  r'|d   dk(  rt        |||d      j                  d f      S t        |||    D ci c]C  }||v r=t        ||   t              r*|||   j                  t        |||   j                  |       fE c}      S c c}w )Nr   r   r   )root)field_definitions)r   r   r   r   r   r   r   rI   
UpdateTyperP   r   rH   )r   rt   rr   r   r   r  s         rU   r   r     s     s|
3K(@A
GCL%%'(t9>d1g3tAw'22D9 
   %S\# H}HQK)M  ..- ! ( 6 6 #	 	# #s   AC
zbranch:to:{})r   loggingrR   rS   collectionsr   	functoolsr   r   r   r   r   typesr	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   langchain_core.runnablesr   r   pydanticr   pydantic.v1r   typing_extensionsr   langgraph._api.deprecationr   langgraph.channels.baser   langgraph.channels.binopr   (langgraph.channels.dynamic_barrier_valuer    r!   "langgraph.channels.ephemeral_valuer"   langgraph.channels.last_valuer#   &langgraph.channels.named_barrier_valuer$   langgraph.checkpoint.baser%   langgraph.constantsr&   r'   r(   r)   r*   r+   r,   langgraph.errorsr-   r.   r/   r0   langgraph.graph.branchr1   langgraph.graph.graphr2   r3   r4   r5   r6   langgraph.graph.schema_utilsr7   langgraph.managed.baser8   r9   r:   r;   r<   r=   langgraph.pregel.readr>   r?   langgraph.pregel.writer@   rA   rB   langgraph.store.baserC   langgraph.typesrD   rE   rF   rG   langgraph.utils.fieldsrH   langgraph.utils.pydanticrI   langgraph.utils.runnablerJ   rK   rL   	getLoggerrZ   r   rV   rl   r`   rb   rp   r   rC  rk   r/  ra  rj  rl  CONTROL_BRANCH_PATHr   rm   r   rs  r   r{  r|  rz  rQ   r   r-  rn   rW   rU   <module>r     s       #  < <     $ >  0 " B / < V = 3 D 0    *  >  : 
 + C C 4 1 W W			8	$	uT#Y^'< 	 	@ @# @GJ Gz# z#z\8 \8~
!%c~#$
*
*'+Cy
*>FtCQTH~>V
*hucz"#
*$s) DcN tCH~ 3 8E#t),<#= .# (5d3C*D . '

  +T2J
4[ !4-=(=#>S#XNO. 

29%. 

 
BF/
//29$-/
;(()/ 
/ :>
26
;(()(49 +)> c x0G'H *# DI (CS:T " 	     	 
 
)_ F # rW   