提升Graph-RAG查询生成的提示策略
在这篇文章中,我们将深入探讨如何优化在图数据库中生成查询的提示策略。我们的重点是如何在提示中获取与数据库特定信息相关的内容,以提高查询的准确性和效率。我们将以Neo4j数据库为示例,演示如何将自然语言问题转换为有效的Cypher查询。
引言
随着数据量的增加,图数据库成为处理复杂连接数据的一种强大工具。然而,生成正确的查询语句可能并不简单。良好的提示策略可以显著提高机器学习模型生成正确查询的能力。本文旨在提供一些实用的方法和代码示例,帮助你优化提示策略,从而更好地与图数据库进行交互。
主要内容
设置环境
首先,我们需要安装必要的包并设置环境变量:
%pip install --upgrade --quiet langchain langchain-community langchain-openai neo4j
注意:在使用更新的包时,可能需要重启内核。
我们默认使用OpenAI模型,但你可以根据需求选择其他模型提供商。
import getpass
import os
os.environ["OPENAI_API_KEY"] = getpass.getpass()
# 如果需要使用LangSmith,取消下面的注释。不一定需要。
# os.environ["LANGCHAIN_API_KEY"] = getpass.getpass()
# os.environ["LANGCHAIN_TRACING_V2"] = "true"
接下来,定义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
节点,可以使用GraphCypherQAChain
链的exclude_types
参数。
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
)
少样本示例
为模型提供少量的自然语言问题与其相应的Cypher查询示例,往往可以提高模型对于复杂查询的表现。
examples = [
{
"question": "How many artists are there?",
"query": "MATCH (a:Person)-[:ACTED_IN]->(:Movie) RETURN count(DISTINCT a)",
},
// 更多示例...
]
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
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"],
)
动态少样本示例
如果有足够的示例,可以动态选择与输入最相关的示例以减少模型的上下文窗口或避免长尾示例对模型的干扰。
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"],
)
print(prompt.format(question="how many artists are there?", schema="foo"))
常见问题和解决方案
-
访问限制问题:由于某些地区的网络限制,开发者在使用API时可能需要考虑API代理服务来提高访问稳定性。例如,可以通过设置
{AI_URL}
作为API端点来确保连接稳定。 -
查询结果不准确:确保你使用的示例足够相关,并且模式信息准确无误。
总结和进一步学习资源
本文介绍了如何通过优化提示策略来提高图数据库查询的生成效果。为进一步学习,建议阅读以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—