
    3fi"                        d Z ddlmZ ddlmZmZmZmZmZ erddl	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mZmZ ddlmZ  G d de      Zy)z Question answering over a graph.    )annotations)TYPE_CHECKINGAnyDictListOptionalN)ChainLLMChain)CallbackManagerCallbackManagerForChainRun)BaseLanguageModel)BasePromptTemplate)Field)GRAPHDB_QA_PROMPTGRAPHDB_SPARQL_FIX_PROMPT GRAPHDB_SPARQL_GENERATION_PROMPT)OntotextGraphDBGraphc                  l    e Zd ZU dZ ed      Zded<   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  fdZ
ed!d       Zed!d       Zeeeded	 	 	 	 	 	 	 	 	 	 	 	 	 d"d       Z	 d#	 	 	 	 	 d$dZ	 	 	 	 	 	 	 	 	 	 d%dZ	 	 	 	 	 	 d&dZ	 	 	 	 	 	 d'dZ	 	 	 	 	 	 	 	 d(dZd)dZ xZS )*OntotextGraphDBQAChaina
  Question-answering against Ontotext GraphDB
       https://graphdb.ontotext.com/ by generating SPARQL queries.

    *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   sparql_generation_chainsparql_fix_chainintmax_fix_retriesqa_chainquerystr	input_keyresult
output_keyFboolallow_dangerous_requestsc                V    t        |   di | | j                  durt        d      y)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)selfkwargs	__class__s     r/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_community/chains/graph_qa/ontotext_graphdb.pyr(   zOntotextGraphDBQAChain.__init__@   s9    "6"((4W
 
 5    c                    | j                   gS N)r    )r*   s    r-   
input_keysz!OntotextGraphDBQAChain.input_keysP   s    r.   c                     | j                   g}|S r0   )r"   )r*   _output_keyss     r-   output_keysz"OntotextGraphDBQAChain.output_keysT   s    (r.      )sparql_generation_promptsparql_fix_promptr   	qa_promptc               n    t        ||      }t        ||      }|}t        ||      }	 | d|	|||d|S )zInitialize from LLM.)llmprompt)r   r   r   r   r&   r
   )
clsr:   r6   r7   r   r8   r+   r   r   r   s
             r-   from_llmzOntotextGraphDBQAChain.from_llmY   sY     #+s;S"T#4EF)I6 
$;-+	

 
 	
r.   c                   |xs t        j                         }|j                         }|| j                     }| j                  j
                  }| j                  j                  ||d|      }|| j                  j                     }| j                  ||||      }| j                  |      }	| j                  j                  ||	d|      }
|
| j                  j                     }| j                  |iS )zv
        Generate a SPARQL query, use it to retrieve a response from GraphDB and answer
        the question.
        )r;   schema	callbacks)r;   context)r   get_noop_manager	get_childr    r   
get_schemar   invoker"   _get_prepared_sparql_query_execute_queryr   )r*   inputsrun_manager_run_managerrA   r;   ontology_schemasparql_generation_chain_resultgenerated_sparqlquery_resultsqa_chain_resultr!   s               r-   _callzOntotextGraphDBQAChain._callq   s     #S&@&Q&Q&S **,	'**//)-)E)E)L)L9Y *M *
& :((33
  ::)%5
 ++,<=--..-8I / 
 !!9!9:((r.   c                   	 | j                  ||      S # t        $ r}d}t        |      }| j                  |||       || j                  k  r	 | j
                  j                  |||d|      }|| j
                  j                     }| j                  ||      cY d }~S # t        $ r-}|dz  }t        |      }	| j                  |||	       Y d }~nd }~ww xY w|| j                  k  rY d }~t        d      d }~ww xY w)Nr   )error_messagerN   r?   r@      z&The generated SPARQL query is invalid.)	_prepare_sparql_query	Exceptionr   _log_invalid_sparql_queryr   r   rF   r"   r)   )
r*   rK   rA   rN   rL   eretriesrS   sparql_fix_chain_resultparse_exceptions
             r-   rG   z1OntotextGraphDBQAChain._get_prepared_sparql_query   s"   	--l<LMM 	GFM**. D000.2.C.C.J.J-:0@&5
 #, /K /+ (?--88($  55lDTUU  qLG&)!fO22$&6  D000* ABB9	s?    	C;/C6ABC;	C'#C
C6CC66C;c                F    ddl m}  ||       | j                  ||       |S )Nr   )prepareQuery)rdflib.plugins.sparqlr]   _log_prepared_sparql_query)r*   rK   rN   r]   s       r-   rU   z,OntotextGraphDBQAChain._prepare_sparql_query   s'     	7%&''6FGr.   c                ~    |j                  dd| j                         |j                  |dd| j                         y )NzGenerated SPARQL:
endverbosegreencolorrc   rd   on_textrd   )r*   rK   generated_querys      r-   r_   z1OntotextGraphDBQAChain._log_prepared_sparql_query   s>     	0dDLLQ7dll 	 	
r.   c                    |j                  dd| j                         |j                  |dd| j                         |j                  dd| j                         |j                  |dd| j                         y )NzInvalid SPARQL query: ra   rb   redrf   zSPARQL Query Parse Error: z

rh   )r*   rK   rj   rS   s       r-   rW   z0OntotextGraphDBQAChain._log_invalid_sparql_query   s     	54V5dDLL 	 	
 	(dDLL 	 	
 	FDLL 	 	
r.   c                j    	 | j                   j                  |      S # t        $ r t        d      w xY w)Nz-Failed to execute the generated SPARQL query.)r   r   rV   r)   )r*   r   s     r-   rH   z%OntotextGraphDBQAChain._execute_query   s:    	N::##E** 	NLMM	Ns    2)r+   r   returnNone)rn   z	List[str])r:   r   r6   r   r7   r   r   r   r8   r   r+   r   rn   r   r0   )rI   zDict[str, Any]rJ   z$Optional[CallbackManagerForChainRun]rn   zDict[str, str])
rK   r   rA   r   rN   r   rL   r   rn   r   )rK   r   rN   r   rn   r   )rK   r   rj   r   rn   ro   )rK   r   rj   r   rS   r   rn   ro   )r   r   rn   zList[rdflib.query.ResultRow])__name__
__module____qualname____doc__r   r   __annotations__r    r"   r$   r(   propertyr1   r4   classmethodr   r   r   r=   rQ   rG   rU   r_   rW   rH   __classcell__)r,   s   @r-   r   r      s    #("5E5%%IsJ%*d*        
 8X0I (9

 #5	

 .
 
 &
 
 
 
 
4 =A)) :) 
	)@%C0%C #%C 	%C
 %C 
%CN 6 JM 	 
6
IL
	

0
 
 	

 

"Nr.   r   )rs   
__future__r   typingr   r   r   r   r   rdfliblangchain_classic.chains.baser	   langchain_classic.chains.llmr    langchain_core.callbacks.managerr   r   langchain_core.language_modelsr   langchain_core.prompts.baser   pydanticr   +langchain_community.chains.graph_qa.promptsr   r   r   langchain_community.graphsr   r   r&   r.   r-   <module>r      sH    & " ; ; / 1 X < :  
 <ENU ENr.   