langchain GraphCypherQAChain无法生成正确的Cypher命令

xwmevbvl  于 4个月前  发布在  其他
关注(0)|答案(1)|浏览(69)

检查其他资源

  • 为这个问题添加了一个非常描述性的标题。
  • 使用集成搜索在LangChain文档中搜索。
  • 使用GitHub搜索找到一个类似的问题,但没有找到。
  • 我确信这是LangChain中的一个bug,而不是我的代码。
  • 通过更新到LangChain的最新稳定版本(或特定集成包)无法解决此错误。

示例代码

from langchain_community.graphs import Neo4jGraph
from langchain.chains import GraphCypherQAChain
from langchain_openai import ChatOpenAI

uri = "bolt://localhost:7687"
username = "xxxx"
password = "xxxxx"

graph = Neo4jGraph(url=uri, username=username, password=password)

llm = ChatOpenAI(model="gpt-4-0125-preview",temperature=0)

chain = GraphCypherQAChain.from_llm(graph=graph, llm=llm, verbose=True, validate_cypher=True)

错误信息和堆栈跟踪(如果适用)

进入新的GraphCypherQAChain链...
生成Cypher:
MATCH (t:Tools {name: "test.py"})-[:has MD5 hash]->(h:Hash) RETURN h.name
Traceback (most recent call last):
File "\lib\site-packages\langchain_community\graphs\neo4j_graph.py", line 391, in query
data = session.run(Query(text=query, timeout=self.timeout), params)
File "\lib\site-packages\neo4j_sync\work\session.py", line 313, in run
self._auto_result._run(
File "\lib\site-packages\neo4j_sync\work\result.py", line 181, in _run
self._attach()
File "\lib\site-packages\neo4j_sync\io_common.py", line 178, in inner
func(args, **kwargs)
File "\lib\site-packages\neo4j_sync\io_bolt.py", line 850, in fetch_message
res = self._process_message(tag, fields)
File "\lib\site-packages\neo4j_sync\io_common.py", line 245, in on_failure
raise Neo4jError.hydrate(**metadata)
neo4j.exceptions.CypherSyntaxError: {code: Neo.ClientError.Statement.SyntaxError} {message: Invalid input 'MD5': expected
"
"
"WHERE"
"]"
"{"
a parameter (line 1, column 50 (offset: 49))
"MATCH (t:Tools {name: "test.py"})-[:has MD5 hash]->(h:Hash) RETURN h.name"
^}
在处理上述异常时,另一个异常发生:
Traceback (most recent call last):
File "\graph_RAG.py", line 29, in
response = chain.invoke({"query": "What is the MD5 of test.py?"})
File "lib\site-packages\langchain\chains\base.py", line 166, in invoke
raise e
File "\lib\site-packages\langchain\chains\base.py", line 156, in invoke
self._call(inputs, run_manager=run_manager)
File "\lib\site-packages\langchain_community\chains\graph_qa\cypher.py, line 274, in _call
context = self.graph.query(generated_cypher)[: self.top_k]
File "\lib\site-packages\langchain_community\graphs\neo4j_graph.py", line 397, in query
raise ValueError(f"Generated Cypher Statement is not valid
{e}")
ValueError: Generated Cypher Statement is not valid
{code: Neo.ClientError.Statement.SyntaxError} {message: Invalid input 'MD5': expected
"*"
"WHERE"
"]"
"{"
a parameter (line 1, column 50 (offset: 49))
"MATCH (t:Tools {name: "test.py"})-[:has MD5 hash]->(h:Hash) RETURN h.name"
^}

pxy2qtax

pxy2qtax1#

你描述的案例似乎是在你的模式中节点标签或关系类型包含空格时发生的边缘情况。可以使用from_llm类方法中的cypher_llm_kwargs参数来解决这个问题。
默认提示符在大多数情况下都能正常工作,但应保持简洁以获得最佳结果。尝试以下提示符来处理这个特定的边缘情况:

cypher_prompt_template = """Task:Generate Cypher statement to query a graph database.
Instructions:
Use only the provided relationship types and properties in the schema.
Do not use any other relationship types or properties that are not provided.
Schema:
{schema}
Note: Do not include any explanations or apologies in your responses.
Do not respond to any questions that might ask anything else than for you to construct a Cypher statement.
Do not include any text except the generated Cypher statement.

Examples:

Example 1:
Schema: {Person: {name, age}, City: {name}, LIVES IN: {since}}
Question: Find all persons living in New York.
Output: MATCH (p:`Person`)-[:`LIVES IN`]->(c:`City` {name: 'New York'}) RETURN p

Example 2:
Schema: {Employee: {name, role}, Department: {name}, WORKS_IN: {since}}
Question: Retrieve the names of all employees working in the Sales department.
Output: MATCH (e:`Employee`)-[:`WORKS_IN`]->(d:`Department` {name: 'Sales'}) RETURN e.name

Example 3:
Schema: {Movie: {title, releaseYear}, Director: {name}, DIRECTED: {since}}
Question: List all movies directed by Christopher Nolan.
Output: MATCH (d:`Director` {name: 'Christopher Nolan'})-[:`DIRECTED`]->(m:`Movie`) RETURN m.title

The question is:
{question}"""

cypher_prompt = PromptTemplate(template=cypher_prompt_template, input_variables=[])
chain = GraphCypherQAChain.from_llm(graph=graph, llm=llm, verbose=True,
                    validate_cypher=True, cypher_llm_kwargs={"prompt": cypher_prompt})

尝试这种方法,看看是否能解决你的问题。

相关问题