
    Ngp'                        d Z ddlmZ ddlZddl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 ddlmZ  G d de
          ZdS )z Question answering over a graph.    )annotationsN)AnyDictListOptional)ChainLLMChain)CallbackManagerForChainRun)BaseLanguageModel)BasePromptTemplate)Field)AQL_FIX_PROMPTAQL_GENERATION_PROMPTAQL_QA_PROMPT)ArangoGraphc                  N    e Zd ZU dZ ed          Zded<   ded<   ded<   ded	<   d
Zded<   dZded<   dZ	ded<   dZ
ded<   dZded<   dZded<   dZded<   dZded<   	 d2 fdZed3d!            Zed3d"            Zed4d#            Zeeeed$d5d+            Z	 d6d7d1Z xZS )8ArangoGraphQAChaina  Chain for question-answering against a graph by generating AQL statements.

    *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.
    T)excluder   graphr
   aql_generation_chainaql_fix_chainqa_chainquerystr	input_keyresult
output_key
   inttop_k aql_examplesFboolreturn_aql_queryreturn_aql_result   max_aql_generation_attemptsallow_dangerous_requestskwargsr   returnNonec                j     t                      j        di | | j        durt          d          dS )zInitialize the chain.Ta  In order to use this chain, you must acknowledge that it can make dangerous requests by setting `allow_dangerous_requests` to `True`.You must narrowly scope the permissions of the database connection to only include necessary permissions. Failure to do so may result in data corruption or loss or reading sensitive data if such data is present in the database.Only use this chain if you understand the risks and have taken the necessary precautions. See https://python.langchain.com/docs/security for more information.N )super__init__r)   
ValueError)selfr*   	__class__s     h/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/chains/graph_qa/arangodb.pyr0   zArangoGraphQAChain.__init__K   sN    ""6"""(44W
 
 
 54    	List[str]c                    | j         gS N)r   r2   s    r4   
input_keyszArangoGraphQAChain.input_keys[   s    r5   c                    | j         gS r8   )r   r9   s    r4   output_keyszArangoGraphQAChain.output_keys_   s      r5   c                    dS )Ngraph_aql_chainr.   r9   s    r4   _chain_typezArangoGraphQAChain._chain_typec   s      r5   )	qa_promptaql_generation_promptaql_fix_promptllmr   r@   r   rA   rB   c                   t          ||          }t          ||          }t          ||          } | d|||d|S )zInitialize from LLM.)rC   prompt)r   r   r   r.   r	   )	clsrC   r@   rA   rB   r*   r   r   r   s	            r4   from_llmzArangoGraphQAChain.from_llmg   sm     I666'C8MNNN S@@@s 
!5'
 
 	
 
 	
r5   NinputsDict[str, Any]run_manager$Optional[CallbackManagerForChainRun]c                V   |pt          j                    }|                                }|| j                 }| j                            | j        j        | j        |d|          }d}d}d}	d}
|	|
| j	        dz   k     rsd}t          j        ||t          j                  }|sM|                    dd| j        	           |                    |d
d| j                   t          d|           |d         }|                    d|
 d| j                   |                    |dd| j                   ddlm} 	 | j                            || j                  }	n~# |$ rv}|j        }|                    dd| j        	           |                    |dd| j                   | j                            | j        j        ||d|          }Y d}~nd}~ww xY w|
dz  }
|	|
| j	        dz   k     s|	d| d}t          |          |                    dd| j        	           |                    t-          |	          dd| j                   |                     | j        j        |||	d|          }| j        || j        j                 i}| j        r||d<   | j        r|	|d<   |S )aw  
        Generate an AQL statement from user input, use it retrieve a response
        from an ArangoDB Database instance, and respond to the user input
        in natural language.

        Users can modify the following ArangoGraphQAChain Class Variables:

        :var top_k: The maximum number of AQL Query Results to return
        :type top_k: int

        :var aql_examples: A set of AQL Query Examples that are passed to
            the AQL Generation Prompt Template to promote few-shot-learning.
            Defaults to an empty string.
        :type aql_examples: str

        :var return_aql_query: Whether to return the AQL Query in the
            output dictionary. Defaults to False.
        :type return_aql_query: bool

        :var return_aql_result: Whether to return the AQL Query in the
            output dictionary. Defaults to False
        :type return_aql_result: bool

        :var max_aql_generation_attempts: The maximum amount of AQL
            Generation attempts to be made prior to raising the last
            AQL Query Execution Error. Defaults to 3.
        :type max_aql_generation_attempts: int
        )
adb_schemar#   
user_input)	callbacksr"   N   z```(?i:aql)?(.*?)```zInvalid Response: 
)endverbosered)colorrR   rS   zResponse is Invalid: r   zAQL Query (z):)rS   green)AQLQueryExecuteErrorzAQL Query Execution Error: yellowz

)rM   	aql_query	aql_errorz
                Maximum amount of AQL Query Generation attempts reached.
                Unable to execute the AQL Query due to the following error:
                z
            zAQL Result:)rM   rN   rY   
aql_resultrY   r[   )r   get_noop_manager	get_childr   r   runr   schemar#   r(   refindallDOTALLon_textrS   r1   arangorW   r   r!   error_messager   r   r   r   r%   r&   )r2   rH   rJ   _run_managerrO   rN   aql_generation_outputrY   rZ   r[   aql_generation_attemptpatternmatchesrW   emr   s                    r4   _callzArangoGraphQAChain._call}   s   B #S&@&Q&S&S **,,	DN+
 !% 9 = ="j/ $ 1( 
   !> !
 !
 		
!" &)IA)MMM .Gj*?KKG R$$(dDL %    $$)D$, %    !!P9N!P!PQQQ
I   84888$, !      dDL !    433333!Z--iDD

'   O	$$1tT\ %    $$X64< %    )-(:(>(>&*j&7%.%. 
 ( )? ) )%%%%%%0 #a'"q &)IA)MMMr    A
 Q--]dlKKK
OO7dl 	 	
 	
 	
 "j/(&(	     
 
 /6$-*B#CD  	,"+F;! 	.#-F< s   > E G$A,GG)r*   r   r+   r,   )r+   r6   )r+   r   )rC   r   r@   r   rA   r   rB   r   r*   r   r+   r   r8   )rH   rI   rJ   rK   r+   rI   )__name__
__module____qualname____doc__r   r   __annotations__r   r   r!   r#   r%   r&   r(   r)   r0   propertyr:   r<   r?   classmethodr   r   r   rG   rm   __classcell__)r3   s   @r4   r   r      s          t,,,E,,,,""""IJ EOOOO L #"""" $#### ()((((%*****             X  ! ! ! X! ! ! ! X! 
 )64I-;
 
 
 
 
 [
0 =AT T T T T T T T Tr5   r   )rq   
__future__r   r`   typingr   r   r   r   langchain.chains.baser   langchain.chains.llmr
   langchain_core.callbacksr   langchain_core.language_modelsr   langchain_core.promptsr   pydanticr   +langchain_community.chains.graph_qa.promptsr   r   r   )langchain_community.graphs.arangodb_graphr   r   r.   r5   r4   <module>r      s;   & & " " " " " " 				 , , , , , , , , , , , , ' ' ' ' ' ' ) ) ) ) ) ) ? ? ? ? ? ? < < < < < < 5 5 5 5 5 5               
 B A A A A Az z z z z z z z z zr5   