
    A'h@                     l   d dl Z d dlmZ d dlmZmZmZ d dlmZm	Z	m
Z
mZmZmZmZ d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZmZmZmZmZmZmZ d d
lm Z  d dl!m"Z"m#Z# d dl$m%Z% d dl&m'Z'm(Z( d dl)m*Z* d dl+m,Z,m-Z- d dl.m/Z/m0Z0  e jb                  e2      Z3 G d de
      Z4 G d d      Z5 G d de#      Z6y)    N)defaultdict)	AwaitableHashableSequence)AnyCallable
NamedTupleOptionalUnioncastoverload)Runnable)Self)	BaseCache)EphemeralValue)	EMPTY_SEQENDNS_ENDNS_SEPSTART
TAG_HIDDENSend)Branch)ChannelPregel)
PregelNode)ChannelWriteChannelWriteEntry)	BaseStore)AllCheckpointer)RunnableLikecoerce_to_runnablec                   h    e Zd ZU eed<   dZeeee	f      ed<   e
Zeeeedf   eeef   f      ed<   y)NodeSpecrunnableNmetadata.ends)__name__
__module____qualname__r   __annotations__r'   r
   dictstrr   r   r(   r   tuple     \/home/kushmeetdev/Regenta/Chatbot/venv/lib/python3.12/site-packages/langgraph/graph/graph.pyr%   r%   '   sH    )-HhtCH~&-=FD(5sCx$sCx.89
:Fr1   r%   c                       e Zd Zd%dZedeeeef      fd       Ze	ddde
deeeef      defd       Ze	ddded	e
deeeef      defd
       Z	 d&dddeee
f   d	ee
   deeeef      defdZdedede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defdZ	 	 d'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defdZd&deee      defdZ	 	 	 	 	 d(ddddedeeeee   f      deeeee   f      ded ee   d!ee    d"ee!   dd#fd$Z"y))GraphreturnNc                     i | _         t        t        t        t        f             | _        t        t              | _        d| _        d| _	        y )NF)
nodessetr/   r.   edgesr   r-   branchessupport_multiple_edgescompiledselfs    r2   __init__zGraph.__init__.   s;    *,
sCx)+
=H=N&+#r1   c                     | j                   S N)r9   r=   s    r2   
_all_edgeszGraph._all_edges5   s    zzr1   )r'   noder'   c                     y rA   r0   )r>   rC   r'   s      r2   add_nodezGraph.add_node9   s     r1   actionc                     y rA   r0   )r>   rC   rF   r'   s       r2   rE   zGraph.add_nodeA   s     r1   c          	      4   t        |t              r$t        t        fD ]  }||v st	        d| d       | j
                  rt        j                  d       t        |t              s&|}t        |dt        |d            }|t	        d      |t        d      || j                  v rt	        d| d	      |t        k(  s	|t        k(  rt	        d| d
      t        t        |t        t        |      d      |      | j                  t        t        |      <   | S )a  Add a new node to the 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)
        'z?' is a reserved character and is not allowed in the node names.zjAdding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.namer)   z6Node name must be provided if action is not a functionzBExpected a function or Runnable action in add_node. Received None.zNode `z` already present.z` is reserved.FrJ   trace)
isinstancer.   r   r   
ValueErrorr<   loggerwarninggetattrRuntimeErrorr7   r   r   r%   r#   r   )r>   rC   rF   r'   	characters        r2   rE   zGraph.add_nodeJ   s(     dC $f- 	$$I;&ef  ==NN: $$F6676:+FGD| L  >T  4::vdV+=>??3;$%-vdV>:;;&.vDdO5I8'


4T?# r1   	start_keyend_keyc                 D   | j                   rt        j                  d       |t        k(  rt	        d      |t
        k(  rt	        d      t        | d      s-|t        d | j                  D              v rt	        d| d      | j                  j                  ||f       | S )zAdd a directed edge from the start node to the end node.

        Args:
            start_key: The key of the start node of the edge.
            end_key: The key of the end node of the edge.
        kAdding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.zEND cannot be a start nodezSTART cannot be an end nodechannelsc              3   &   K   | ]	  \  }}|  y wrA   r0   ).0start_s      r2   	<genexpr>z!Graph.add_edge.<locals>.<genexpr>   s      >
eQE>
s   zAlready found path for node 'zB'.
For multiple edges, use StateGraph with an Annotated state key.)
r<   rO   rP   r   rN   r   hasattrr8   r9   add)r>   rT   rU   s      r2   add_edgezGraph.add_edge{   s     ==NN: 9::e:;; tZ(Y# >
"&**>
 ;
 .
 /	{ ;R R 
 	

	7+,r1   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
                  |   |<   | 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.

        rW   NTrK   	conditionzBranch with name `z` already exists for node ``F)	r<   rO   rP   r#   rJ   r:   rN   r   	from_path)r>   ra   rb   rc   rd   rJ   s         r2   add_conditional_edgeszGraph.add_conditional_edges   s    > ==NN: "$T>yy'K4==(($TYYK/J6(RST  '-&6&6tXtU&Sfd#r1   keyc                 .    | j                  t        |      S )a+  Specifies the first node to be called in the graph.

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

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

        Returns:
            Self: The instance of the graph, allowing for method chaining.
        )r`   r   r>   rj   s     r2   set_entry_pointzGraph.set_entry_point   s     }}UC((r1   c                 2    | j                  t        |||      S )al  Sets a conditional entry point in the graph.

        Args:
            path: The callable that determines the next
                node or nodes. If not specifying `path_map` it should return one or
                more nodes. If it returns END, the graph will stop execution.
            path_map: Optional mapping of paths to node
                names. If omitted the paths returned by `path` should be node names.
            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.
        )ri   r   )r>   rb   rc   rd   s       r2   set_conditional_entry_pointz!Graph.set_conditional_entry_point   s    0 ))%xFFr1   c                 .    | j                  |t              S )a0  Marks a node as a finish point of the graph.

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

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

        Returns:
            Self: The instance of the graph, allowing for method chaining.
        )r`   r   rl   s     r2   set_finish_pointzGraph.set_finish_point   s     }}S#&&r1   	interruptc                    | j                   D ch c]  \  }}|	 }}}| j                  j                         D ]  \  }}|j                  |       |j                         D ]  \  }}|j                  |j
                  ;|j
                  j                         D ]  }	|	t        k7  s|j                  |	        Z| j                  D ])  }
|
|k7  s	|
|j                  k7  s|j                  |
       +   | j                  j                         D ]#  \  }}|j
                  s|j                  |       % |D ])  }|| j                  vs|t        k7  st        d| d       t        |vrt        d      | j                   D 	ch c]  \  }}	|		 }}}	| j                  j                         D ]  \  }}|j                         D ]  \  }}|j                  |j                  |j                         |j
                  ]|j
                  j                         D ]?  }	|	| j                  vr|	t        k7  rt        d| d| d|	 d      |j                  |	       A |j                  t               | j                  D ])  }
|
|k7  s	|
|j                  k7  s|j                  |
       +   | j                  j                         D ]-  \  }}|j
                  s|j                  |j
                         / |D ])  }|| j                  vs|t        k7  st        d| d       |r$|D ]  }
|
| j                  vst        d	|
 d
       d| _        | S c c}}w c c}	}w )Nz%Found edge starting at unknown node 'rI   zOGraph must have an entrypoint: add at least one edge from START to another nodezAt 'z	' node, 'z' branch found unknown target 'z#Found edge ending at unknown node `rg   zInterrupt node `z` not foundT)rB   r:   itemsr_   rd   r(   valuesr   r7   r   rN   updater<   )r>   rr   srcr\   all_sourcesr[   r:   condbranchendrC   rJ   specra   all_targetstargets                   r2   validatezGraph.validate   sG   )-9vsAs99#}}224 	6OE8OOE" ( 0 	6f;;*{{.#);;#5#5#7 5C"cz + 45 %)JJ 6D#u}1D + 56	6	6 ****, 	&JD$yy%	& " 	TFTZZ'FeO #HPQ!RSS	T #a 
 *.9vq#s99#}}224 	2OE8 ( 0 2f;;*OOFKK0;;*%{{113 -djj0SCZ","&ugYtf<[\_[``a b#  $,-  OOC( $

 25=TV[[-@'OOD122	2  ****, 	.JD$yy""499-	. " 	RFTZZ'FcM #Fvha!PQQ	R ! Ktzz)$'7v[%IJJK s :6 :s   MM)cachestorecheckpointerinterrupt_beforeinterrupt_afterdebugrJ   r   r   CompiledGraphc                f   |xs g }|xs g }| j                  |dk7  r|dk7  r|ng |z   ng        t        | i t        t        t              t
        t        t              it        t
        dg |||d||xs d||      }| j                  j                         D ]  \  }	}
