
    (Gg	T                        d dl Z d dl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 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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, d dl-m.Z.m/Z/ d dl0m1Z1m2Z2 d dl3m4Z4m5Z5  ejl                  e7      Z8 G d de	      Z9 G d d      Z G d de(      Z:y)    N)defaultdict)
Any	AwaitableCallableHashable
NamedTupleOptionalSequenceUnioncastoverload)Runnable)RunnableConfig)Graph)Node)Self)EphemeralValue)	EMPTY_SEQENDNS_ENDNS_SEPSTART
TAG_HIDDENSend)Branch)ChannelPregel)PregelProtocol)
PregelNode)ChannelWriteChannelWriteEntry)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     r/home/kushmeetdev/apache_webroot/langgraph_flaskproject/venv/lib/python3.12/site-packages/langgraph/graph/graph.pyr'   r'   ,   sH    )-HhtCH~&-=FD(5sCx$sCx.89
:Fr3   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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 y)&r   returnNc                     i | _         t        t        t        t        f             | _        t        t              | _        d| _        d| _	        y NF)
nodessetr1   r0   edgesr   r/   branchessupport_multiple_edgescompiledselfs    r4   __init__zGraph.__init__3   s;    *,
sCx)+
=H=N&+#r3   c                     | j                   S N)r;   r?   s    r4   
_all_edgeszGraph._all_edges:   s    zzr3   r)   noder)   c                     y rC   r2   )r@   rF   r)   s      r4   add_nodezGraph.add_node>   s     r3   actionc                     y rC   r2   )r@   rF   rI   r)   s       r4   rH   zGraph.add_nodeF   s     r3   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 )N'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rM   trace)
isinstancer0   r   r   
ValueErrorr>   loggerwarninggetattrRuntimeErrorr9   r   r   r'   r%   r   )r@   rF   rI   r)   	characters        r4   rH   zGraph.add_nodeO   s(    dC $f- 	$$I;&ef  ==NN: $$F6676:+FGD| L  >T  4::vdV+=>??3;$%-vdV>:;;&.vDdO5I8'


4T?# r3   	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 )NkAdding 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rC   r2   ).0start_s      r4   	<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>   rR   rS   r   rQ   r   hasattrr:   r;   add)r@   rW   rX   s      r4   add_edgezGraph.add_edgew   s    ==NN: 9::e:;; tZ(Y# >
"&**>
 ;
 .
 /	{ ;R R 
 	

	7+,r3   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 )
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.

        rZ   NTrN   	conditionzBranch with name `z` already exists for node ``F)	r>   rR   rS   r%   rM   r<   rQ   r   	from_path)r@   rd   re   rf   rg   rM   s         r4   add_conditional_edgeszGraph.add_conditional_edges   s    > ==NN: "$T>yy'K4==(($TYYK/NvhVWX  '-&6&6tXtU&Sfd#r3   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.
        )rc   r   r@   rm   s     r4   set_entry_pointzGraph.set_entry_point   s     }}UC((r3   c                 2    | j                  t        |||      S )a  Sets a conditional entry point in the graph.

        Args:
            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[str, 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.
        )rl   r   )r@   re   rf   rg   s       r4   set_conditional_entry_pointz!Graph.set_conditional_entry_point   s    0 ))%xFFr3   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.
        )rc   r   ro   s     r4   set_finish_pointzGraph.set_finish_point   s     }}S#&&r3   	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 'rL   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 `rj   zInterrupt node `z` not foundT)rD   r<   itemsrb   rg   r*   valuesr   r9   r   rQ   updater>   )r@   ru   srcr_   all_sourcesr^   r<   condbranchendrF   rM   specrd   all_targetstargets                   r4   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checkpointerinterrupt_beforeinterrupt_afterdebugrM   CompiledGraphc                 b   |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 )N*)ru   rx   F	LangGraph)builderr9   r[   input_channelsoutput_channelsstream_modestream_channelsr   interrupt_before_nodesinterrupt_after_nodesauto_validater   rM   )r   r   r   r   r   r   r9   rw   attach_noder;   attach_edger<   attach_branch)r@   r   r   r   r   rM   r>   rm   rF   r^   r~   r<   r}   s                r4   compilezGraph.compile0  sR    ,1r)/R 	 #c) &6%<!"W	 	 	
 !^C0#~c7JK  %#3"1$
" ))+ 	,IC  d+	, ** 	-JE3  ,	-  $}}224 	<OE8 ( 0 <f&&udF;<	<
   ""r3   )r6   NrC   )NN)NNNFN)!r+   r,   r-   rA   propertyr:   r1   r0   rD   r   r$   r	   r/   r   r   rH   r   rc   r   r   listr   r   rl   rp   rr   rt   r
   r   r#   r"   boolr   r2   r3   r4   r   r   2   sc    Cc3h0   
 .2	 4S>*	
 
   .2 
 4S>* 
  *.&
 .2&C%&& &&
 4S>*& 
