
    A'h,                     0   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	 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 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.m/Z/ d dl0m1Z1 d dl2m3Z3m4Z4 d dl5m6Z6m7Z7 d dl8m9Z9 d dl:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZA d dlBmCZCmDZDmEZEmFZF d dlGmHZH d dlImJZJmKZKmLZLmMZMmNZN d dlOmPZP d dlQmRZRmSZSmTZTmUZUmVZVmWZW d dlXmYZYmZZZ d dl[m\Z\m]Z]m^Z^ d dl_m`Z` d dlambZbmcZcmdZdmeZemfZf d dlgmhZhmiZi d dljmkZk d d llmmZmmnZn  ej                  ep      Zqd!eere   ef   d"dfd#Zsd$emd"etfd%Zu G d& d'e      Zv G d( d)eM      Zw G d* d+eL      Zxd,e	et   d!ere   d-eeyetef      d"eeegef      fd.Zzd!ere   d/eyetef   d"eyetef   fd0Z{d1ed"e	e|etef      fd2Z}d3ee|etd4f   eyetetf   f   d"e	e|eteeet   f      fd5Z~d/ed"ee	e|etef         fd6Zd!erey   d"e|eyete)f   eyeteUf   eyetef   f   fd7Zed8etd9ed:ed;   d"e)fd<       Zed=d>d8etd9ed:ed=   d"ee)eUf   fd?       Zd=d>d8etd9ed:ed"ee)eUf   fd@ZdAere   d"ee)   fdBZdAere   d"ee+   fdCZd8etdAere   d"eeU   fdDZdAerdEeydFeyd8etd"ere!   f
dGZdHZy)I    N)defaultdict)	AwaitableHashableSequence)partial)isclass
isfunctionismethod	signature)FunctionType)AnyCallableLiteral
NamedTupleOptionalUnioncastget_args
get_originget_type_hintsoverload)RunnableRunnableConfig)	BaseModel)Self)LangGraphDeprecationWarning)	BaseCache)BaseChannel)BinaryOperatorAggregate)DynamicBarrierValueDynamicBarrierValueAfterFinishWaitForNames)EphemeralValue)	LastValueLastValueAfterFinish)NamedBarrierValueNamedBarrierValueAfterFinish)
Checkpoint)	EMPTY_SEQ	INTERRUPTMISSINGNS_ENDNS_SEP
TAG_HIDDENTASKS)	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CachePolicyCheckpointerCommandRetryPolicy)get_field_defaultget_update_as_tuples)create_model)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)rQ   s    \/home/kushmeetdev/Regenta/Chatbot/venv/lib/python3.12/site-packages/langgraph/graph/state.py_warn_invalid_state_schemarZ   [   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: )	rT   r   get_namecallablegetattr	__class__r^   	TypeErrorrU   )r\   s    rY   _get_node_namerd   g   sO    $!}}	$tZ)@)@AA1$t*>??r[   c                       e Zd ZU eed<   eeeef      ed<   e	e   ed<   ee
eee   f      ed<   ee   ed<   eZee
eedf   eeef   f      ed<   dZeed	<   y
)StateNodeSpecrunnablemetadatainputretry_policycache_policy.endsFdeferN)r^   
__module____qualname__r   __annotations__r   dictstrr   rU   r   rK   r   rH   r)   rl   tuplerm   bool r[   rY   rf   rf   p   s}    tCH~&&95h{.C!CDEE;''=FD(5sCx$sCx.89
:FE4r[   rf   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<   	 	 d2d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d3dede
e   ddfdZeddddddddededeeeef      d
ee
e      deeeee   f      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ddedededeeeef      d
ee
e      deeeee   f      dee   deeeeef   eedf   f      defd       Z	 d4ddddddddeeef   dee   dedeeeef      d
ee
e      deeeee   f      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	 	 d2d"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#	 d4ddddddd(d)e$d*ee%   d+ee&   d,eee'ee   f      d-eee'ee   f      d.ed/ee   dd0fd1Z( xZ)S )5
StateGrapha1  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: The schema class that defines the state.
        config_schema: The schema class that defines the configuration.
            Use this to expose configurable parameters in your API.

    Example:
        ```python
        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}})
        # {'x': [0.5, 0.75]}
        ```
    nodeschannelsmanagedschemasN)ri   outputstate_schemaconfig_schemari   r|   rR   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__
ValueErrorrW   rX   r   r{   ry   rz   
type_hintsrQ   ri   r|   _add_schemar~   setwaiting_edges)selfr}   r~   ri   r|   rb   s        rY   r   zStateGraph.__init__   s     	} !PQQ LMMf+	 }$~%;="
&e4u5*?Bur[   c           	      ~    | j                   | j                  D ch c]  \  }}|D ]  }||f  c}}}z  S c c}}}w N)edgesr   )r   startsendstarts       rY   
_all_edgeszStateGraph._all_edges   sP    zz,0,>,>
 
