
    dh*                     L    S SK Jr  S SKJrJrJrJr  S SKJrJ	r	   " S S5      r
g)    )md5)AnyDictListTuple)GraphDocumentRelationshipc            
           \ rS rSrSr SS\S\S\SS4S jjr\	S\4S	 j5       r
0 4S
\S\S\\\\4      4S jjrSS jrSS jrS\SS4S jrS\SS4S jr SS\\   S\\\\\4      S\SS4S jjrSrg)	KuzuGraph   u  Kùzu wrapper for graph operations.

*Security note*: Make sure that the database connection uses credentials
    that are narrowly-scoped to only include necessary permissions.
    Failure to do so may result in data corruption or loss, since the calling
    code may attempt commands that would result in deletion, mutation
    of data if appropriately prompted or reading sensitive data if such
    data is present in the database.
    The best way to guard against such negative outcomes is to (as appropriate)
    limit the permissions granted to the credentials used with this tool.

    See https://python.langchain.com/docs/security for more information.
dbdatabaseallow_dangerous_requestsreturnNc                     USLa  [        S5      e SSKnXl        UR	                  U R                  5      U l        X l        U R                  5         g! [         a    [        S5      ef = f)u0   Initializes the Kùzu graph database connection.TzThe KuzuGraph class is a powerful tool that can be used to execute arbitrary queries on the database. To enable this functionality, set the `allow_dangerous_requests` parameter to `True` when constructing the KuzuGraph object.r   NuS   Could not import Kùzu python package.Please install Kùzu with `pip install kuzu`.)
ValueErrorkuzuImportErrorr   
Connectionconnr   refresh_schema)selfr   r   r   r   s        ]/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_community/graphs/kuzu_graph.py__init__KuzuGraph.__init__   sv    
 $4/5 	 OODGG,	   	@ 	s   A A)c                     U R                   $ )u(   Returns the schema of the Kùzu database)schemar   s    r   
get_schemaKuzuGraph.get_schema/   s     {{    queryparamsc                    U R                   R                  X5      nUR                  5       n/ nUR                  5       (       aJ  UR	                  5       nUR                  [        [        XF5      5      5        UR                  5       (       a  MJ  U$ )u   Query Kùzu database)r   executeget_column_nameshas_nextget_nextappenddictzip)r   r"   r#   resultcolumn_namesreturn_listrows          r   r"   KuzuGraph.query4   sq    ""51..0oo//#CtC$:;< oo r!   c           
         / nU R                   R                  5       nU H  n/ US.nU R                   R                  U5      nU Hm  nXV   S   nSnXV   S   S:  a<  SXV   ;   a  XV   S    H  n	USU	 S3-  nM     O[        XV   S   5       H  n
US	-  nM
     Xx-  nUS
   R	                  UU45        Mo     UR	                  U5        M     / nU R                   R                  5       nU H'  nUR	                  SUS    SUS    SUS    S35        M)     / nU H  nUS   n/ US.nU R                   R                  SU S35      nUR                  5       (       aG  UR                  5       nUS   nUS   nUS
   R	                  UU45        UR                  5       (       a  MG  UR	                  U5        M     SU SU SU S3U l	        g)u,   Refreshes the Kùzu graph schema information)
propertieslabeltype 	dimensionr   shape[]z[]r2   z(:srcz)-[:namez]->(:dst)zCALL table_info('z') RETURN *;      zNode properties: z
Relationships properties: z
Relationships: 
N)
r   _get_node_table_names_get_node_property_namesranger)   _get_rel_table_namesr%   r'   r(   r   )r   node_propertiesnode_table_names
table_namecurrent_table_schemar2   property_nameproperty_typelist_type_flagsirelationships
rel_tablestablerel_propertiesquery_resultr/   	prop_name	prop_types                      r   r   KuzuGraph.refresh_schema>   s,   99::<*J24z#J ;;JGJ!+ * 9& A!#,[9A=*";;!+!:7!CA*!Ah6N "D "'z'@'M!NA*d2N "O/$\299%% "," ""#78) +, YY335
E  U5\N$uV}oU5<.J  
 EvJ24z#J 99,,#J<|<L ''))"++-F	F	$\2999i:PQ	 ''))
 !!"67    0 1))7(8 9+_B0 	r!   c                 :    U R                   R                  S5        g )Nz
            CREATE NODE TABLE IF NOT EXISTS Chunk (
                id STRING,
                text STRING,
                type STRING,
                PRIMARY KEY(id)
            );
            r   r%   r   s    r   _create_chunk_node_table"KuzuGraph._create_chunk_node_tables   s    				
r!   
node_labelc                 B    U R                   R                  SU S35        g )Nz-
            CREATE NODE TABLE IF NOT EXISTS zv (
                id STRING,
                type STRING,
                PRIMARY KEY(id)
            );
            rW   )r   rZ   s     r   _create_entity_node_table#KuzuGraph._create_entity_node_table   s(    		--7L 9	
