
    Ng#%                        d Z ddlm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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 dZddZ G d de	          ZdS )z Question answering over a graph.    )annotations)AnyDictListOptional)ChainLLMChain)CallbackManagerCallbackManagerForChainRun)BaseLanguageModel)BasePromptTemplate)PromptTemplate)Field)CYPHER_QA_PROMPTGRAPHDB_SPARQL_FIX_TEMPLATEGREMLIN_GENERATION_PROMPT)GremlinGraphintermediate_stepstextstrreturnc                    |                      dd          } |                     d          r| t          d          d         } |                      dd          S )zExtract Gremlin code from a text.

    Args:
        text: Text to extract Gremlin code from.

    Returns:
        Gremlin code extracted from the text.
    ` gremlinN
)replace
startswithlen)r   s    g/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/chains/graph_qa/gremlin.pyextract_gremlinr"      sU     <<R  Dy!! &C	NN$$%<<b!!!    c                      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<   	 dA fdZedBd            ZedBd             Ze eg d! ej        d"d#                              d$d%          &          eed'dCd.            Z	 dDdEd5ZdFd7ZdGd=ZdHd@Z xZS )IGremlinQAChaina  Chain for question-answering against a graph by generating gremlin 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
   gremlin_generation_chainqa_chaingremlin_fix_chain   intmax_fix_retriesqueryr   	input_keyresult
output_keyd   top_kFboolreturn_directreturn_intermediate_stepsallow_dangerous_requestskwargsr   r   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__r7   
ValueError)selfr8   	__class__s     r!   r=   zGremlinQAChain.__init__Q   sN    ""6"""(44W
 
 
 54r#   	List[str]c                    | j         gS )z,Input keys.

        :meta private:
        )r/   )r?   s    r!   
input_keyszGremlinQAChain.input_keysa   s     r#   c                    | j         g}|S )z-Output keys.

        :meta private:
        )r1   )r?   _output_keyss     r!   output_keyszGremlinQAChain.output_keysi   s     (r#   error_messagegenerated_sparqlschemaSPARQLGremlinzin Turtle formatr   )input_variablestemplate)gremlin_fix_prompt	qa_promptgremlin_promptllmr   rO   r   rP   rQ   c                   t          ||          }t          ||          }t          ||          } | d|||d|S )zInitialize from LLM.)rR   prompt)r)   r(   r*   r;   r	   )	clsrR   rO   rP   rQ   r8   r)   r(   gremlinl_fix_chains	            r!   from_llmzGremlinQAChain.from_llmr   sn      I666#+N#K#K#K %#6HIIIs 
%=0
 
 	
 
 	
r#   NinputsDict[str, Any]run_manager$Optional[CallbackManagerForChainRun]Dict[str, str]c                d   |pt          j                    }|                                }|| j                 }g }| j                            || j        j        d|          }t          || j        j	                           }|
                    dd| j                   |
                    |dd| j                   |                    d|i           |r%|                     |||          d	| j                 }	ng }	| j        r|	}
n|
                    d
d| j                   |
                    t!          |	          dd| j                   |                    d|	i           | j                            ||	d|          }|| j        j	                 }
| j	        |
i}| j        r
||t&          <   |S )zHGenerate gremlin statement, use it to look up in db and answer question.)questionrJ   	callbackszGenerated gremlin:r   endverbosegreencolorrb   rc   r.   NzFull Context:context)r^   rg   )r   get_noop_manager	get_childr/   r(   invoker'   
get_schemar"   r1   on_textrc   appendexecute_with_retryr3   r5   r   r)   r6   INTERMEDIATE_STEPS_KEY)r?   rX   rZ   _run_managerr`   r^   r   chain_responsegenerated_gremlinrg   final_resultr0   chain_results                r!   _callzGremlinQAChain._call   s    #S&@&Q&S&S **,,	$.)#%6==!TZ-BCCy > 
 
 ,48CD
 
 	1tT\RRRW$ 	 	
 	
 	
 	!!7,=">??? 	--i): 
