a
    bgE/                     @  s  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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$ dZ%dZ&dddddZ'ddddddZ(G dd deZ)dS )z Question answering over a graph.    )annotationsN)AnyDictListOptionalUnion)Chain)CallbackManagerForChainRun)BaseLanguageModel)	AIMessageBaseMessageSystemMessageToolMessage)StrOutputParser)BasePromptTemplateChatPromptTemplateHumanMessagePromptTemplateMessagesPlaceholder)Runnable)Field)MEMGRAPH_GENERATION_PROMPTMEMGRAPH_QA_PROMPT)MemgraphGraph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!
str)textreturnc                 C  s$   d}t || t j}|r |d S | 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matches r"   z/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_community/chains/graph_qa/memgraph.pyextract_cypher*   s    
r$   zList[Dict[str, Any]]zList[BaseMessage])questioncontextr   c                 C  s@   d}t dd|d|  d dddd	gid
tt||dg}|S )NZcall_H7fABDuzEau48T10Qn0Lsh0D Z
tool_callsz{"question":"z"}ZGetInformation)	argumentsnamefunction)idr*   type)contentZadditional_kwargs)r-   Ztool_call_id)r   r   r   )r%   r&   ZTOOL_IDmessagesr"   r"   r#   get_function_response<   s     
r/   c                      s.  e Zd ZU dZed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dd fddZedddd Zeddd!d"Zed	dd#d$Zed3d%d%d%d%d%d%ded&d'd(d(d'd)d*d*dd	dd d+d,d-Zd4d.d/d.d0d1d2Z  ZS )5MemgraphQAChaina  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_chainqa_chainr   graph_schemaquery	input_keyresult
output_key
   inttop_kFboolreturn_intermediate_stepsreturn_directuse_function_responseallow_dangerous_requestsr   None)kwargsr   c                   s(   t  jf 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__rA   
ValueError)selfrC   	__class__r"   r#   rE      s
    
zMemgraphQAChain.__init__z	List[str])r   c                 C  s   | j gS )z7Return the input keys.

        :meta private:
        )r7   rG   r"   r"   r#   
input_keys   s    zMemgraphQAChain.input_keysc                 C  s   | j g}|S )z8Return the output keys.

        :meta private:
        )r9   )rG   Z_output_keysr"   r"   r#   output_keys   s    zMemgraphQAChain.output_keysc                 C  s   dS )NZgraph_cypher_chainr"   rJ   r"   r"   r#   _chain_type   s    zMemgraphQAChain._chain_typeN)	qa_promptcypher_prompt
cypher_llmqa_llmqa_llm_kwargscypher_llm_kwargsr@   function_response_systemzOptional[BaseLanguageModel]zOptional[BasePromptTemplate]z'Optional[Union[BaseLanguageModel, Any]]zOptional[Dict[str, Any]])llmrN   rO   rP   rQ   rR   rS   r@   rT   rC   r   c             	   K  s  |s|st d|s |s t d|r4|r4|r4t d|rD|rDt d|rT|rTt d|dur`|ni }|durp|ni }d|vr|dur|nt|d< d|vr|dur|nt|d< |p|}|rz>|i  tt|	dtd	t	d
dg}||B t
 B }W n  ttfy   t dY n0 n|d |B t
 B }|d }|durD|n|}|durl|durl||B t
 B }nt d|
d j}| f ||||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)r-   z
{question}function_response)Zvariable_namez4Provided LLM does not support native tools/functionszNMissing required components for the cypher generation chain: 'prompt' or 'llm'r2   )r5   r4   r3   r@   )rF   r   r   Z
bind_toolsr   Zfrom_messagesr   r   Zfrom_templater   r   NotImplementedErrorAttributeErrorZ
get_schema)clsrU   rN   rO   rP   rQ   rR   rS   r@   rT   rC   Zuse_qa_llm_kwargsZuse_cypher_llm_kwargsZresponse_promptr4   rV   Z
llm_to_user3   r5   r"   r"   r#   from_llm   sr    

zMemgraphQAChain.from_llmzDict[str, Any]z$Optional[CallbackManagerForChainRun])inputsrun_managerr   c                 C  s@  |p
t  }| }|| j }|| jd}|| g }| jj||d}t|}|j	dd| j
d |j	|dd| j
d |d|i |r| j|d	| j }	ng }	| jr|	}
nt|j	d
d| j
d |j	t|	dd| j
d |d|	i | jrt||	}| j||d}
n| jj||	d|d}
d|
i}| jr<||t< |S )zGGenerate Cypher statement, use it to look up in db and answer question.)r%   Zschema)	callbackszGenerated Cypher:
)endverbosegreen)colorr`   ra   r6   NzFull Context:r&   )r%   rW   )r%   r&   r8   )r	   Zget_noop_managerZ	get_childr7   r5   updater3   Zinvoker$   Zon_textra   appendr2   r6   r<   r?   r   r@   r/   r4   r>   INTERMEDIATE_STEPS_KEY)rG   r\   r]   Z_run_managerr^   r%   argsr   Zgenerated_cypherr&   r8   rW   Zchain_resultr"   r"   r#   _call   sP    



zMemgraphQAChain._call)N)N)__name__
__module____qualname____doc__r   r2   __annotations__r7   r9   r<   r>   r?   r@   rA   rE   propertyrK   rL   rM   classmethodFUNCTION_RESPONSE_SYSTEMr[   rh   __classcell__r"   r"   rH   r#   r0   U   sB   
 ([ r0   )*rl   
__future__r   r   typingr   r   r   r   r   Zlangchain.chains.baser   Zlangchain_core.callbacksr	   Zlangchain_core.language_modelsr
   Zlangchain_core.messagesr   r   r   r   Zlangchain_core.output_parsersr   Zlangchain_core.promptsr   r   r   r   Zlangchain_core.runnablesr   Zpydanticr   Z+langchain_community.chains.graph_qa.promptsr   r   Z)langchain_community.graphs.memgraph_graphr   rf   rp   r$   r/   r0   r"   r"   r"   r#   <module>   s$   