r!   relc           	          U R                   R                  SUR                   SUR                  R                   SUR                  R                   S35        g )Nz,
            CREATE REL TABLE IF NOT EXISTS z (
                FROM z TO z
            );
            )r   r%   r4   sourcetarget)r   r^   s     r   !_create_entity_relationship_table+KuzuGraph._create_entity_relationship_table   sN    		,,/HH: 6jjoo&d3::??*; <	
r!   graph_documentsallowed_relationshipsinclude_sourcec                 <   [        U VVs1 sH   oDR                   H  oUR                  iM     M"     snn5      nU GH  nU(       a  U R                  5         UR                  R
                  R                  S5      (       dS  [        UR                  R                  R                  S5      5      R                  5       UR                  R
                  S'   U R                  R                  SUR                  R
                  S   UR                  R                  S.S9  U H  nU R                  U5        M     UR                   GH  nU R                  R                  SUR                   S3SUR                  0S9  U(       d  MA  U R                  5         Sn/ n	U H  nU	R                  S	U 35        M     [        [!        U	5      5      n	US
R#                  U	5      -  nUS-  nU(       a  U R                  R                  U5        UR                  U;   d  M  U R                  R                  SUR                   S3UR                  R
                  S   UR                  S.S9  GM"     UR$                   H  n
U R'                  U
5        U
R                  R                  nU
R                  R                  nU
R(                  R                  nU
R(                  R                  nU R                  R                  SU SU SU
R                   S3UUS.S9  M     GM     gs  snnf )u  
Adds a list of `GraphDocument` objects that represent nodes and relationships
in a graph to a Kùzu backend.

Parameters:
  - graph_documents (List[GraphDocument]): A list of `GraphDocument` objects
    that contain the nodes and relationships to be added to the graph. Each
    `GraphDocument` should encapsulate the structure of part of the graph,
    including nodes, relationships, and the source document information.

  - allowed_relationships (List[Tuple[str, str, str]]): A list of allowed
    relationships that exist in the graph. Each tuple contains three elements:
    the source node type, the relationship type, and the target node type.
    Required for Kùzu, as the names of the relationship tables that need to
    pre-exist are derived from these tuples.

  - include_source (bool): If True, stores the source document
    and links it to nodes in the graph using the `MENTIONS` relationship.
    This is useful for tracing back the origin of data. Merges source
    documents based on the `id` property from the source document metadata
    if available; otherwise it calculates the MD5 hash of `page_content`
    for merging process. Defaults to False.
idzutf-8z
                    MERGE (c:Chunk {id: $id}) 
                        SET c.text = $text,
                            c.type = "text_chunk"
                    )rh   text)
parametersz
                    MERGE (e:zN {id: $id})
                        SET e.type = "entity"
                    z/CREATE REL TABLE GROUP IF NOT EXISTS MENTIONS (zFROM Chunk TO z, z), label STRING, triplet_source_id STRING)z]
                            MATCH (c:Chunk {id: $id}),
                                  (e:z {id: $node_id})
                            MERGE (c)-[m:MENTIONS]->(e)
                          SET m.triplet_source_id = $id
                            )rh   node_idz
                    MATCH (e1:z4 {id: $source_id}),
                            (e2:z4 {id: $target_id})
                    MERGE (e1)-[:z]->(e2)
                    )	source_id	target_idN)listnodesr4   rX   r`   metadatagetr   page_contentencode	hexdigestr   r%   r\   rh   r)   setjoinrN   rb   ra   )r   rd   re   rf   documentnodenode_labelsrZ   ddltable_namesr^   source_labelrl   target_labelrm   s                  r   add_graph_documentsKuzuGraph.add_graph_documents   s   < '6R8>>4YY>YR
 (H --///33D9958 44;;GD6ik OO,,T2 		!! 'oo66t< ( < <  " 
 *
..z: * !		!!"ii[ ) !%dgg "  "> 113KC"$K&1
#**^J<+HI '2"&s;'7"8K499[11CFFC		))#. yyK/		))!&&*ii[ 1  '/oo&>&>t&D+/77( * 3 'N  --66s;"zzJJMM	"zzJJMM			!!+n -!!- /""%(( , &/%.  " 
 .E ( Ss   &L
)r   r   r   r   )r   F)r   N)F)__name__
__module____qualname____firstlineno____doc__r   strboolr   propertyr   r*   r   r   r"   r   rX   r\   r	   rb   r   r   r~   __static_attributes__ r!   r   r   r      s     QV!$IM	2 C   02 3  d4S>6J 3
j

	
C 	
D 	

\ 
d 
  %	um,u  $E#sC-$89u 	u
 
u ur!   r   N)hashlibr   typingr   r   r   r   )langchain_community.graphs.graph_documentr   r	   r   r   r!   r   <module>r      s     ) ) QA Ar!   