
    Ng                     z    d dl Z d dlZd dlmZmZmZmZmZ d dlm	Z	 d dl
mZmZmZ d dlmZ  G d de          ZdS )    N)AnyDictListOptionalUnion)get_from_env)GraphDocumentNodeRelationship)
GraphStorec                   ^   e Zd ZdZedeeef         fd            Z	 	 	 	 	 dde	e         de	e         de	e         d	ed
e	e         ddfdZ
edefd            ZddZi fdededeeeef                  fdZ	 ddee         deddfdZdedefdZdedefdZi fdededefdZdedefdZdS )GremlinGrapha  Gremlin wrapper for graph operations.

    Parameters:
    url (Optional[str]): The URL of the Gremlin database server or env GREMLIN_URI
    username (Optional[str]): The collection-identifier like '/dbs/database/colls/graph'
                               or env GREMLIN_USERNAME if none provided
    password (Optional[str]): The connection-key for database authentication
                              or env GREMLIN_PASSWORD if none provided
    traversal_source (str): The traversal source to use for queries. Defaults to 'g'.
    message_serializer (Optional[Any]): The message serializer to use for requests.
                                        Defaults to serializer.GraphSONSerializersV2d0()
    *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.

    *Implementation details*:
        The Gremlin queries are designed to work with Azure CosmosDB limitations
    returnc                     | j         S N)structured_schemaselfs    d/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/graphs/gremlin_graph.pyget_structured_schemaz"GremlinGraph.get_structured_schema&   s    %%    Ngurlusernamepasswordtraversal_sourcemessage_serializerc           
         	 ddl }ddlm}m} t          j        dk    r'|                    |                                           n# t          $ r t          d          w xY w|	                    t          dd|          |t          dd	|          t          d