(VSF
CHUCL

 
 	
 
s   8
r   rQ   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, r^    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 ')r{   rZ   _get_channelsjoinra   r   r   itemsry   rT   r$   rz   )
r   rQ   r   ry   rz   r   namesschema_namekeychannels
             rY   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/ &r[   F)rm   rh   ri   retryrk   destinationsr\   rm   rh   r   rk   r   .c                     y)zqAdd a new node to the state graph.
        Will take the name of the function/runnable as the node name.
        Nru   )r   r\   rm   rh   ri   r   rk   r   s           rY   add_nodezStateGraph.add_node   s     	r[   actionc                     y)z"Add a new node to the state graph.Nru   )	r   r\   r   rm   rh   ri   r   rk   r   s	            rY   r   zStateGraph.add_node  s     	r[   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  Add a new node to the state graph.

        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. (default: None)
                Will be used as the node function or runnable if `node` is a string (node name).
            metadata: The metadata associated with the node. (default: None)
            input: The input schema for the node. (default: the graph's input schema)
            retry: The policy for retrying the node. (default: None)
                If a sequence is provided, the first matching policy will be applied.
            cache_policy: The cache policy for the node. (default: None)
            destinations: 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.

        Example:
            ```python
            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}
            ```

        Example: Customize the name:
            ```python
            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.
        r^   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__rR   r   Fr   trace)ri   rj   rk   rl   rm   ),rT   rr   r   r_   ra   rb   r^   r   ry   compiledloggerwarningr   RuntimeErrorrx   r5   r6   r-   r,   r)   r	   r
   r   nextiterinspectr   r   
parameterskeysgetrU   r   r   r   rJ   r   	NameErrorrc   StopIterationr   rf   rP   rQ   )r   r\   r   rm   rh   ri   r   rk   r   	characterrl   hintsfirst_parameter_name
input_hintrtn
rtn_originrtn_argsarg
arg_originrargsvalss                        rY   r   zStateGraph.add_node   sK   x $$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  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 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)rT   rr   r   add_edger   r   r   r5   r   rx   r6   r   addrs   )r   r   r   r   rb   s       rY   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':;r[   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 )	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.
            then: 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   rP   r   branchesr   r4   	from_pathinput_schemar   )r   r   r   r   r   r   rQ   s          rY   add_conditional_edgesz StateGraph.add_conditional_edges  s    > ==NN: "$T>yy'K4==(($TYYK/J6(RST  '-&6&6tXtT&Rfd#]]6*40===6=V$r[   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.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   rT   rs   rd   rx   r   r   )r   rx   previous_namer\   r   s        rY   add_sequencezStateGraph.add_sequence  s    $ u:>CDD'+ 	!D$&3t9>!
d%d+tzz! EdV Lv v 
 MM$%(mT2 M!	!$ r[   )cachestoreinterrupt_beforeinterrupt_afterdebugr   checkpointerr   r   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i d| j                  dt        | j                        dkD  r;t        | j                        r&t        | j                  t              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|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 state graph 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 state graph.
        *)	interruptr   __root__builderschema_to_mapperconfig_typeinput_modelNrx   ry   input_channelsstream_modeupdatesoutput_channelsstream_channelsr   interrupt_before_nodesinterrupt_after_nodesauto_validateFr   r   r   r   	LangGraphru   )validater   r{   r|   r   r?   ry   r   r~   r   ri   
issubclassr   rz   r6   r#   attach_noderx   r   attach_edger   r   attach_branch)r   r   r   r   r   r   r   r   r   valr   r   r   r\   r   r   r   r   branchs                      rY   compilezStateGraph.compileA  sE   > ,1r)/R 	 #c) &6%<!"W	 	 	
 4<<,-2dll4;;77 
 !%T[[ 9 ? ? AC', 	 	 4==!Q&:+F  %)MM$7$7$9 SAQRUAV 	 & 


 **
 t}}%)DJJ'tzz95 

 
 
--,, ~djj1
" !#
$ "%
& ,'
( ,)
* &+
, $4-
. #2/
0  1
2 3
4 5
6 7
8 $9
> 	UD)))+ 	,IC  d+	, ** 	-JE3  ,	-  -- 	.KFC  -	.  $}}224 	<OE8 ( 0 <f&&udF;<	<   ""ws   K"<K(K()NN)Tr   )*r^   rn   ro   __doc__rq   rr   rf   rp   r   r>   rU   r   r   r   r   propertyr   rs   r   rt   r   r   rO   rK   r   rH   r   r   listr   r   r   r   r   r   r   rI   r   rF   rG   r   __classcell__rb   s   @rY   rw   rw   z   s^   1f ]"##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 
 -1%)EI.2IM 	
 4S>* S	" k8K+@@AB {+ uT#s(^U38_%DEF 
    -1%)EI.2IM 
  4S>* S	" k8K+@@AB {+ uT#s(^U38_%DEF 
 $ *.\
 -1%)EI.2IM\C%&\ &\
 \ 4S>*\ S	"\ k8K+@@AB\ {+\ uT#s(^U38_%DEF\ 
\|$%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#
 	"k# #5d3i#89k# "%T#Y"78k# k# smk# 
k#r[   rw   c                   6    e Zd ZU eed<   eee   ee	egef      f   ed<   deee   ee	egef      f   deddf fdZ
	 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 xZS )r   r   r   kwargsrR   Nc                2    t        |   di | || _        y Nru   )r   r   r   )r   r   r   rb   s      rY   r   zCompiledStateGraph.__init__  s     	"6" 0r[   configc                     t        | j                  j                  | j                  j                  | j                  j                  | j                  d            S )NInputtypr{   ry   r   )_get_schemar   ri   r{   ry   r_   r   r   s     rY   get_input_schemaz#CompiledStateGraph.get_input_schema  sD     ""LL((\\**w'	
 	
r[   c                     t        | j                  j                  | j                  j                  | j                  j                  | j                  d            S )NOutputr  )r  r   r|   r{   ry   r_   r  s     rY   get_output_schemaz$CompiledStateGraph.get_output_schema  sD     ##LL((\\**x(	
 	
r[   r   r\   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        f   dt        t        t        t         t        f         ffdt#        dgk(  rt$        n      t#        t&        |!|j(                  t+        |j(                        nd       f}|t         k(  r6t-        t.        gt         gt         gt1        |      g      | j2                  |<   y |h|r|j                  n| j                  j4                  }| j                  j                  |   D ci c]  }|| }}t7        |      dk(  xr d|v }|| j8                  v r| j8                  |   }	n<t;        t        |      || j                  j<                  |         }	|	| j8                  |<   t>        jA                  |      }
|jB                  rtE        t              ntG        t        d	
      | j                  |
<   t-        |
g|rt        |      n||	t1        |      g|jH                  |jJ                  |jL                  |jN                        | j2                  |<   y tP        c c}}w c c}}w c c}w )Nri   rR   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        |      rt        |       S t        d|  t        j                         }t#        |      c c}}w c c}}w )Nc              3   <   K   | ]  }t        |t                y wr   rT   rJ   .0is     rY   	<genexpr>zGCompiledStateGraph.attach_node.<locals>._get_updates.<locals>.<genexpr>  s     >1
1g.>   c              3   6   K   | ]  \  }}|v s||f  y wr   ru   )r  kvoutput_keyss      rY   r  zGCompiledStateGraph.attach_node.<locals>._get_updates.<locals>.<genexpr>  s%      ''+q![HXQF's   	ru   zExpected dict, got )message
error_code)rT   rq   r   rJ   graphPARENT_update_as_tuplesr   rs   anyextendrU   r   rM   r3   r0   INVALID_GRAPH_NODE_RETURN_VALUEr1   )	ri   r  r  r   r  tmsg_get_updatesr  s	          rY   r   z4CompiledStateGraph.attach_node.<locals>._get_updates  st    }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+E;??*1%9(HH )--= Ns   FF FFr   )mapper)r!  static)tagstriggersry   writersr   F)guard)r$  ry   r!  r%  rh   rj   rk   bound))r6   r   r{   ri   r   r?   r   ry   rz   r@   r   rq   r   r   r   rs   rr   rE   	_get_root_control_branchrl   _control_staticrB   r.   rC   rx   rQ   r   r   _pick_mapperr   CHANNEL_BRANCH_TOformatrm   r%   r#   rh   rj   rk   rg   r   )r   r   r\   r  r  write_entriesr   input_valuesis_single_inputr!  branch_channelr   r  s              @@rY   r   zCompiledStateGraph.attach_node  s   %< !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$	.tS)$	.huS#X/0$	.P #$/J<$?y\ #&#		(= 'tyy1		
W
 %<( \%m45	DJJsO )-4::4<<3F3FL*.,,*>*>|*LMQAqDMLM!,/14S|9SOt444..|<%& LL++L9
 7=%%l3.55c:N :: %S)#Cu5 MM.)
 )()0?$|,\%m45!..!..mmDJJsO S9F Ns   
L +L
Lr   r   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:+:)rT   rr   r5   rx   r%  appendrC   rD   r,  r-  r   r   rm   r'   r   ry   r&   r$  )r   r   r   channel_namer   s        rY   r   zCompiledStateGraph.attach_edge=  s+   fc"cz

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

5!))00 "3L%"H!JK r[   T)with_readerr   r   r   r7  c          
         	 ddt         t        t        t        f      dt        dt         t        t
        t        f      ffd}|rj                  xsQ | j                  j                  v r#| j                  j                     j                  n| j                  j                  }t        | j                  j                  |         }|| j                  v r| j                  |   }n3t        ||| j                  j                  |         }|| j                  |<   t!        t"        j$                  |dgk(  r|d   n|d|      }	nd }	| j                     j&                  j)                  j+                  ||	             j,                  r^j,                  t.        k7  rIj0                  rj0                  j3                         n3| j                  j                  D 
cg c]  }
|
j,                  k7  s|
 c}
}d	 d
 d}| j                  j                  j,                     j4                  rt7        t              | j8                  |<   nt;        t              | j8                  |<   | j                  j,                     j<                  j)                  |       |D ]H  }|t.        k7  s| j                  |   j&                  j)                  t?        t        ||      f             J y y y c c}
w )Npacketsr"  rR   c                 x   | 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 j                  rNj                  t         k7  r;|j                  t        d d dt        t        d | D                                 |S c c}w )Nbranch:r4  ::thenc              3   X   K   | ]"  }t        |t              r|j                  n| $ y wr   )rT   r9   r\   r  ps     rY   r  zGCompiledStateGraph.attach_branch.<locals>.get_writes.<locals>.<genexpr>o  s'      &IJ*Q*=1 D&s   (*)
r5   rT   r9   rD   r,  r-  r   r5  r"   	frozenset)r9  r"  r?  writesr   r   r   s       rY   
get_writesz4CompiledStateGraph.attach_branch.<locals>.get_writesZ  s     !
 "DS	 &a. &#X+<+C+CA+F 	
F 
 	{{v{{c1%!%$v6$% &NU& 	 M1
s   AB7r   r   T)selectfreshr!  r;  r4  r<  )F) r   r   rr   r9   rt   rD   r   r   rx   ri   rQ   r   r{   r   r+  r   r   rA   do_readr%  r5  runr   r5   rl   valuesrm   r!   ry   r    r$  rC   )r   r   r   r   r7  rB  rQ   ry   r!  readerr\   rl   r6  r   s    ```          rY   r   z CompiledStateGraph.attach_branchW  s|    AF	eCI./	9=	e-t345	: (( DLL... ""5)//\\(( 
 DLL0089H.....v6%h8O8OPV8WX06%%f-@G##&.:,&>x{HAF F 	

5!!((J)GH ;;6;;#- ;; ""$'+||'9'9QtTV[[=PdQ 
 %UG1TF&9L||!!&++.44.LS.Ql+.A#.Fl+JJv{{#,,33LA #:JJsO++22$&7c&J%LM .; Rs   K+3K+
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:r4  r   z
branch:to:r;  )r   
startswithsplitrx   maxpopr   r*   countr   
isdisjointr   r   r   r6   r5   r5  r+   )r   rI  rG  versionsseenr  r\   new_knew_vssssource_to_targetr   r   r  cs                   rY   _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 4r[   r   )r^   rn   ro   rw   rp   rq   rU   r   r   r   r   r   r   r  r  rr   rf   r   r   r   r   r4   rt   r   r(   r^  r   r   s   @rY   r   r     sQ   49hxs
/C&DDEE1 tCy(8SE3J3G*HHI1 	1
 
1 26
~.
	i
 26
~.
	i
ks k(=*A kd kZ%Xc](:"; # $ 6 MQMM #M-3MEIM	M^f8j f8T f8r[   r   
state_keysr   c                     | dgk(  ry t        |      r.t        |t              ry t        |t              rt	        ||      S t        t        |      S )Nr   )r   )r   r   rq   r   r:   r   _coerce_state)r_  rQ   r   s      rY   r+  r+    sI     j\!vfd#fi(':FF=&))r[   ri   c                      | di |S r   ru   )rQ   ri   s     rY   ra  ra    s    ?E?r[   valuec                    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              r"|j	                  t        |j                  f       gt        |j                  t              r1|j	                  t        j                  |j                        d f       |j                  d |j                  D                |S )Nc              3   z   K   | ]3  }t        |t              rt        |fnt        j	                  |      d f 5 y wr   )rT   r9   r/   r,  r-  )r  gos     rY   r  z"_control_branch.<locals>.<genexpr>3  sB        b$' '..r2D9:s   9;)rT   r9   r/   rJ   r5  r   rs   r  r  r2   gotorr   r,  r-  r  )rc  commandscmdr   commands        rY   r)  r)     s   %   H%!	ED%=	) 	%C#w'$	% "$C ==GNN*((gllD)JJw||,-c*JJ)00>EFJJ  ",,	  Jr[   rl   .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   )rT   rq   r   r5   r,  r-  )rl   r  labeles       rY   r*  r*  <  s     $ !JJL
5 s(Q 1 8 8 ;T5I
 	
 SW
MN!s(Q 1 8 8 ;T4H
 	



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 )Nru   c              3   <   K   | ]  }t        |t                y wr   r  r  s     rY   r  z_get_root.<locals>.<genexpr>R  s     61
1g&6r  r   )
rT   rJ   r  r  r  r   rs   r  r  r5  )ri   r   r  s      rY   r(  r(  J  s    %!;;'..(&&((54-(666)+ 	0A!W%77gnn,q2245
A/	0 		U#$$ 
r[   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 )Nrp   r   Fr   T)include_extras	__slots__)hasattr_get_channelr   r   rT   r   r?   )rQ   r   r   r  all_keysr  r  s          rY   r   r   a  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   Fc                     y r   ru   r   rv  r   s      rY   rt  rt  x  s     r[   Tr   c                     y r   ru   rx  s      rY   rt  rt  ~  s     ,/r[   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   rv  r   managerr   fallbacks         rY   rt  rt    s     *$
;;w;NuZL0MNOO%j1	1	1#J/	/	/#J/HHLOr[   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   rO  
__origin__)rs  r  r   rT   r   r   r   r  )r  metas     rY   r|  r|    s    sN#t9>jb;?8OY!^R 1jb;6W48gc<.HCNNRRcRRr[   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   rO  c              3   d   K   | ](  }|j                   |j                  |j                  fv  * y wr   )kindPOSITIONAL_ONLYPOSITIONAL_OR_KEYWORDr>  s     rY   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 )rs  r  r   r`   r   r   r   rG  sumr   r   )r  r  sigparamss       rY   r}  r}    s    sN#t9>htBx0DH%C#..//12F #  	 /sDH== KC5Q  r[   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   rO  )rs  r  r   r   r?   rT   r=   r   r   r;   r<   r  )r   r  r  
decorationr  r  s         rY   r{  r{    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
 "!r[   r{   ry   c                    t        |       rt        | t              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   rN   
UpdateTyperT   r   rL   )r  r{   ry   r   r   r  s         rY   r  r    s     s|
3	2
GCL%%'(t9>d1g3tAw'22D9 
   %S\# H}HQK)M  ..- ! ( 6 6 #	 	# #s   <AC
zbranch:to:{})r   loggingrV   rW   collectionsr   collections.abcr   r   r   	functoolsr   r   r	   r
   r   typesr   r   r   r   r   r   r   r   r   r   r   r   langchain_core.runnablesr   r   pydanticr   typing_extensionsr   langgraph._api.deprecationr   langgraph.cache.baser   langgraph.channels.baser   langgraph.channels.binopr   (langgraph.channels.dynamic_barrier_valuer    r!   r"   "langgraph.channels.ephemeral_valuer#   langgraph.channels.last_valuer$   r%   &langgraph.channels.named_barrier_valuer&   r'   langgraph.checkpoint.baser(   langgraph.constantsr)   r*   r+   r,   r-   r.   r/   langgraph.errorsr0   r1   r2   r3   langgraph.graph.branchr4   langgraph.graph.graphr5   r6   r7   r8   r9   langgraph.graph.schema_utilsr:   langgraph.managed.baser;   r<   r=   r>   r?   r@   langgraph.pregel.readrA   rB   langgraph.pregel.writerC   rD   rE   langgraph.store.baserF   langgraph.typesrG   rH   rI   rJ   rK   langgraph.utils.fieldsrL   rM   langgraph.utils.pydanticrN   langgraph.utils.runnablerO   rP   	getLoggerr^   r   rU   rZ   rr   rd   rf   rw   r   rq   r+  ra  rs   r)  r*  r(  r   rt  rt   r|  r}  r{  r  r,  ru   r[   rY   <module>r     s       # 9 9  < <     >  " B * / < 
 > I 1    *  >  : 
 + P P J 1 E			8	$	uT#Y^'< 	 	@ @# @J r# r#j]8 ]8@
*
*'+Cy
*>FtCQTH~>V
*hucz"#
*$s) DcN tCH~ 3 8E#s(O#< 8

c3hc3h/
0
eChsm+,-
%S %XhuS#X&?@ %.J
4[ !4-=(=#>S#XNO. 

29%. 

 
BF/
//29$-/
;(()/ 
/ :>
26
;(()(49 +)> c x0G'H *# DI (CS:T " 	     	 
 
)_ F # r[   