[docs]deftrim_query(query:str)->str:"""Trim the query to only include Cypher keywords."""keywords=("CALL","CREATE","DELETE","DETACH","LIMIT","MATCH","MERGE","OPTIONAL","ORDER","REMOVE","RETURN","SET","SKIP","UNWIND","WITH","WHERE","//",)lines=query.split("\n")new_query=""forlineinlines:ifline.strip().upper().startswith(keywords):new_query+=line+"\n"returnnew_query
[docs]defextract_cypher(text:str)->str:"""Extract Cypher code from text using Regex."""# The pattern to find Cypher code enclosed in triple backtickspattern=r"```(.*?)```"# Find all matches in the input textmatches=re.findall(pattern,text,re.DOTALL)returnmatches[0]ifmatcheselsetext
[docs]defuse_simple_prompt(llm:BaseLanguageModel)->bool:"""Decides whether to use the simple prompt"""ifllm._llm_typeand"anthropic"inllm._llm_type:# type: ignorereturnTrue# Bedrock anthropicifhasattr(llm,"model_id")and"anthropic"inllm.model_id:# type: ignorereturnTruereturnFalse
[docs]defget_prompt(llm:BaseLanguageModel)->BasePromptTemplate:"""Selects the final prompt"""ifuse_simple_prompt(llm):returnNEPTUNE_OPENCYPHER_GENERATION_SIMPLE_PROMPTelse:returnNEPTUNE_OPENCYPHER_GENERATION_PROMPT
[docs]defcreate_neptune_opencypher_qa_chain(llm:BaseLanguageModel,graph:BaseNeptuneGraph,qa_prompt:BasePromptTemplate=CYPHER_QA_PROMPT,cypher_prompt:Optional[BasePromptTemplate]=None,return_intermediate_steps:bool=False,return_direct:bool=False,extra_instructions:Optional[str]=None,allow_dangerous_requests:bool=False,)->Runnable:"""Chain for question-answering against a Neptune graph by generating openCypher 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_opencypher_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_cypher_prompt=cypher_promptorget_prompt(llm)cypher_generation_chain=_cypher_prompt|llmdefnormalize_input(raw_input:Union[str,dict])->dict:ifisinstance(raw_input,str):return{"query":raw_input}returnraw_inputdefexecute_graph_query(cypher_query:str)->dict:returngraph.query(cypher_query)defget_cypher_inputs(inputs:dict)->dict:return{"question":inputs["query"],"schema":graph.get_schema,"extra_instructions":extra_instructionsor"",}defget_qa_inputs(inputs:dict)->dict:return{"question":inputs["query"],"context":inputs["context"],}defformat_response(inputs:dict)->dict:intermediate_steps=[{"query":inputs["cypher"]}]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(cypher_generation_inputs=get_cypher_inputs)|{"query":lambdax:x["query"],"cypher":(lambdax:x["cypher_generation_inputs"])|cypher_generation_chain|(lambdax:extract_cypher(x.content))|trim_query,}|RunnablePassthrough.assign(context=lambdax:execute_graph_query(x["cypher"]))|RunnablePassthrough.assign(qa_result=(lambdax:get_qa_inputs(x))|qa_chain)|format_response)returnchain_result