
    Ng6=                       d Z ddlm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 ddlmZ ddlm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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(m)Z) ddl*m+Z+ dZ,dZ- eddd          d,d            Z. eddd          d-d"            Z/ eddd#          d.d(            Z0 eddd)           G d* d+e                      Z1dS )/z Question answering over a graph.    )annotationsN)AnyDictListOptionalUnion)Chain)LLMChain)
deprecated)CallbackManagerForChainRun)BaseLanguageModel)	AIMessageBaseMessageSystemMessageToolMessage)StrOutputParser)BasePromptTemplateChatPromptTemplateHumanMessagePromptTemplateMessagesPlaceholder)Runnable)Field)CypherQueryCorrectorSchema)CYPHER_GENERATION_PROMPTCYPHER_QA_PROMPT)
GraphStoreintermediate_stepszYou are an assistant that helps to form nice and human 
understandable answers based on the provided information from tools.
Do not add any other information that wasn't present in the tools, and use 
very concise style in interpreting results!
z0.3.8z1.0z5langchain_neo4j.chains.graph_qa.cypher.extract_cypher)sinceremovalalternative_importtextstrreturnc                ^    d}t          j        || t           j                  }|r|d         n| S )zExtract Cypher code from a text.

    Args:
        text: Text to extract Cypher code from.

    Returns:
        Cypher code extracted from the text.
    z```(.*?)```r   )refindallDOTALL)r"   patternmatchess      f/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/chains/graph_qa/cypher.pyextract_cypherr,   0   s3     G j$	22G *71::d*    z7langchain_neo4j.chains.graph_qa.cypher.construct_schemastructured_schemaDict[str, Any]include_types	List[str]exclude_typesc           
     f   dfdfd|                      di                                           D             fd|                      d	i                                           D             fd
|                      dg           D             d}g }|d                                         D ]?\  }}d                    d |D                       }|                    | d| d           @g }|d	                                         D ]?\  }	}d                    d |D                       }|                    |	 d| d           @d |d         D             }
d                    dd                    |          dd                    |          dd                    |
          g          S )z5Filter the schema based on included or excluded typesxr#   r$   boolc                    r| v n| vS N )r4   r2   r0   s    r+   filter_funcz%construct_schema.<locals>.filter_funcS   s    %2NqM!!8NNr-   c                2    i | ]\  }} |          ||S r8   r8   .0kvr9   s      r+   
<dictcomp>z$construct_schema.<locals>.<dictcomp>W   s=     
 
 
1{1~~
q
 
 
r-   
node_propsc                2    i | ]\  }} |          ||S r8   r8   r;   s      r+   r?   z$construct_schema.<locals>.<dictcomp>\   s=     
 
 
1{1~~
q
 
 
r-   	rel_propsc                N    g | ] t          fd dD                       !S )c              3  :   K   | ]} |                   V  d S r7   r8   )r<   tr9   rs     r+   	<genexpr>z.construct_schema.<locals>.<listcomp>.<genexpr>d   s1      GG;;qt$$GGGGGGr-   )startendtype)all)r<   rF   r9   s    @r+   
<listcomp>z$construct_schema.<locals>.<listcomp>a   sQ     
 
 
GGGGG.FGGGGG

 
 
r-   relationships)r@   rB   rM   z, c                4    g | ]}|d           d|d          S propertyz: rJ   r8   r<   props     r+   rL   z$construct_schema.<locals>.<listcomp>l   /    JJJtZ 22DL22JJJr-   z {}c                4    g | ]}|d           d|d          S rO   r8   rQ   s     r+   rL   z$construct_schema.<locals>.<listcomp>t   rS   r-   c           	     J    g | ] }d |d          d|d          d|d          d!S )z(:rH   z)-[:rJ   z]->(:rI   )r8   r<   els     r+   rL   z$construct_schema.<locals>.<listcomp>y   sO        	<R[;;bj;;r%y;;;  r-   
z"Node properties are the following:,z*Relationship properties are the following:z$The relationships are the following:)r4   r#   r$   r5   )getitemsjoinappend)r.   r0   r2   filtered_schemaformatted_node_propslabel
properties	props_strformatted_rel_propsrel_typeformatted_relsr9   s    ``        @r+   construct_schemarh   G   sg   O O O O O O O
 
 
 
)--lB??EEGG
 
 


 
 
 
)--k2>>DDFF
 
 


 
 
 
&**?B??
 
 
' 'O& ,\:@@BB @ @zIIJJzJJJ
 
	 	##u$>$>$>$>$>????  / < B B D D B B*IIJJzJJJ
 
	 	""h#@#@9#@#@#@AAAA !/2  N
 990HH)**8HH())2HH^$$	
	 	 	r-   z<langchain_neo4j.chains.graph_qa.cypher.get_function_responsequestioncontextList[Dict[str, Any]]List[BaseMessage]c                    d}t          dd|d| z   dz   dddd	gi
          t          t          |          |          g}|S )Ncall_H7fABDuzEau48T10Qn0Lsh0D 