|j                  |	|
        | j                  D ]  \  }}|j                  ||        | j                  j                         D ]0  \  }}|j                         D ]  \  }}|j                  |||        2 |j                         S )a  Compiles the graph into a `CompiledGraph` 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:
            CompiledGraph: The compiled graph.
        *)rr   ru   F	LangGraph)builderr7   rX   input_channelsoutput_channelsstream_modestream_channelsr   interrupt_before_nodesinterrupt_after_nodesauto_validater   rJ   r   r   )r   r   r   r   r   r   r7   rt   attach_noder9   attach_edger:   attach_branch)r>   r   r   r   r   rJ   r   r   r<   rj   rC   r[   r{   r:   rz   s                  r2   compilezGraph.compile:  sX   > ,1r)/R 	 #c) &6%<!"W	 	 	
 !^C0#~c7JK  %#3"1$
& ))+ 	,IC  d+	, ** 	-JE3  ,	-  $}}224 	<OE8 ( 0 <f&&udF;<	<
   ""r1   )r5   NrA   )NN)NNNFN)#r)   r*   r+   r?   propertyr8   r/   r.   rB   r   r"   r
   r-   r   r   rE   r   r`   r   r   listr   r   ri   rm   ro   rq   r   r   r!   r    boolr   r   r   r0   r1   r2   r4   r4   -   s    Cc3h0   
 .2	 4S>*	
 
   .2 
 4S>* 
  *./
 .2/C%&/ &/
 4S>*/ 
/b#   J EI"// S%$x. 899:S)E(DN*B$CDDES%$x. 899:<
/ 5hm!4d3i!?@A/ sm/ 
/b)3 )4 )( EI"GS%$x. 899:S)E(DN*B$CDDES%$x. 899:<
G 5hm!4d3i!?@AG smG 
G4'C 'D ';(8C="9 ;T ;~ &*<@;?"J# &*%)J#"J# #5d3i#89J# "%T#Y"78	J#
 J# smJ# 	"J# 	"J# 
J#r1   r4   c                   x     e Zd ZU eed<   dededdf fdZdededdfdZ	d	ed
eddfdZ
d	edededdfdZ xZS )r   r   kwargsr5   Nc                2    t        |   di | || _        y )Nr0   )superr?   r   )r>   r   r   	__class__s      r2   r?   zCompiledGraph.__init__  s    "6"r1   rj   rC   c                 ,   t        t              | j                  |<   t        g g |j                        |j
                  z  t        t        |      g      z  | j                  |<   t        t        t           | j                        j                  |       y )N)rX   triggersr'   )r   r   rX   r   r'   r&   r   r   r7   r   r   r.   r   append)r>   rj   rC   s      r2   r   zCompiledGraph.attach_node  su    +C0cR$--Hmm-c2345 	

3
 	T#Y,,-44S9r1   r[   r{   c                 `   |t         k(  r@| j                  |   j                  j                  t	        t        t               g             y | j                  |   j                  j                  |       t        t        t           | j                  |   j                        j                  |       y rA   )r   r7   writersr   r   r   r   r   r   r.   rX   )r>   r[   r{   s      r2   r   zCompiledGraph.attach_edge  sy    #:JJu%%,,\;LS;Q:R-ST JJsO$$++E2cDJJsO445<<UCr1   rJ   rz   c           
      &   	 ddt         t        t        t        f      dt        dt         t        t
        t        f      ffd}t        k(  r;| j                  vr-t        j                  t        t        g      | j                  <   | j                  xx   |j                  |      z  cc<   |j                  r|j                  j                         n| j                  D cg c]  }| c}}|D ]  }|t        k7  sd d d| }t        t               | j"                  |<   | j                  |   j$                  j'                  |       t)        t*        t           | j                  |   j"                        j'                  |        y c c}w )	Npacketsstaticr5   c                     | D cg c]7  }t        |t              s#t        |t        k7  rd d d| nt              n|9 c}S c c}w )Nbranch::)rM   r   r   r   )r   r   prJ   r[   s      r2   