&P#   > 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 ;~ &*<@;?"2#"2# #5d3i#892# "%T#Y"78	2#
 2# sm2# 
2#r3   r   c                       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	 ddddee   deeef   defdZ	 ddddee   deeef   defdZ	 di ddee   deeef   defdZdedeeef   fdZ xZS )r   r   kwargsr6   Nc                2    t        |   di | || _        y )Nr2   )superrA   r   )r@   r   r   	__class__s      r4   rA   zCompiledGraph.__init__h  s    "6"r3   rm   rF   c                 :   t        t              | j                  |<   t        g g |j                        |j
                  z  t        t        |      gt        g      z  | j                  |<   t        t        t           | j                        j                  |       y )N)r[   triggersr)   tags)r   r   r[   r   r)   r(   r    r!   r   r9   r   r   r0   r   append)r@   rm   rF   s      r4   r   zCompiledGraph.attach_nodel  sz    +C0cR$--Hmm-c23:,GH 	

3
 	T#Y,,-44S9r3   r^   r~   c                 n   |t         k(  rG| j                  |   j                  j                  t	        t        t               gt        g             y | j                  |   j                  j                  |       t        t        t           | j                  |   j                        j                  |       y )Nr   )r   r9   writersr   r    r!   r   r   r   r   r0   r[   )r@   r^   r~   s      r4   r   zCompiledGraph.attach_edgeu  s    #:JJu%%,,/45ZLI
 JJsO$$++E2cDJJsO445<<UCr3   rM   r}   c                    dt         t        t        t        f      dt        dt
        t           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configr6   c                     | D cg c]7  }t        |t              s#t        |t        k7  rd d d| nt              n|9 }}t	        t        t        t        t        t        f      |      t        g      S c c}w )Nbranch::r   )	rP   r   r!   r   r    r   r
   r   r   )r   r   pwritesrM   r^   s       r4   branch_writerz2CompiledGraph.attach_branch.<locals>.branch_writer  s     !  &a. &a3hwavQqc&BTWXF   Xe$5t$;<=vF \ s   <A8r   r   r   )r
   r   r0   r   r   r	   r    r   r9   r   subscribe_tor   runr*   rx   r   r   r   r[   r   r   r   r   )	r@   r^   rM   r}   r   rF   r*   r~   channel_names	    ``      r4   r   zCompiledGraph.attach_branch  s:   	eCI./	9G	l#	" E>e4::5 ' 4 4U* NDJJu 	

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

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

3 8 89@@N	O 9Vs   	E?Fxrayr   r   c          	        K   ddl m} r7| j                         2 ci c3 d{   \  }}t        |t        |f      r||"i }| j                  |      S 7 26 nc c}}w }}}t        |t        j                  fd|j                         D          d{  7        D ci c]  \  }}||
 nc c}}w }}}xw);Returns a drawable representation of the computation graph.r   RemoteGraphNc              3   x   K   | ]1  }|j                  t        t              sd k  rndz
         3 yw)r      r   N)