lGG G 	<"LL  dDL QQQ  GGt| !    %%y'&:;;;]))%'::# *  F "$-":;L(,'F) 	F3EL/0r#   	List[Any]c                    	 | j                             |          S # t          $ rE}t          |d          rt	          |j                  t	          t          |                    d }~ww xY w)Nstatus_message)r'   r.   	Exceptionhasattrr>   rx   r   )r?   r.   es      r!   execute_queryzGremlinQAChain.execute_query   st    	):##E*** 	) 	) 	)q*++ ) !1222 Q(((		)s    
A+A A&&A+rp   r   r`   r   rr   c                   	 |                      |          S # t          $ r}d}t          |          }|                     |||           || j        k     r	 | j                            ||| j        d|          }|| j        j                 }|                      |          cY d }~S # t          $ r5}|dz  }t          |          }	|                     |||	           Y d }~nd }~ww xY w|| j        k     Y d }~nd }~ww xY wt          d          )Nr   rG   r_      z'The generated Gremlin query is invalid.)
r|   ry   r   log_invalid_queryr-   r*   rj   rJ   r1   r>   )
r?   rp   r`   rr   r{   retriesrH   fix_chain_resultfixed_gremlinparse_exceptions
             r!   rn   z!GremlinQAChain.execute_with_retry   so   	Y%%&7888 	Y 	Y 	YGFFM""<1BMRRRD000Y'+'='D'D-:0A&*k	  #, (E ( ($ %5T5K5V$WM--m<<<<<<<<  Y Y YqLG&)!ffO**<XXXXXXXXY D000	Y. BCCCs?    
C=3C8AB& C=&
C%0+C C8 C%%C88C=generated_queryrH   c                    |                     dd| j                   |                     |dd| j                   |                     dd| j                   |                     |dd| j                   d S )NzInvalid Gremlin query: r   ra   redre   zGremlin Query Parse Error: z

)rl   rc   )r?   rp   r   rH   s       r!   r   z GremlinQAChain.log_invalid_query   s     	6D$,WWW5dDL 	 	
 	
 	
 	)tT\ 	 	
 	
 	
 	FDL 	 	
 	
 	
 	
 	
r#   )r8   r   r   r9   )r   rA   )rR   r   rO   r   rP   r   rQ   r   r8   r   r   r%   )N)rX   rY   rZ   r[   r   r\   )r.   r   r   rv   )rp   r   r`   r   rr   r   r   rv   )rp   r   r   r   rH   r   r   r9   )__name__
__module____qualname____doc__r   r'   __annotations__r-   r/   r1   r3   r5   r6   r7   r=   propertyrC   rF   classmethodr   r   r   r   r   rW   ru   r|   rn   r   __classcell__)r@   s   @r!   r%   r%   (   s&           %---E----&&&&OIJEM&+++++%*****             X     X 
 2@KKK8089MMUU"B 2
 2
 2
 )9-F
 
 
 
 
 [
8 =A6 6 6 6 6p) ) ) )D D D DB
 
 
 
 
 
 
 
r#   r%   N)r   r   r   r   ) r   
__future__r   typingr   r   r   r   langchain.chains.baser   langchain.chains.llmr
    langchain_core.callbacks.managerr   r   langchain_core.language_modelsr   langchain_core.promptsr   langchain_core.prompts.promptr   pydanticr   +langchain_community.chains.graph_qa.promptsr   r   r   langchain_community.graphsr   ro   r"   r%   r;   r#   r!   <module>r      sc   & & " " " " " " , , , , , , , , , , , , ' ' ' ' ' ' ) ) ) ) ) ) X X X X X X X X < < < < < < 5 5 5 5 5 5 8 8 8 8 8 8               
 4 3 3 3 3 3- " " " "U
 U
 U
 U
 U
U U
 U
 U
 U
 U
r#   