
    Ng7                         d dl Z d dlmZmZ d dlmZmZmZmZm	Z	m
Z
  G d de          Z G d de          Z G d d	e          Z G d
 de          ZdS )    N)ABCabstractmethod)AnyDictListOptionalTupleUnionc                   F    e Zd ZdZdeeef         fdZdefdZde	fdZ
dS )NeptuneQueryExceptionz"Exception for the Neptune queries.	exceptionc                     t          |t                    r(d|v r|d         nd| _        d|v r|d         nd| _        d S || _        d| _        d S )Nmessageunknowndetails)
isinstancedictr   r   )selfr   s     d/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/graphs/neptune_graph.py__init__zNeptuneQueryException.__init__	   s`    i&& 	%3<	3I3I9Y//yDL3<	3I3I9Y//yDLLL$DL$DLLL    returnc                     | j         S N)r   r   s    r   get_messagez!NeptuneQueryException.get_message   
    |r   c                     | j         S r   )r   r   s    r   get_detailsz!NeptuneQueryException.get_details   r   r   N)__name__
__module____qualname____doc__r
   strr   r   r   r   r    r   r   r   r      st        ,,%%T	"2 % % % %S    S      r   r   c                   &   e Zd ZdZedefd            Zei fdededefd            Z	ede
fd            Zdeee         ee         f         fdZd	ee         dee         fd
Zdee         de
defdZd	ee         de
eef         defdZddZdS )BaseNeptuneGraphz Abstract base class for Neptune.r   c                     | j         S )z)Return the schema of the Neptune database)schemar   s    r   
get_schemazBaseNeptuneGraph.get_schema   s     {r   queryparamsc                     t                      r   NotImplementedError)r   r+   r,   s      r   r+   zBaseNeptuneGraph.query        !###r   c                     t                      r   r.   r   s    r   _get_summaryzBaseNeptuneGraph._get_summary$   r0   r   c                 R    |                                  }|d         }|d         }||fS )z<Get node and edge labels from the Neptune statistics summary
nodeLabels
edgeLabels)r2   )r   summaryn_labelse_labelss       r   _get_labelszBaseNeptuneGraph._get_labels(   s2    ##%%<(<(!!r   r8   c                    d}d}g }|D ]}}|                     |          }|                     |          }|D ]M}|                     |d         d         |d         |d         d                   }	|                    |	           N~|S )	Nz
        MATCH (a)-[e:`{e_label}`]->(b)
        WITH a,e,b LIMIT 3000
        RETURN DISTINCT labels(a) AS from, type(e) AS edge, labels(b) AS to
        LIMIT 10
        z(:`{a}`)-[:`{e}`]->(:`{b}`)e_labelfromr   edgeto)aeb)formatr+   append)
r   r8   triple_querytriple_templatetriple_schemalabelqdatadtriples
             r   _get_tripleszBaseNeptuneGraph._get_triples/   s     8 	- 	-E##E#22A::a==D - -(//ilai1T71: 0   $$V,,,,	- r   r7   typesc           
         d}g }|D ]}|                     |          }||                     |          d}t          i           }|d         D ]Q}	|	d                                         D ]4\  }
}|                    |
|t          |          j                 f           5Rd |D             |d}|                    |           |S )Nz_
        MATCH (a:`{n_label}`)
        RETURN properties(a) AS props
        LIMIT 100
        )n_labelrH   
propertiesrR   propsc                     g | ]
\  }}||d S )propertytyper%   .0kvs      r   
<listcomp>z9BaseNeptuneGraph._get_node_properties.<locals>.<listcomp>T   $    HHHdaAq99HHHr   )rR   labelsrC   r+   setitemsaddrW   r    rD   )r   r7   rN   node_properties_querynode_propertiesrH   rI   rJ   sprZ   r[   nps                r   _get_node_propertiesz%BaseNeptuneGraph._get_node_propertiesD   s    !
  	' 	'E%,,U,;;A"$**Q--@@DBA,' 8 8gJ,,.. 8 8DAqEE1eDGG$45677778 IHaHHH B ""2&&&&r   c           
         d}g }|D ]}|                     |          }||                     |          d}t          i           }|d         D ]Q}	|	d                                         D ]4\  }
}|                    |
|t          |          j                 f           5R|d |D             d}|                    |           |S )Nzf
        MATCH ()-[e:`{e_label}`]->()
        RETURN properties(e) AS props
        LIMIT 100
        r;   rQ   rR   rS   c                     g | ]
\  }}||d S rU   r%   rX   s      r   r\   z9BaseNeptuneGraph._get_edge_properties.<locals>.<listcomp>l   r]   r   )rW   rR   r_   )r   r8   rN   edge_properties_queryedge_propertiesrH   rI   rJ   re   rf   rZ   r[   eps                r   _get_edge_propertiesz%BaseNeptuneGraph._get_edge_properties[   s    !
  	' 	'E%,,U,;;A"$**Q--@@DBA,' 8 8gJ,,.. 8 8DAqEE1eDGG$45677778 HHaHHH B ""2&&&&r   Nc                     ddddddd}|                                  \  }}|                     |          }|                     ||          }|                     ||          }d| d	| d
| d| _        dS )zA
        Refreshes the Neptune graph schema information.
        STRINGDOUBLEINTEGERLISTMAPBOOLEAN)r$   floatintlistr   boolz4
        Node properties are the following:
        z<
        Relationship properties are the following:
        z6
        The relationships are the following:
        z	
        N)r9   rM   rh   rn   r)   )r   rN   r7   r8   rG   rd   rl   s          r   _refresh_schemaz BaseNeptuneGraph._refresh_schemar   s     
 
 "--//())(3333HeDD33HeDD	  
	  
  r   )r   N)r    r!   r"   r#   rV   r$   r*   r   r   r+   r   r2   r	   r   r9   rM   rh   r   rn   rz   r%   r   r   r'   r'      sq       **C    X /1 $ $3 $ $d $ $ $ ^$ $d $ $ $ ^$"U49d3i#78 " " " "T#Y 49    *T#Y t     .T#Y tCH~ RV    .     r   r'   c                       e Zd ZdZ	 	 	 ddededee         dee         ddf
dZi fd	ed
ede	eef         fdZ
de	fdZdS )NeptuneAnalyticsGraphaY  Neptune Analytics wrapper for graph operations.

    Parameters:
        client: optional boto3 Neptune client
        credentials_profile_name: optional AWS profile name
        region_name: optional AWS region, e.g., us-west-2
        graph_identifier: the graph identifier for a Neptune Analytics graph

    Example:
        .. code-block:: python

        graph = NeptuneAnalyticsGraph(
            graph_identifier='<my-graph-id>'
        )

    *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.
    Ngraph_identifierclientcredentials_profile_nameregion_namer   c                 P   	 ||| _         nqddl}||                    |          }n|                                }|| _        |r|                     d|          | _         n|                     d          | _         nb# t          $ r t	          d          t
          $ r=}t          |          j        dk    rt	          d          |t          d	          |d}~ww xY w	 | 	                                 dS # t
          $ r$}t          d
t          |          d          d}~ww xY w)z6Create a new Neptune Analytics graph wrapper instance.Nr   profile_namezneptune-graph)r   RCould not import boto3 python package. Please install it with `pip install boto3`.UnknownServiceErrorzgNeptuneGraph requires a boto3 version 1.34.40 or greater.Please install it with `pip install -U boto3`.Could not load credentials to authenticate with AWS client. Please check that credentials in the specified profile name are valid.)Could not get schema for Neptune databaser   detail)r~   boto3Sessionr}   ImportError	ExceptionrW   r    
ValueErrorrz   r   r$   )r   r}   r~   r   r   r   sessionrA   s           r   r   zNeptuneAnalyticsGraph.__init__   s   %	!$+7#mm9QmRRGG $mmooG(8% B")..'[ #1 # #DKK #*.."A"ADK 	 	 	>    	 	 	Aww#888!E  
 !.  			  """"" 	 	 	'J!!ff   	s0   A;A> >"C 8CC!C7 7
D%D  D%r+   r,   c                 6   	 | j                             | j        ||d          }t          j        |d                                                             d                    d         S # t          $ r$}t          dt          |          d          d}~ww xY w)	Query Neptune database.OPEN_CYPHER)graphIdentifierqueryString
parameterslanguagepayloadzUTF-8results,An error occurred while executing the query.r   r   N)
r~   execute_queryr}   jsonloadsreaddecoder   r   r$   )r   r+   r,   resprA   s        r   r+   zNeptuneAnalyticsGraph.query   s    	;,, $ 5!!&	 -  D :d9o2244;;GDDEEiPP 	 	 	'M"1vv   	s   A'A* *
B4BBc                 .   	 | j                             | j        d          }n1# t          $ r$}t	          dt          |          d          d }~ww xY w	 |d         }|S # t          $ r* t	          d|j                                        d          w xY w)Ndetailed)r   modez/Summary API error occurred on Neptune Analyticsr   graphSummary,Summary API did not return a valid response.)r~   get_graph_summaryr}   r   r   r$   contentr   r   responserA   r6   s       r   r2   z"NeptuneAnalyticsGraph._get_summary   s    
	{44 $ 5J 5  HH  	 	 	' Q"1vv   	
	~.G N  	 	 	'M'/6688   	s    !$ 
AAAA   4B)NNN)r    r!   r"   r#   r$   r   r   r   r   r   r+   r2   r%   r   r   r|   r|      s         < 26%)8 88 8 #+3-	8
 c]8 
8 8 8 8t 02  3  d38n    $d      r   r|   c                       e Zd ZdZ	 	 	 	 	 	 ddedededed	ee         d
ee         deddfdZ	i fdede
deeef         fdZdefdZdS )NeptuneGrapha  Neptune wrapper for graph operations.

    Parameters:
        host: endpoint for the database instance
        port: port number for the database instance, default is 8182
        use_https: whether to use secure connection, default is True
        client: optional boto3 Neptune client
        credentials_profile_name: optional AWS profile name
        region_name: optional AWS region, e.g., us-west-2
        sign: optional, whether to sign the request payload, default is True

    Example:
        .. code-block:: python

        graph = NeptuneGraph(
            host='<my-cluster>',
            port=8182
        )

    *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.
      TNhostport	use_httpsr~   r   r   signr   c                    	 ||| _         nddl}||                    |          }	n|                                }	i }
|r||
d<   |rdnd}| d| d| |
d	<   |r |	j         di |
| _         n-ddlm} ddlm}  |	j         	 di |
d ||          i| _         nb# t          $ r t          d          t          $ r=}t          |          j
        dk    rt          d          |t          d          |d}~ww xY w	 |                                  dS # t          $ r$}t          dt          |          d          d}~ww xY w)z,Create a new Neptune graph wrapper instance.Nr   r   r   httpshttpz://:endpoint_urlneptunedata)UNSIGNED)Configconfig)signature_versionr   r   zgNeptuneGraph requires a boto3 version 1.28.38 or greater.Please install it with `pip install -U boto3`.r   r   r   )r   )r~   r   r   botocorer   botocore.configr   r   r   rW   r    r   rz   r   r$   )r   r   r   r   r~   r   r   r   r   r   client_paramsprotocolr   r   rA   s                  r   r   zNeptuneGraph.__init__0  s   0	!$+7#mm9QmRRGG $mmooG " ?3>M-0&/;77V3;0M0M0M0Mt0M0Mn- 
"0'."P"P-"P"PDKK111111666666"0'.%# #'# #  &vAAA# # #DK  	 	 	>    	 	 	Aww#888!E  
 !.  			  """"" 	 	 	'J!!ff   	s0   BB "C;>8C66C;?D 
ED>>Er+   r,   c                     	 | j                             |          d         S # t          $ r$}t          dt	          |          d          d}~ww xY w)r   )openCypherQueryr   r   r   N)r~   execute_open_cypher_queryr   r   r$   )r   r+   r,   rA   s       r   r+   zNeptuneGraph.queryx  ss    
	;888OO   	 	 	'M"1vv   	s    # 
AAAc                 *   	 | j                                         }n1# t          $ r$}t          dt	          |          d          d }~ww xY w	 |d         d         }|S # t          $ r* t          d|j                                        d          w xY w)Nz`Summary API is not available for this instance of Neptune,ensure the engine version is >=1.2.1.0r   r   r   r   )r~   get_propertygraph_summaryr   r   r$   r   r   r   s       r   r2   zNeptuneGraph._get_summary  s    	{<<>>HH 		 		 		'A  #1vv   		
	y).9G N  	 	 	'M'/6688   	s     
A
AA
A 4B)r   TNNNT)r    r!   r"   r#   r$   rw   ry   r   r   r   r   r   r+   r2   r%   r   r   r   r     s        D 26%)F FF F 	F
 F #+3-F c]F F 
F F F FP 02  3  d38n    d      r   r   )r   abcr   r   typingr   r   r   r   r	   r
   r   r   r'   r|   r   r%   r   r   <module>r      s&    # # # # # # # # : : : : : : : : : : : : : : : :    I   $s s s s ss s s sl    ,   DN N N N N# N N N N Nr   