get_writesz/CompiledGraph.attach_branch.<locals>.get_writes  s\     !  &a. &a3hwavQqc&BTWX  s   <A)tagsr   r   )F)r   r   r.   r   r   r   r   r7   r   subscribe_tor   runr(   ru   r   r   r   rX   r   r   r   r   )	r>   r[   rJ   rz   r   rC   r(   r{   channel_names	    ``      r2   r   zCompiledGraph.attach_branch  sH   @E
	eCI./
	9=
	e-t345
	 E>e4::5 ' 4 4U* NDJJu 	

5VZZ
33 (.{{v{{!!#$**8U$8U 	OCcz!(qau=.<S.Al+

3((//=T#Y

3 8 89@@N	O 9Vs   $	F)r)   r*   r+   r4   r,   r   r?   r.   r%   r   r   r   r   __classcell__)r   s   @r2   r   r     s    N5 C D :s :( :t :D D3 D4 DO3 Oc O6 Od Or1   r   )7loggingcollectionsr   collections.abcr   r   r   typingr   r   r	   r
   r   r   r   langchain_core.runnablesr   typing_extensionsr   langgraph.cache.baser   "langgraph.channels.ephemeral_valuer   langgraph.constantsr   r   r   r   r   r   r   langgraph.graph.branchr   langgraph.pregelr   r   langgraph.pregel.readr   langgraph.pregel.writer   r   langgraph.store.baser   langgraph.typesr    r!   langgraph.utils.runnabler"   r#   	getLoggerr)   rO   r%   r4   r   r0   r1   r2   <module>r      s     # 9 9   . " * =   * , , B * - E			8	$Gz GW# W#t
4OF 4Or1   