a
    bg                     @   sl   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 deZdS )    N)AnyDictListOptionalUnion)get_from_env)GraphDocumentNodeRelationship)
GraphStorec                   @   s   e Zd ZdZeeeef dddZd e	e e	e e	e ee	e dddd	Z
eedd
dZddddZi feeeeeef  dddZd!ee eddddZeedddZeedddZi feeedddZeedd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                 C   s   | j S N)structured_schemaself r   v/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_community/graphs/gremlin_graph.pyget_structured_schema&   s    z"GremlinGraph.get_structured_schemaNg)urlusernamepasswordtraversal_sourcemessage_serializerr   c           	      C   s   z4ddl }ddlm}m} tjdkr2||  W n tyN   tdY n0 |j	t
dd||t
dd	|t
d
d||r||n| d| _d| _dS )z,Create a new Gremlin graph wrapper instance.r   N)client
serializerwin32z@Please install gremlin-python first: `pip3 install gremlinpythonr   ZGREMLIN_URIr   ZGREMLIN_USERNAMEr   ZGREMLIN_PASSWORD)r   r   r   r   r    )asyncioZgremlin_python.driverr   r   sysplatformset_event_loop_policyZWindowsSelectorEventLoopPolicyImportErrorZClientr   ZGraphSONSerializersV2d0schema)	r   r   r   r   r   r   r   r   r   r   r   r   __init__*   s&    	




	zGremlinGraph.__init__c                 C   s   t | jdkr|   | jS )z*Returns the schema of the Gremlin databaser   )lenr$   refresh_schemar   r   r   r   
get_schemaJ   s    zGremlinGraph.get_schemac                 C   sz   | 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   )Zvertex_labelsZedge_labelsZ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   Zvertex_schemaZedge_schemaZvertex_propertiesr   r   r   r'   Q   s(    
	zGremlinGraph.refresh_schema)queryparamsr   c                 C   s   | j |}|  S r   )r   r+   r,   r-   )r   r/   r0   qr   r   r   r/   o   s    zGremlinGraph.queryF)graph_documentsinclude_sourcer   c              
   C   s   i }|D ]}|rN|j j|j jd}t|j j  }| t|d|d|}|j	D ]>}| |}	|rT| 
td||	i d | 
td|	|i d qT|jD ]*}
| |
j | | |
j| | 
|
 qqdS )zN
        Take GraphDocument as input as uses it to construct a graph.
        )page_contentmetadataZDocument)idtype
propertieszcontains information about)r7   sourcetargetr8   zis extracted fromN)r9   r4   r5   hashlibmd5encode	hexdigestadd_noder	   nodesadd_edger
   Zrelationshipsr:   )r   r2   r3   
node_cacheZdocumentZ	doc_propsZdoc_idZdoc_nodennodeelr   r   r   add_graph_documentss   sB    



z GremlinGraph.add_graph_documents)rD   r   c                 C   sj   d|j  dd|j d d|j  d d|j d }|j D ]\}}|d| d| d7 }qB|d	 S )
Nzg.V().has('id','z	').fold()z.coalesce(unfold(),addV('')z.property('id','z.property('type','.property('', '))r6   r7   r8   items)r   rD   
base_querykeyvaluer   r   r   build_vertex_query   s    zGremlinGraph.build_vertex_query)relationshipr   c              	   C   s   d|j j d}d|jj d}d| d| d|j d|j d	dd	d
d	}|j D ]\}}|d| d| d7 }q\|S )Nz.has('id','rG   z"g.V()z.as('a')  
            .V()z7.as('b') 
            .choose(
                __.inE('zR').where(outV().as('a')),
                __.identity(),
                __.addE('z7').from('a').to('b')
            )        
            r)   r   	rH   rI   )r9   r6   r:   r7   replacer8   rK   )r   rP   Zsource_queryZtarget_queryrL   rM   rN   r   r   r   build_edge_query   s     zGremlinGraph.build_edge_query)rD   rB   r   c                 C   s^   d|j vr|j|j d< |j|v r*||j S | |}| j|  d }|||j< |S d S )Nlabelr   )r8   r7   r6   rO   r   r+   r,   r-   )r   rD   rB   r/   _r   r   r   r?      s    




zGremlinGraph.add_nodec                 C   s   |  |}| j|  S r   )rS   r   r+   r,   r-   )r   rP   r/   r   r   r   rA      s    
zGremlinGraph.add_edge)NNNr   N)F)__name__
__module____qualname____doc__propertyr   strr   r   r   r%   r(   r'   dictr   r/   r   boolrF   r	   rO   r
   rS   r?   rA   r   r   r   r   r      s:         " 2r   )r;   r    typingr   r   r   r   r   Zlangchain_core.utilsr   Z)langchain_community.graphs.graph_documentr   r	   r
   Z&langchain_community.graphs.graph_storer   r   r   r   r   r   <module>   s   