tool_callsz{"question":"z"}GetInformation)	argumentsnamefunction)idrt   rJ   )contentadditional_kwargs)rv   tool_call_id)r   r   r#   )ri   rj   TOOL_IDmessagess       r+   get_function_responser{      s}     .G%)88)Cd)J$4% % !+ 		
 	
 	
 	CLLw???!H$ Or-   z"langchain_neo4j.GraphCypherQAChainc                  l    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<   	 d; fd Zed<d"            Zed<d#            Zed=d$            Ze	 d>ddddg g dddded%d?d5            Z	 d>d@d:Z xZS )AGraphCypherQAChaina  Chain for question-answering against a graph by generating Cypher 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
   cypher_generation_chainzUnion[LLMChain, Runnable]qa_chainr#   graph_schemaquery	input_keyresult
output_key
   inttop_kFr5   return_intermediate_stepsreturn_directNzOptional[CypherQueryCorrector]cypher_query_correctoruse_function_response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.Nr8   )super__init__r   
ValueError)selfr   	__class__s     r+   r   zGraphCypherQAChain.__init__   sN    ""6"""(44W
 
 
 54r-   r1   c                    | j         gS )z7Return the input keys.

        :meta private:
        )r   r   s    r+   
input_keyszGraphCypherQAChain.input_keys   s     r-   c                    | j         g}|S )z8Return the output keys.

        :meta private:
        )r   )r   _output_keyss     r+   output_keyszGraphCypherQAChain.output_keys   s     (r-   c                    dS )Ngraph_cypher_chainr8   r   s    r+   _chain_typezGraphCypherQAChain._chain_type   s    ##r-   )	qa_promptcypher_prompt
cypher_llmqa_llmr2   r0   validate_cypherqa_llm_kwargscypher_llm_kwargsr   function_response_systemllmOptional[BaseLanguageModel]r   Optional[BasePromptTemplate]r   r   r   'Optional[Union[BaseLanguageModel, Any]]r2   r0   r   r   Optional[Dict[str, Any]]r   r   c          	        |s|st          d          |s|st          d          |r|r|rt          d          |r|
rt          d          |r|	rt          d          |	|	ni }|
|
ni }d|vr||nt          |d<   d|vr||nt          |d<   |p|}|r	 |                    i            t	          j        t          |          t          j        d	          t          d
          g          }||z  t                      z  }n2# t          t          f$ r t          d          w xY wt          dd|i|}t          dd|p|i|}|r|rt          d          t          |d         j        ||          }d}|r9d |d         j                            d          D             }t%          |          } | d|||||d|S )zInitialize from LLM.z8Either `llm` or `cypher_llm` parameters must be providedz4Either `llm` or `qa_llm` parameters must be providedzaYou can specify up to two of 'cypher_llm', 'qa_llm', and 'llm', but not all three simultaneously.zqSpecifying cypher_prompt and cypher_llm_kwargs together is not allowed. Please pass prompt via cypher_llm_kwargs.zeSpecifying qa_prompt and qa_llm_kwargs together is not allowed. Please pass prompt via qa_llm_kwargs.Nprompt)rv   z
{question}function_response)variable_namez4Provided LLM does not support native tools/functionsr   zGEither `exclude_types` or `include_types` can be provided, but not bothr   c                T    g | ]%}t          |d          |d         |d                   &S )rH   rJ   rI   )r   rX   s     r+   rL   z/GraphCypherQAChain.from_llm.<locals>.<listcomp>U  s@           r'{BvJ5	::     r-   rM   )r   r   r   r   r   r8   )r   r   r   
bind_toolsr   from_messagesr   r   from_templater   r   NotImplementedErrorAttributeErrorr
   rh   get_structured_schemar.   r\   r   )clsr   r   r   r   r   r2   r0   r   r   r   r   r   r   use_qa_llm_kwargsuse_cypher_llm_kwargsresponse_promptr   r   r   r   corrector_schemas                         r+   from_llmzGraphCypherQAChain.from_llm   s	   (  	Y# 	YWXXX 	Uc 	USTTT 	& 	S 	A    	. 	J    	 	F   .;-FMMB!2!>B 	 ,,,&2		8H h' 000!.!:@X "(+ 3  	AY!!"%%%"4"B%.FGGG2@NN+:MNNN# # +V3o6G6GG'8 Y Y Y !WXXXY  @@F@.?@@H"* #
 #
!c#
##
 #

  	] 	0   (7O1=-
 
 "& 	L    /;??PP      &::J%K%K"s 
%$;#9"7
 
 
 
 	
s   A.D !D)inputsr/   run_manager$Optional[CallbackManagerForChainRun]c                   |pt          j                    }|                                }|| j                 }|| j        d}|                    |           g }| j                            ||          }t          |          }| j	        r| 	                    |          }|
                    dd| j                   |
                    |dd| j                   |                    d|i           |r(| j                            |          d	| j                 }	ng }	| j        r|	}
n|
                    d
d| j                   |
                    t#          |	          dd| j                   |                    d|	i           | j        r.t'          ||	          }| j                            ||d          }
n1| j                            ||	d|          }|| j        j                 }
| j        |
i}| j        r
||t0          <   |S )zGGenerate Cypher statement, use it to look up in db and answer question.)ri   schema)	callbackszGenerated Cypher:rZ   )rI   verbosegreen)colorrI   r   r   NzFull Context:rj   )ri   r   )ri   rj   )r   get_noop_manager	get_childr   r   updater   runr,   r   on_textr   r_   r   r   r   r   r#   r   r{   r   invoker   r   INTERMEDIATE_STEPS_KEY)r   r   r   _run_managerr   ri   argsr   generated_cypherrj   final_resultr   r   chain_results                 r+   _callzGraphCypherQAChain._calld  sh    #S&@&Q&S&S **,,	$.) '
 
 	F#%7;;DI;VV **:;; & 	M#::;KLL0dDLQQQGt| 	 	
 	
 	
 	!!7,<"=>>>  	j&&'7884:FGGG 	@"LL  dDL QQQ  GGt| !    %%y'&:;;;) 
@$9(G$L$L!#}33!)@QRR    --!)g>>' .    &dm&>?(,'F) 	F3EL/0r-   )r   r   r$   r   )r$   r1   )r$   r#   r7   )r   r   r   r   r   r   r   r   r   r   r2   r1   r0   r1   r   r5   r   r   r   r   r   r5   r   r#   r   r   r$   r}   )r   r/   r   r   r$   r/   )__name__
__module____qualname____doc__r   r   __annotations__r   r   r   r   r   r   r   r   r   rP   r   r   r   classmethodFUNCTION_RESPONSE_SYSTEMr   r   __classcell__)r   s   @r+   r}   r}      s          d+++E++++%%%%''''IJEOOOO4&+++++VMM=AAAAA)"'''''H%*****             X     X $ $ $ X$  ,0a
 376:26:>#%#% %266:&+(@a
 a
 a
 a
 a
 [a
L =AA A A A A A A A Ar-   r}   )r"   r#   r$   r#   )r.   r/   r0   r1   r2   r1   r$   r#   )ri   r#   rj   rk   r$   rl   )2r   
__future__r   r&   typingr   r   r   r   r   langchain.chains.baser	   langchain.chains.llmr
   langchain_core._api.deprecationr   langchain_core.callbacksr   langchain_core.language_modelsr   langchain_core.messagesr   r   r   r   langchain_core.output_parsersr   langchain_core.promptsr   r   r   r   langchain_core.runnablesr   pydanticr   0langchain_community.chains.graph_qa.cypher_utilsr   r   +langchain_community.chains.graph_qa.promptsr   r   &langchain_community.graphs.graph_storer   r   r   r,   rh   r{   r}   r8   r-   r+   <module>r      s   & & " " " " " " 				 3 3 3 3 3 3 3 3 3 3 3 3 3 3 ' ' ' ' ' ' ) ) ) ) ) ) 6 6 6 6 6 6 ? ? ? ? ? ? < < < < < <            : 9 9 9 9 9            . - - - - -                     > = = = = =-   
N  
+ + + 
+$ 
P  
; ; ; 
;| 
U  
   
2 
;  
x x x x x x x 
x x xr-   