
    3fi!                        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 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 dZdZ eddge      ZddZ eddd       G d de	             Z y)z;
Question answering over an RDF or OWL graph using SPARQL.
    )annotations)AnyDictListOptional)Chain)LLMChain)
deprecated)CallbackManagerForChainRun)BaseLanguageModel)BasePromptTemplate)PromptTemplate)Field)SPARQL_QA_PROMPT)NeptuneRdfGraphintermediate_stepsa4  
Task: Generate a SPARQL SELECT statement for querying a graph database.
For instance, to find all email addresses of John Doe, the following 
query in backticks would be suitable:
```
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?email
WHERE {{
    ?person foaf:name "John Doe" .
    ?person foaf:mbox ?email .
}}
```
Instructions:
Use only the node types and properties provided in the schema.
Do not use any node types and properties that are not explicitly provided.
Include all necessary prefixes.

Examples:

Schema:
{schema}
Note: Be as concise as possible.
Do not include any explanations or apologies in your responses.
Do not respond to any questions that ask for anything else than 
for you to construct a SPARQL query.
Do not include any text except the SPARQL query generated.

The question is:
{prompt}schemapromptinput_variablestemplatec                    | j                         } | j                  d      }t        |      dk(  r|d   } | j                  d      r| dd } | S | j                  d      r| j	                  d      r| d	d
 } | S )zExtract SPARQL code from a text.

    Args:
        query: Text to extract SPARQL code from.

    Returns:
        SPARQL code extracted from the text.
    z```      sparql   Nz<sparql>z	</sparql>   i)stripsplitlen
startswithendswith)query	querytokss     p/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_community/chains/graph_qa/neptune_sparql.pyextract_sparqlr&   :   s}     KKMEE"I
9~!H%!"IE L 
		*	%%..*EaL    z0.3.15z1.0z,langchain_aws.create_neptune_sparql_qa_chain)sinceremovalalternative_importc                  ,    e Zd ZU dZ ed      Z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 fdZed d       Zed d       Zeeedd	 	 	 	 	 	 	 	 	 	 	 d!d       Z	 d"	 	 	 	 	 d#dZ xZS )$NeptuneSparqlQAChaina  Chain for question-answering against a Neptune graph
    by generating SPARQL 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.

    Example:
        .. code-block:: python

        chain = NeptuneSparqlQAChain.from_llm(
            llm=llm,
            graph=graph
        )
        response = chain.invoke(query)
    T)excluder   graphr	   sparql_generation_chainqa_chainr#   str	input_keyresult
output_key
   inttop_kFboolreturn_intermediate_stepsreturn_directNOptional[str]extra_instructions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%   rA   zNeptuneSparqlQAChain.__init__   s9    "6"((4W
 
 5r'   c                    | j                   gS N)r2   )rC   s    r%   
input_keyszNeptuneSparqlQAChain.input_keys   s    r'   c                     | j                   g}|S rG   )r4   )rC   _output_keyss     r%   output_keysz NeptuneSparqlQAChain.output_keys   s    (r'   )	qa_promptsparql_promptexamplesc                   t        ||      }t        }|r$|j                  dd|z         }t        ddg|      }t        ||      } | d|||d|S )	zInitialize from LLM.)llmr   z	Examples:z
Examples: r   r   r   )r0   r/   rN   r?   )r	   SPARQL_GENERATION_TEMPLATEreplacer   )	clsrP   rL   rM   rN   rD   r0   template_to_user/   s	            r%   from_llmzNeptuneSparqlQAChain.from_llm   s|     I64-55\H4O +!)8 4M #+s="I 
$;
 	
 	
r'   c                @   |xs t        j                         }|j                         }|| j                     }g }| j                  j                  || j                  j                  d|      }t        |      }|j                  dd| j                         |j                  |dd| j                         |j                  d|i       | j                  j                  |      }| j                  r|}	n|j                  d	d| j                         |j                  t        |      dd| j                         |j                  d
|i       | j                  ||d|      }
|
| j                  j                      }	| j                   |	i}| j"                  r	||t$        <   |S )zt
        Generate SPARQL query, use it to retrieve a response from the gdb and answer
        the question.
        )r   r   )	callbackszGenerated SPARQL:
)endverbosegreen)colorrY   rZ   r#   zFull Context:context)r   r]   )r   get_noop_manager	get_childr2   r/   runr.   
get_schemar&   on_textrZ   appendr#   r:   r1   r0   r4   r9   INTERMEDIATE_STEPS_KEY)rC   inputsrun_manager_run_managerrW   r   r   generated_sparqlr]   final_resultr3   chain_results               r%   _callzNeptuneSparqlQAChain._call   s    #S&@&Q&Q&S **,	'#%77;;)>)>?9 < 

 **:;0dDLLQGt|| 	 	
 	!!7,<"=>**""#34"L  dDLL Q  GGt|| !  %%y'&:;]]!g6# # F "$--":":;L(,'F))3EL/0r'   )rD   r   returnNone)rl   z	List[str])rP   r   rL   r   rM   r   rN   r;   rD   r   rl   r,   rG   )re   zDict[str, Any]rf   z$Optional[CallbackManagerForChainRun]rl   zDict[str, str])__name__
__module____qualname____doc__r   r.   __annotations__r2   r4   r7   r9   r:   r<   r=   rA   propertyrH   rK   classmethodr   SPARQL_GENERATION_PROMPTrU   rk   __classcell__)rE   s   @r%   r,   r,   O   s(   0 #40E?0%%IsJE3O&+t+VM4M(,,L%*d*        
 )9,D"&

 &	

 *
  
 
 

 
> =A33 :3 
	3r'   r,   N)r#   r1   rl   r1   )!rq   
__future__r   typingr   r   r   r   langchain_classic.chains.baser   langchain_classic.chains.llmr	   langchain_core._api.deprecationr
    langchain_core.callbacks.managerr   langchain_core.language_modelsr   langchain_core.prompts.baser   langchain_core.prompts.promptr   pydanticr   +langchain_community.chains.graph_qa.promptsr   langchain_community.graphsr   rd   rQ   ru   r&   r,   r?   r'   r%   <module>r      s    # , , / 1 6 G < : 8  H 6-  < *x(3M 
* 
E
^5 ^
^r'   