aget_graphrP   r   )r]   r   r   r   s     r4   r`   z+CompiledGraph.aget_graph.<locals>.<genexpr>  sH       !" LL &#-dD#9TQY &*%)AX	 ) s   7:	subgraphs)
langgraph.pregel.remoter   aget_subgraphsrP   r   zipasynciogatherrx   _draw_graph)r@   r   r   r   kv
subpregelsr   s    ``     r4   r   zCompiledGraph.aget_graph  s      	8  #'"5"5"75 5!Qa-!=> 1, I )<<55 5 5J 5  !.. &0%6%6%8
 
 
Aq 1 I sN   B>AAAAAB>AA=B>B
B>&B43B>c                
   ddl m} |ra| j                         D ci c]E  \  }}t        |t        |f      r.||j                  |t        |t              s|dk  r|n|dz
        G }}}ni }| j                  ||      S c c}}w )r   r   r   r   r   r   )r   r   get_subgraphsrP   r   	get_graphr   r   )r@   r   r   r   r   r   r   s          r4   r   zCompiledGraph.get_graph  s     	8  !..0
 Aqa-!=> 1;;!+D$!7419$QR(   I  I )<<s   A
A?r   r   c                    t               t        j                   j                        t              ii 	 	 ddt        dt        dt
        t           dt        dd f
 fd} j                  j                  j                         D ]1  \  }}|j                  }|j                  xs i }| j                  v r| j                  v rd|d<   n'| j                  v rd	|d<   n| j                  v rd
|d<   ||v r||   }|j                          |j!                          t#        |j                        dk\  r?j%                  ||      \  }	}
|	t&        j)                  d| d       |
|
|<   |	|<   j                  |||xs d       }||<   ||<   j                  |||xs d       }||<   ||<   4 t+         j                  j,                        D ]  \  }} |||         j                  j.                  j                         D ]
  \  }}i  j                  j                  D ci c]  }||k7  s	|| c}t0        t0        i}|j                         D ]  \  }}|j2                  |j2                  }nO|j4                  &|D ci c]  }|t0        |j4                  fvs|| }}nt7        t8        t        t        f   |      }|j                         D ]8  \  }} |||||k7  r|nd d       |j4                  & |||j4                         :    j                  j                  j                         D ]  \  }}t;        |j2                  t8              r/|j2                  j                         D ]  \  }} ||||d        Ot;        |j2                  t<              sj|j2                  D ]  } |||d         S c c}w c c}w )Nr^   r~   labelconditionalr6   c                     |t         k(  r4t         vr,j                  j                        t               t         <   | vs|vrt        j	                  d|  d| d       y j                  |    |   |t        |      |      S d |      S )NzCould not add edge from 'z' to 'z' due to missing nodes)r   rH   get_output_schemarR   rS   rc   r0   )	r^   r~   r   r   r   	end_nodesgraphr@   start_nodess	       r4   rc   z+CompiledGraph._draw_graph.<locals>.add_edge  s     czc2!&0F0Fv0NPS!T	#K'3i+?/wfSEAWX >>E"##/E
	  6:	 r3   zbefore,after__interruptbeforeafterr   )prefixzCould not extend subgraph 'z' due to missing entrypointrE   T)r   r8   )DrawableGraphr   rH   get_input_schemar0   r	   r   r   r   r9   rw   r(   r)   r   r   trim_first_nodetrim_last_nodelenextendrR   rS   sortedrD   r<   r   r*   rg   r   r/   rP   r1   )r@   r   r   rc   rm   nrF   r)   subgraphesnnr^   r~   r<   r   default_endsr_   r}   r*   r   r   r   r   s   ``                   @@@r4   r   zCompiledGraph._draw_graph  s    5>>$"7"7"?G0
 .0	
 )- %				 H%	 		
 	 	( ll((..0 	$FC::Dzz'RHd111cT=W=W6W*8'333*2'222*1'i$S>((*'')x~~&!+ <<<=DAqy9#>YZ !}+,C(%&IcNcH<LMB')K$%'IcN^^D#8HD^I#%C !#	#=	$> !!8!89 	!JE3UC 	!#||44::< 	3OE8!%!3!3BAqEz1a4BSL &^^- 3	6;;*!;;D[[,*6VQ!CCU:UAqDVDVXs] 3\BD"&**, 3JE3!&#4$(	 {{. fkk233	3* ll((..0 	9FC!&&$'"#&&,,. @JCS#u$?@AFFE*66 9CS#489	9 7 C Ws   8
OOO1Oc                 V    t        |       | j                         j                         dS )z0Mime bundle used by Jupyter to display the graph)z
text/plainz	image/png)reprr   draw_mermaid_png)r@   r   s     r4   _repr_mimebundle_zCompiledGraph._repr_mimebundle_B  s(     t*)::<
 	
r3   rC   )r+   r,   r-   r   r.   r   rA   r0   r'   r   r   r   r   r	   r   r   intr   r   r   r   r/   r   r   __classcell__)r   s   @r4   r   r   e  s^   N5 C D :s :( :t :	D 	D3 	D4 	DO3 Oc O6 Od OF ,0%= "'	%=(%= CI	%=
 
%=R ,0= "'	=(= CI	=
 
=6 ,0_ /1	_(_ ]*+	_
 
_B
# 
$sCx. 
r3   r   );r   loggingcollectionsr   typingr   r   r   r   r   r	   r
   r   r   r   langchain_core.runnablesr   langchain_core.runnables.configr   langchain_core.runnables.graphr   r   r   DrawableNodetyping_extensionsr   "langgraph.channels.ephemeral_valuer   langgraph.constantsr   r   r   r   r   r   r   langgraph.graph.branchr   langgraph.pregelr   r   langgraph.pregel.protocolr   langgraph.pregel.readr   langgraph.pregel.writer    r!   langgraph.typesr"   r#   langgraph.utils.runnabler$   r%   	getLoggerr+   rR   r'   r   r2   r3   r4   <module>r      s      #   . : A ? " =   * , 4 , B - E			8	$Gz Gp# p#f	b
F b
r3   