d|          |r|n|                                          | _        d| _        dS )z,Create a new Gremlin graph wrapper instance.r   N)client
serializerwin32z@Please install gremlin-python first: `pip3 install gremlinpythonr   GREMLIN_URIr   GREMLIN_USERNAMEr   GREMLIN_PASSWORD)r   r   r   r   r    )asynciogremlin_python.driverr   r    sysplatformset_event_loop_policyWindowsSelectorEventLoopPolicyImportErrorClientr   GraphSONSerializersV2d0schema)	r   r   r   r   r   r   r&   r   r    s	            r   __init__zGremlinGraph.__init__*   s    
	NNN@@@@@@@@|w&&--g.T.T.V.VWWW 	 	 	U  	
 mmUM377-!*.@(KK!*.@(KK! 6113355 $ 
 
 s   AA A c                 h    t          | j                  dk    r|                                  | j        S )z*Returns the schema of the Gremlin databaser   )lenr/   refresh_schemar   s    r   
get_schemazGremlinGraph.get_schemaJ   s3     t{q  !!!{r   c                 ,   | j                             d                                                                          }| j                             d                                                                          }| j                             d                                                                          d         }|||d| _        d                    dd                    |          d	d                    |          d
| g          | _        dS )zA
        Refreshes the Gremlin graph schema information.
        zg.V().label().dedup()zg.E().label().dedup()z?g.V().group().by(label).by(properties().label().dedup().fold())r   )vertex_labelsedge_labelsvertice_props
z Vertex labels are the following:,zEdge labes are the following:z$Vertices have following properties:
N)r   submitallresultr   joinr/   )r   vertex_schemaedge_schemavertex_propertiess       r   r3   zGremlinGraph.refresh_schemaQ   s    **+BCCGGIIPPRRk(()@AAEEGGNNPPKQ  SUUVXXa	 	 +&."
 "
 ii2''/%%K8IKK
 
r   queryparamsc                     | j                             |          }|                                                                S r   )r   r;   r<   r=   )r   rB   rC   qs       r   rB   zGremlinGraph.queryo   s/    Ku%%uuww~~r   Fgraph_documentsinclude_sourcec           
         i }|D ]H}|r|j         j        |j         j        d}t          j        |j         j                                                                                  }|                     t          |d|          |          }|j	        D ]e}|                     |          }	|rL| 
                    t          d||	i                      | 
                    t          d|	|i                      f|j        D ]M}
|                     |
j         |           |                     |
j        |           | 
                    |
           NJdS )zN
        Take GraphDocument as input as uses it to construct a graph.
        )page_contentmetadataDocument)idtype
propertieszcontains information about)rM   sourcetargetrN   zis extracted fromN)rO   rI   rJ   hashlibmd5encode	hexdigestadd_noder
   nodesadd_edger   relationshipsrP   )r   rF   rG   
node_cachedocument	doc_propsdoc_iddoc_nodennodeels              r   add_graph_documentsz GremlinGraph.add_graph_documentss   s    35
' )	" )	"H 	 %-O$@ ( 8 	 !X_%A%H%H%J%JKKUUWW==F	JJJJ 
 ^  }}Q''! MM$!=#+#'')	     MM$!4#'#+')	     , " "bi444bi444b!!!!"G)	" )	"r   r_   c                     d|j          dd|j         dz   d|j          dz   d|j         dz   }|j                                        D ]\  }}|d| d| dz  }|d	z   S )
Nzg.V().has('id','z	').fold()z.coalesce(unfold(),addV('')z.property('id','z.property('type','.property('', '))rL   rM   rN   items)r   r_   
base_querykeyvalues        r   build_vertex_queryzGremlinGraph.build_vertex_query   s    1tw1117$)7778,,,,- 1490001 	 ///11 	; 	;JC:::::::JJCr   relationshipc           	         d|j         j         d}d|j        j         d}d| d| d|j         d|j         d	                    dd	                              d
d	          }|j                                        D ]\  }}|d| d| dz  }|S )Nz.has('id','rc   z"g.V()z.as('a')  
            .V()z7.as('b') 
            .choose(
                __.inE('zR').where(outV().as('a')),
                __.identity(),
                __.addE('z7').from('a').to('b')
            )        
            r9   r%   	rd   re   )rO   rL   rP   rM   replacerN   rg   )r   rl   source_querytarget_queryrh   ri   rj   s          r   build_edge_queryzGremlinGraph.build_edge_query   s    ?\%8%;????\%8%;???    &* 
 '+   b!!''$"3"3 	 '17799 	; 	;JC:::::::JJr   rY   c                 (   d|j         vr|j        |j         d<   |j        |v r||j                 S |                     |          }| j                            |                                                                          d         }|||j        <   |S )Nlabelr   )rN   rM   rL   rk   r   r;   r<   r=   )r   r_   rY   rB   _s        r   rU   zGremlinGraph.add_node   s    $/))'+yDOG$7j  dg&&++D11E""5))--//6688;A"&JtwKr   c                     |                      |          }| j                            |                                                                          S r   )rr   r   r;   r<   r=   )r   rl   rB   s      r   rW   zGremlinGraph.add_edge   sC    %%l33{!!%((,,..55777r   )NNNr   N)r   N)F)__name__
__module____qualname____doc__propertyr   strr   r   r   r0   r4   r3   dictr   rB   r	   boolra   r
   rk   r   rr   rU   rW    r   r   r   r      s        4 &tCH~ & & & X&
 ""&"& #,0 c] 3- 3-	
  %SM 
   @ C    X
 
 
 
< 02    3    d4S>6J        
 LQ0" 0"#M20"DH0"	0" 0" 0" 0"d
 t 
  
  
  
  
 \ c    " 79 
 
T 
t 
T 
 
 
 
8\ 8c 8 8 8 8 8 8r   r   )rQ   r(   typingr   r   r   r   r   langchain_core.utilsr   )langchain_community.graphs.graph_documentr	   r
   r   &langchain_community.graphs.graph_storer   r   r   r   r   <module>r      s     



 3 3 3 3 3 3 3 3 3 3 3 3 3 3 - - - - - - W W W W W W W W W W = = = = = =E8 E8 E8 E8 E8: E8 E8 E8 E8 E8r   