Source code for langchain_aws.chains.graph_qa.neptune_sparql
"""Question answering over an RDF or OWL graph using SPARQL."""from__future__importannotationsfromtypingimportAny,Optional,Unionfromlangchain_core.language_modelsimportBaseLanguageModelfromlangchain_core.prompts.baseimportBasePromptTemplatefromlangchain_core.prompts.promptimportPromptTemplatefromlangchain_core.runnablesimportRunnable,RunnablePassthroughfromlangchain_aws.graphsimportNeptuneRdfGraphfrom.promptsimport(NEPTUNE_SPARQL_GENERATION_PROMPT,NEPTUNE_SPARQL_GENERATION_TEMPLATE,SPARQL_QA_PROMPT,)INTERMEDIATE_STEPS_KEY="intermediate_steps"
[docs]defextract_sparql(query:str)->str:"""Extract SPARQL code from a text. Args: query: Text to extract SPARQL code from. Returns: SPARQL code extracted from the text. """query=query.strip()querytoks=query.split("```")iflen(querytoks)==3:query=querytoks[1]ifquery.startswith("sparql"):query=query[6:]elifquery.startswith("<sparql>")andquery.endswith("</sparql>"):query=query[8:-9]returnquery
[docs]defget_prompt(examples:str)->BasePromptTemplate:"""Selects the final prompt."""template_to_use=NEPTUNE_SPARQL_GENERATION_TEMPLATEifexamples:template_to_use=template_to_use.replace("Examples:","Examples: "+examples)returnPromptTemplate(input_variables=["schema","prompt"],template=template_to_use)returnNEPTUNE_SPARQL_GENERATION_PROMPT
[docs]defcreate_neptune_sparql_qa_chain(llm:BaseLanguageModel,graph:NeptuneRdfGraph,qa_prompt:BasePromptTemplate=SPARQL_QA_PROMPT,sparql_prompt:Optional[BasePromptTemplate]=None,return_intermediate_steps:bool=False,return_direct:bool=False,extra_instructions:Optional[str]=None,allow_dangerous_requests:bool=False,examples:Optional[str]=None,)->Runnable[Any,dict]:"""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 = create_neptune_sparql_qa_chain( llm=llm, graph=graph ) response = chain.invoke({"query": "your_query_here"}) """ifallow_dangerous_requestsisnotTrue:raiseValueError("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.")qa_chain=qa_prompt|llm_sparql_prompt=sparql_promptorget_prompt(examples)sparql_generation_chain=_sparql_prompt|llmdefnormalize_input(raw_input:Union[str,dict])->dict:ifisinstance(raw_input,str):return{"query":raw_input}returnraw_inputdefexecute_graph_query(sparql_query:str)->dict:returngraph.query(sparql_query)defget_sparql_inputs(inputs:dict)->dict:return{"prompt":inputs["query"],"schema":graph.get_schema,"extra_instructions":extra_instructionsor"",}defget_qa_inputs(inputs:dict)->dict:return{"prompt":inputs["query"],"context":inputs["context"],}defformat_response(inputs:dict)->dict:intermediate_steps=[{"query":inputs["sparql"]}]ifreturn_direct:final_response={"result":inputs["context"]}else:final_response={"result":inputs["qa_result"]}intermediate_steps.append({"context":inputs["context"]})ifreturn_intermediate_steps:final_response[INTERMEDIATE_STEPS_KEY]=intermediate_stepsreturnfinal_responsechain_result=(normalize_input|RunnablePassthrough.assign(sparql_generation_inputs=get_sparql_inputs)|{"query":lambdax:x["query"],"sparql":(lambdax:x["sparql_generation_inputs"])|sparql_generation_chain|(lambdax:extract_sparql(x.content)),}|RunnablePassthrough.assign(context=lambdax:execute_graph_query(x["sparql"]))|RunnablePassthrough.assign(qa_result=(lambdax:get_qa_inputs(x))|qa_chain)|format_response)returnchain_result