API 文档¶
组件¶
KGWriter¶
- class neo4j_graphrag.experimental.components.kg_writer.KGWriter[source]¶
用于将知识图谱写入数据存储的抽象类。
- abstract run(graph, lexical_graph_config=LexicalGraphConfig(id_prefix='', document_node_label='Document', chunk_node_label='Chunk', chunk_to_document_relationship_type='FROM_DOCUMENT', next_chunk_relationship_type='NEXT_CHUNK', node_to_chunk_relationship_type='FROM_CHUNK', chunk_index_property='index', chunk_text_property='text', chunk_embedding_property='embedding'))[source]¶
将图写入数据存储。
- 参数:
graph (Neo4jGraph) – 要写入数据存储的知识图谱。
lexical_graph_config (LexicalGraphConfig) – 词汇图中的节点标签和关系类型。
- 返回类型:
Neo4jWriter¶
- class neo4j_graphrag.experimental.components.kg_writer.Neo4jWriter(driver, neo4j_database=None, batch_size=1000)[source]¶
将知识图谱写入 Neo4j 数据库。
- 参数:
示例
from neo4j import GraphDatabase from neo4j_graphrag.experimental.components.kg_writer import Neo4jWriter from neo4j_graphrag.experimental.pipeline import Pipeline URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") DATABASE = "neo4j" driver = GraphDatabase.driver(URI, auth=AUTH, database=DATABASE) writer = Neo4jWriter(driver=driver, neo4j_database=DATABASE) pipeline = Pipeline() pipeline.add_component(writer, "writer")
- run(graph, lexical_graph_config=LexicalGraphConfig(id_prefix='', document_node_label='Document', chunk_node_label='Chunk', chunk_to_document_relationship_type='FROM_DOCUMENT', next_chunk_relationship_type='NEXT_CHUNK', node_to_chunk_relationship_type='FROM_CHUNK', chunk_index_property='index', chunk_text_property='text', chunk_embedding_property='embedding'))[source]¶
将知识图谱更新插入到 Neo4j 数据库中。
- 参数:
graph (Neo4jGraph) – 要更新插入到数据库中的知识图谱。
lexical_graph_config (LexicalGraphConfig)
- 返回类型:
TextSplitter¶
FixedSizeSplitter¶
- class neo4j_graphrag.experimental.components.text_splitters.fixed_size_splitter.FixedSizeSplitter(chunk_size=4000, chunk_overlap=200)[source]¶
文本分割器,它将输入文本分割成固定大小的块,并可以选择重叠。
示例
from neo4j_graphrag.experimental.components.text_splitters.fixed_size_splitter import FixedSizeSplitter from neo4j_graphrag.experimental.pipeline import Pipeline pipeline = Pipeline() text_splitter = FixedSizeSplitter(chunk_size=4000, chunk_overlap=200) pipeline.add_component(text_splitter, "text_splitter")
LangChainTextSplitterAdapter¶
LlamaIndexTextSplitterAdapter¶
TextChunkEmbedder¶
- class neo4j_graphrag.experimental.components.embedder.TextChunkEmbedder(embedder)[source]¶
用于从文本块创建嵌入的组件。
- 参数:
embedder (Embedder) – 用于创建嵌入的嵌入器。
示例
from neo4j_graphrag.experimental.components.embedder import TextChunkEmbedder from neo4j_graphrag.embeddings.openai import OpenAIEmbeddings from neo4j_graphrag.experimental.pipeline import Pipeline embedder = OpenAIEmbeddings(model="text-embedding-3-large") chunk_embedder = TextChunkEmbedder(embedder) pipeline = Pipeline() pipeline.add_component(chunk_embedder, "chunk_embedder")
- run(text_chunks)[source]¶
嵌入文本块列表。
- 参数:
text_chunks (TextChunks) – 要嵌入的文本块。
- 返回值:
每个输入文本块都添加了一个嵌入。
- 返回类型:
LexicalGraphBuilder¶
Neo4jChunkReader¶
- class neo4j_graphrag.experimental.components.neo4j_reader.Neo4jChunkReader(driver, fetch_embeddings=False)[source]¶
- 参数:
driver (neo4j.Driver)
fetch_embeddings (bool)
- run(lexical_graph_config=LexicalGraphConfig(id_prefix='', document_node_label='Document', chunk_node_label='Chunk', chunk_to_document_relationship_type='FROM_DOCUMENT', next_chunk_relationship_type='NEXT_CHUNK', node_to_chunk_relationship_type='FROM_CHUNK', chunk_index_property='index', chunk_text_property='text', chunk_embedding_property='embedding'))[source]¶
- 参数:
lexical_graph_config (LexicalGraphConfig)
- 返回类型:
SchemaBuilder¶
- class neo4j_graphrag.experimental.components.schema.SchemaBuilder[source]¶
一个用于从给定实体、关系及其在潜在模式中定义的相互关系构建 SchemaConfig 对象的构建器类。
示例
from neo4j_graphrag.experimental.components.schema import ( SchemaBuilder, SchemaEntity, SchemaProperty, SchemaRelation, ) from neo4j_graphrag.experimental.pipeline import Pipeline entities = [ SchemaEntity( label="PERSON", description="An individual human being.", properties=[ SchemaProperty( name="name", type="STRING", description="The name of the person" ) ], ), SchemaEntity( label="ORGANIZATION", description="A structured group of people with a common purpose.", properties=[ SchemaProperty( name="name", type="STRING", description="The name of the organization" ) ], ), ] relations = [ SchemaRelation( label="EMPLOYED_BY", description="Indicates employment relationship." ), ] potential_schema = [ ("PERSON", "EMPLOYED_BY", "ORGANIZATION"), ] pipe = Pipeline() schema_builder = SchemaBuilder() pipe.add_component(schema_builder, "schema_builder") pipe_inputs = { "schema": { "entities": entities, "relations": relations, "potential_schema": potential_schema, }, ... } pipe.run(pipe_inputs)
- run(entities, relations=None, potential_schema=None)[source]¶
异步构建并返回一个 SchemaConfig 对象。
- 参数:
entities (List[SchemaEntity]) – 实体对象列表。
relations (List[SchemaRelation]) – 关系对象列表。
potential_schema (Dict[str, List[str]]) – 将实体名称映射到关系名称列表的字典。
- 返回值:
一个配置好的模式对象,异步构建。
- 返回类型:
EntityRelationExtractor¶
LLMEntityRelationExtractor¶
SinglePropertyExactMatchResolver¶
- class neo4j_graphrag.experimental.components.resolver.SinglePropertyExactMatchResolver(driver, filter_query=None, resolve_property='name', neo4j_database=None)[source]¶
解析具有相同标签和完全相同属性(默认值为“name”)的实体。
- 参数:
示例
from neo4j import GraphDatabase from neo4j_graphrag.experimental.components.resolver import SinglePropertyExactMatchResolver URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") DATABASE = "neo4j" driver = GraphDatabase.driver(URI, auth=AUTH, database=DATABASE) resolver = SinglePropertyExactMatchResolver(driver=driver, neo4j_database=DATABASE) await resolver.run() # no expected parameters
Pipelines¶
Pipeline¶
- class neo4j_graphrag.experimental.pipeline.Pipeline(store=None)[source]¶
这是主管道,其中定义了组件及其执行顺序。
- 参数:
store (Optional[ResultStore])
- add_component(component, name)[source]¶
添加一个新组件。组件通过其名称唯一标识。如果“name”已存在于管道中,则会引发 ValueError。
- 参数:
component (Component)
name (str)
- 返回类型:
None
SimpleKGPipeline¶
Retrievers¶
RetrieverInterface¶
- 类 neo4j_graphrag.retrievers.base.Retriever(driver, neo4j_database=None)[源代码]¶
Neo4j检索器的抽象类
- 参数:
driver (neo4j.Driver)
**neo4j_database** (可选[str])
- VERIFY_NEO4J_VERSION = True¶
- search(*args, **kwargs)[源代码]¶
搜索方法。调用返回 neo4j.Record 列表的 get_search_results 方法,并使用 get_result_formatter 返回的函数格式化它们以返回 RetrieverResult。
- 参数:
- 返回类型:
- 抽象 get_search_results(*args, **kwargs)[源代码]¶
此方法必须在每个子类中实现。它将接收通过 search 方法提供给公共接口的相同参数,并在验证后。它返回一个 RawSearchResult 对象,该对象包含 neo4j.Record 对象列表和一个可选的 metadata 字典,该字典可以包含检索器级别的信息。
请注意,即使此方法不打算从类外部调用,我们也将其公开,以便使开发人员更清楚地了解它应该在子类中实现。
- 返回值:
Neo4j 记录列表和可选的元数据字典
- 返回类型:
- 参数:
- get_result_formatter()[源代码]¶
返回用于将 neo4j.Record 转换为 RetrieverResultItem 的函数。
- 返回类型:
Callable[[Record], RetrieverResultItem]
VectorRetriever¶
- 类 neo4j_graphrag.retrievers.VectorRetriever(driver, index_name, embedder=None, return_properties=None, result_formatter=None, neo4j_database=None)[源代码]¶
提供使用向量搜索嵌入的检索方法。如果提供了嵌入器,则它需要具有所需的 Embedder 类型。
示例
import neo4j from neo4j_graphrag.retrievers import VectorRetriever driver = neo4j.GraphDatabase.driver(URI, auth=AUTH) retriever = VectorRetriever(driver, "vector-index-name", custom_embedder) retriever.search(query_text="Find me a book about Fremen", top_k=5)
或者如果查询文本的向量嵌入可用
retriever.search(query_vector=..., top_k=5)
- 参数:
**driver** (neo4j.Driver) – Neo4j Python 驱动程序。
**index_name** (str) – 向量索引名称。
**embedder** (可选[Embedder]) – 用于嵌入查询文本的 Embedder 对象。
**result_formatter** (可选[Callable[[neo4j.Record], RetrieverResultItem]]) –
提供的自定义函数,用于将 neo4j.Record 转换为 RetrieverResultItem。
在 neo4j.Record 中提供了两个变量
node:表示从向量索引搜索中检索到的节点。
score:表示相似度得分。
**neo4j_database** (可选[str]) – Neo4j 数据库的名称。如果未提供,则默认为数据库中的“neo4j”(请参阅文档参考)。
- 引发:
RetrieverInitializationError – 如果输入参数验证失败。
- search(query_vector=None, query_text=None, top_k=5, filters=None)¶
获取提供的 query_vector 或 query_text 的前 top_k 个最近邻嵌入。有关更多详细信息,请参阅以下文档
要通过文本查询,必须在实例化类时提供嵌入器。如果传递了 query_vector,则不需要嵌入器。
- 参数:
- 引发:
SearchValidationError – 如果输入参数验证失败。
EmbeddingRequiredError – 如果未提供嵌入器。
- 返回值:
搜索查询的结果,作为 neo4j.Record 列表和可选的元数据字典
- 返回类型:
VectorCypherRetriever¶
- 类 neo4j_graphrag.retrievers.VectorCypherRetriever(driver, index_name, retrieval_query, embedder=None, result_formatter=None, neo4j_database=None)[源代码]¶
提供使用向量相似性并通过 Cypher 查询进行增强的检索方法。此检索器建立在 VectorRetriever 的基础上。如果提供了嵌入器,则它需要具有所需的 Embedder 类型。
注意:node 是来自基本查询的变量,可以在 retrieval_query 中使用,如下面的示例所示。
retrieval_query 是可以在检索 node 后允许进行图遍历的其他 Cypher。
示例
import neo4j from neo4j_graphrag.retrievers import VectorCypherRetriever driver = neo4j.GraphDatabase.driver(URI, auth=AUTH) retrieval_query = "MATCH (node)-[:AUTHORED_BY]->(author:Author)" "RETURN author.name" retriever = VectorCypherRetriever( driver, "vector-index-name", retrieval_query, custom_embedder ) retriever.search(query_text="Find me a book about Fremen", top_k=5)
- 参数:
**driver** (neo4j.Driver) – Neo4j Python 驱动程序。
**index_name** (str) – 向量索引名称。
**retrieval_query** (str) – 附加的 Cypher 查询。
**embedder** (可选[Embedder]) – 用于嵌入查询文本的 Embedder 对象。
**result_formatter** (可选[Callable[[neo4j.Record], RetrieverResultItem]]) – 提供的自定义函数,用于将 neo4j.Record 转换为 RetrieverResultItem。
**neo4j_database** (可选[str]) –
Neo4j 数据库的名称。如果未提供,则默认为数据库中的“neo4j”(请参阅文档参考)。
在 用户指南 中了解更多信息。
- search(query_vector=None, query_text=None, top_k=5, query_params=None, filters=None)¶
获取提供的 query_vector 或 query_text 的前 top_k 个最近邻嵌入。有关更多详细信息,请参阅以下文档
要通过文本查询,必须在实例化类时提供嵌入器。如果传递了 query_vector,则不需要嵌入器。
- 参数:
- 引发:
SearchValidationError – 如果输入参数验证失败。
EmbeddingRequiredError – 如果未提供嵌入器。
- 返回值:
搜索查询的结果,作为 neo4j.Record 列表和可选的元数据字典
- 返回类型:
混合检索器¶
- class neo4j_graphrag.retrievers.HybridRetriever(driver, vector_index_name, fulltext_index_name, embedder=None, return_properties=None, result_formatter=None, neo4j_database=None)[source]¶
提供使用向量嵌入搜索和全文搜索相结合的检索方法。如果提供了嵌入器,则它需要具有所需的 Embedder 类型。
示例
import neo4j from neo4j_graphrag.retrievers import HybridRetriever driver = neo4j.GraphDatabase.driver(URI, auth=AUTH) retriever = HybridRetriever( driver, "vector-index-name", "fulltext-index-name", custom_embedder ) retriever.search(query_text="Find me a book about Fremen", top_k=5)
- 参数:
**driver** (neo4j.Driver) – Neo4j Python 驱动程序。
vector_index_name (str) – 向量索引名称。
fulltext_index_name (str) – 全文索引名称。
**embedder** (可选[Embedder]) – 用于嵌入查询文本的 Embedder 对象。
**neo4j_database** (可选[str]) –
Neo4j 数据库的名称。如果未提供,则默认为数据库中的“neo4j”(请参阅文档参考)。
**result_formatter** (可选[Callable[[neo4j.Record], RetrieverResultItem]]) –
提供的自定义函数,用于将 neo4j.Record 转换为 RetrieverResultItem。
在 neo4j.Record 中提供了两个变量
node:表示从向量索引搜索中检索到的节点。
score:表示相似度得分。
- search(query_text, query_vector=None, top_k=5)¶
获取提供的 query_vector 或 query_text 的前 top_k 个最近邻嵌入。可以同时提供 query_vector 和 query_text。如果提供了 query_vector,则在向量搜索中将优先于嵌入的 query_text。
有关更多详细信息,请参阅以下文档
要按文本查询,在实例化类时必须提供嵌入器。
- 参数:
- 引发:
SearchValidationError – 如果输入参数验证失败。
EmbeddingRequiredError – 如果未提供嵌入器。
- 返回值:
搜索查询的结果,作为 neo4j.Record 列表和可选的元数据字典
- 返回类型:
混合 Cypher 检索器¶
- class neo4j_graphrag.retrievers.HybridCypherRetriever(driver, vector_index_name, fulltext_index_name, retrieval_query, embedder=None, result_formatter=None, neo4j_database=None)[source]¶
提供使用向量嵌入搜索和全文搜索相结合的检索方法,并通过 Cypher 查询进行增强。此检索器建立在 HybridRetriever 的基础上。如果提供了嵌入器,则它需要具有所需的 Embedder 类型。
注意:node 是来自基本查询的变量,可以在 retrieval_query 中使用,如下面的示例所示。
示例
import neo4j from neo4j_graphrag.retrievers import HybridCypherRetriever driver = neo4j.GraphDatabase.driver(URI, auth=AUTH) retrieval_query = "MATCH (node)-[:AUTHORED_BY]->(author:Author)" "RETURN author.name" retriever = HybridCypherRetriever( driver, "vector-index-name", "fulltext-index-name", retrieval_query, custom_embedder ) retriever.search(query_text="Find me a book about Fremen", top_k=5)
要按文本查询,在实例化类时必须提供嵌入器。
- 参数:
**driver** (neo4j.Driver) – Neo4j Python 驱动程序。
vector_index_name (str) – 向量索引名称。
fulltext_index_name (str) – 全文索引名称。
**retrieval_query** (str) – 附加的 Cypher 查询。
**embedder** (可选[Embedder]) – 用于嵌入查询文本的 Embedder 对象。
**result_formatter** (可选[Callable[[neo4j.Record], RetrieverResultItem]]) – 提供的自定义函数,用于将 neo4j.Record 转换为 RetrieverResultItem。
**neo4j_database** (可选[str]) –
Neo4j 数据库的名称。如果未提供,则默认为数据库中的“neo4j”(请参阅文档参考)。
- 引发:
RetrieverInitializationError – 如果输入参数验证失败。
- search(query_text, query_vector=None, top_k=5, query_params=None)¶
获取提供的 query_vector 或 query_text 的前 top_k 个最近邻嵌入。可以同时提供 query_vector 和 query_text。如果提供了 query_vector,则在向量搜索中将优先于嵌入的 query_text。
有关更多详细信息,请参阅以下文档
- 参数:
- 引发:
SearchValidationError – 如果输入参数验证失败。
EmbeddingRequiredError – 如果未提供嵌入器。
- 返回值:
搜索查询的结果,作为 neo4j.Record 列表和可选的元数据字典
- 返回类型:
文本到 Cypher 检索器¶
- class neo4j_graphrag.retrievers.Text2CypherRetriever(driver, llm, neo4j_schema=None, examples=None, result_formatter=None, custom_prompt=None)[source]¶
允许使用自然语言从 Neo4j 数据库检索记录。使用 LLM 将用户的自然语言查询转换为 Cypher 查询,然后使用生成的 Cypher 查询从 Neo4j 数据库检索记录。
- 参数:
**driver** (neo4j.Driver) – Neo4j Python 驱动程序。
llm (neo4j_graphrag.generation.llm.LLMInterface) – 用于生成 Cypher 查询的 LLM 对象。
neo4j_schema (可选[str]) – 用于生成 Cypher 查询的 Neo4j 模式。
custom_prompt (可选[str]) – 可选的自定义提示,用于代替自动生成的提示。如果提供了,则不包含 neo4j_schema 或 examples 参数。
result_formatter (可选[Callable[[neo4j.Record], RetrieverResultItem]])
- 引发:
RetrieverInitializationError – 如果输入参数验证失败。
- search(query_text, prompt_params=None)¶
- 使用 LLM 将 query_text 转换为 Cypher 查询。
使用生成的 Cypher 查询从 Neo4j 数据库检索记录。
- 参数:
- 引发:
SearchValidationError – 如果输入参数验证失败。
Text2CypherRetrievalError – 如果 LLM 无法生成正确的 Cypher 查询。
- 返回值:
搜索查询的结果,作为 neo4j.Record 列表和可选的元数据字典
- 返回类型:
外部检索器¶
本节包含与 Neo4j 外部数据库集成的检索器。
WeaviateNeo4j 检索器¶
PineconeNeo4j 检索器¶
QdrantNeo4j 检索器¶
嵌入器¶
SentenceTransformerEmbeddings¶
OpenAIEmbeddings¶
AzureOpenAIEmbeddings¶
VertexAIEmbeddings¶
- class neo4j_graphrag.embeddings.vertexai.VertexAIEmbeddings(model='text-embedding-004')[source]¶
Vertex AI 嵌入类。此类使用 Vertex AI Python 客户端为文本数据生成向量嵌入。
- 参数:
model (str) – 要使用的 Vertex AI 文本嵌入模型的名称。默认为“text-embedding-004”。
- embed_query(text, task_type='RETRIEVAL_QUERY', **kwargs)[source]¶
使用 Vertex AI 文本嵌入模型为给定查询生成嵌入。
- 参数:
text (str) – 要生成嵌入的文本。
task_type (str) – 文本嵌入任务的类型。默认为“RETRIEVAL_QUERY”。有关完整列表,请参见 https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/text-embeddings-api#tasktype。
**kwargs (Any) – 要传递给 Vertex AI 客户端的 get_embeddings 方法的其他关键字参数。
- 返回类型:
MistralAIEmbeddings¶
CohereEmbeddings¶
生成¶
LLM¶
LLMInterface¶
- class neo4j_graphrag.llm.LLMInterface(model_name, model_params=None, **kwargs)[source]¶
大型语言模型的接口。
- 参数:
- abstract invoke(input)[source]¶
将文本输入发送到 LLM 并检索响应。
- 参数:
input (str) – 发送到 LLM 的文本
- 返回值:
LLM 的响应。
- 返回类型:
- 引发:
LLMGenerationError – 如果出现任何错误。
- 抽象 异步 ainvoke(input)[source]¶
异步地将文本输入发送到LLM并检索响应。
- 参数:
input (str) – 发送到 LLM 的文本
- 返回值:
LLM 的响应。
- 返回类型:
- 引发:
LLMGenerationError – 如果出现任何错误。
OpenAILLM¶
AzureOpenAILLM¶
VertexAILLM¶
- 类 neo4j_graphrag.llm.vertexai_llm.VertexAILLM(model_name='gemini-1.5-flash-001', model_params=None, **kwargs)[source]¶
Vertex AI 上大型语言模型的接口
- 参数:
- 引发:
LLMGenerationError – 如果模型生成响应时出错。
示例
from neo4j_graphrag.llm import VertexAILLM from vertexai.generative_models import GenerationConfig generation_config = GenerationConfig(temperature=0.0) llm = VertexAILLM( model_name="gemini-1.5-flash-001", generation_config=generation_config ) llm.invoke("Who is the mother of Paul Atreides?")
AnthropicLLM¶
- 类 neo4j_graphrag.llm.anthropic_llm.AnthropicLLM(model_name, model_params=None, **kwargs)[source]¶
Anthropic 上大型语言模型的接口
- 参数:
- 引发:
LLMGenerationError – 如果模型生成响应时出错。
示例
from neo4j_graphrag.llm import AnthropicLLM llm = AnthropicLLM( model_name="claude-3-opus-20240229", model_params={"max_tokens": 1000}, api_key="sk...", # can also be read from env vars ) llm.invoke("Who is the mother of Paul Atreides?")
CohereLLM¶
- 类 neo4j_graphrag.llm.cohere_llm.CohereLLM(model_name='', model_params=None, **kwargs)[source]¶
Cohere 平台上大型语言模型的接口
- 参数:
- 引发:
LLMGenerationError – 如果模型生成响应时出错。
示例
from neo4j_graphrag.llm import CohereLLM llm = CohereLLM(api_key="...") llm.invoke("Say something")
MistralAILLM¶
- 类 neo4j_graphrag.llm.mistralai_llm.MistralAILLM(model_name, model_params=None, **kwargs)[source]¶
-
- invoke(input)[source]¶
将文本输入发送到 Mistral 聊天完成模型并返回响应的内容。
- 参数:
input (str) – 发送到 LLM 的文本
- 返回值:
MistralAI 的响应。
- 返回类型:
- 引发:
LLMGenerationError – 如果出现任何错误。
- 异步 ainvoke(input)[source]¶
异步地将文本输入发送到 MistralAI 聊天完成模型并返回响应的内容。
- 参数:
input (str) – 发送到 LLM 的文本
- 返回值:
MistralAI 的响应。
- 返回类型:
- 引发:
LLMGenerationError – 如果出现任何错误。
PromptTemplate¶
- 类 neo4j_graphrag.generation.prompts.PromptTemplate(template=None, expected_inputs=None)[source]¶
此类用于生成参数化提示。它使用 Python 格式语法(花括号 {} 中的参数)和所需输入列表从字符串(模板)定义。在将指令发送到 LLM 之前,请调用 format 方法,该方法将用提供的值替换参数。如果缺少任何预期输入,则会引发 PromptMissingInputError。
- format(*args, **kwargs)[source]¶
此方法用于将参数替换为提供的值。必须提供参数: - 作为 kwargs - 如果使用与预期输入相同的顺序,则作为 args
示例
prompt_template = PromptTemplate( template='''Explain the following concept to {target_audience}: Concept: {concept} Answer: ''', expected_inputs=['target_audience', 'concept'] ) prompt = prompt_template.format('12 yo children', concept='graph database') print(prompt) # Result: # '''Explain the following concept to 12 yo children: # Concept: graph database # Answer: # '''
RagTemplate¶
- class neo4j_graphrag.generation.prompts.RagTemplate(template=None, expected_inputs=None)[source]¶
-
- DEFAULT_TEMPLATE: str = 'Answer the user question using the following context\n\nContext:\n{context}\n\nExamples:\n{examples}\n\nQuestion:\n{query_text}\n\nAnswer:\n'¶
- format(query_text, context, examples)[source]¶
此方法用于将参数替换为提供的值。必须提供参数: - 作为 kwargs - 如果使用与预期输入相同的顺序,则作为 args
示例
prompt_template = PromptTemplate( template='''Explain the following concept to {target_audience}: Concept: {concept} Answer: ''', expected_inputs=['target_audience', 'concept'] ) prompt = prompt_template.format('12 yo children', concept='graph database') print(prompt) # Result: # '''Explain the following concept to 12 yo children: # Concept: graph database # Answer: # '''
ERExtractionTemplate¶
- class neo4j_graphrag.generation.prompts.ERExtractionTemplate(template=None, expected_inputs=None)[source]¶
-
- DEFAULT_TEMPLATE: str = '\nYou are a top-tier algorithm designed for extracting\ninformation in structured formats to build a knowledge graph.\n\nExtract the entities (nodes) and specify their type from the following text.\nAlso extract the relationships between these nodes.\n\nReturn result as JSON using the following format:\n{{"nodes": [ {{"id": "0", "label": "Person", "properties": {{"name": "John"}} }}],\n"relationships": [{{"type": "KNOWS", "start_node_id": "0", "end_node_id": "1", "properties": {{"since": "2024-08-01"}} }}] }}\n\nUse only the following nodes and relationships (if provided):\n{schema}\n\nAssign a unique ID (string) to each node, and reuse it to define relationships.\nDo respect the source and target node types for relationship and\nthe relationship direction.\n\nDo not return any additional information other than the JSON in it.\n\nExamples:\n{examples}\n\nInput text:\n\n{text}\n'¶
- format(schema, examples, text='')[source]¶
此方法用于将参数替换为提供的值。必须提供参数: - 作为 kwargs - 如果使用与预期输入相同的顺序,则作为 args
示例
prompt_template = PromptTemplate( template='''Explain the following concept to {target_audience}: Concept: {concept} Answer: ''', expected_inputs=['target_audience', 'concept'] ) prompt = prompt_template.format('12 yo children', concept='graph database') print(prompt) # Result: # '''Explain the following concept to 12 yo children: # Concept: graph database # Answer: # '''
RAG¶
GraphRAG¶
- class neo4j_graphrag.generation.graphrag.GraphRAG(retriever, llm, prompt_template=<neo4j_graphrag.generation.prompts.RagTemplate object>)[source]¶
使用特定的检索器和 LLM 执行 GraphRAG 搜索。
示例
import neo4j from neo4j_graphrag.retrievers import VectorRetriever from neo4j_graphrag.llm.openai_llm import OpenAILLM from neo4j_graphrag.generation import GraphRAG driver = neo4j.GraphDatabase.driver(URI, auth=AUTH) retriever = VectorRetriever(driver, "vector-index-name", custom_embedder) llm = OpenAILLM() graph_rag = GraphRAG(retriever, llm) graph_rag.search(query_text="Find me a book about Fremen")
- 参数:
retriever (Retriever) – 用于查找相关上下文并传递给LLM的检索器。
llm (LLMInterface) – 用于生成答案的LLM。
prompt_template (RagTemplate) – 将使用上下文和用户问题进行格式化并传递给LLM的提示模板。
- 引发:
RagInitializationError – 如果输入参数验证失败。
数据库交互¶
- neo4j_graphrag.indexes.create_vector_index(driver, name, label, embedding_property, dimensions, similarity_fn, fail_if_exists=False, neo4j_database=None)[source]¶
此方法构造一个Cypher查询并执行它,以在Neo4j中创建新的向量索引。
请参阅Cypher手册关于创建向量索引。
确保提供的索引名称在数据库上下文中是唯一的。
示例
from neo4j import GraphDatabase from neo4j_graphrag.indexes import create_vector_index URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") INDEX_NAME = "vector-index-name" # Connect to Neo4j database driver = GraphDatabase.driver(URI, auth=AUTH) # Creating the index create_vector_index( driver, INDEX_NAME, label="Document", embedding_property="vectorProperty", dimensions=1536, similarity_fn="euclidean", fail_if_exists=False, )
- 参数:
driver (neo4j.Driver) – Neo4j Python驱动程序实例。
name (str) – 索引的唯一名称。
label (str) – 要索引的节点标签。
embedding_property (str) – 包含嵌入值的节点的属性键。
dimensions (int) – 向量嵌入维度
similarity_fn (str) – 向量相似度函数的不区分大小写的值:
euclidean
或cosine
。fail_if_exists (bool) – 如果为True,则如果索引已存在则引发错误。默认为False。
**neo4j_database** (可选[str]) –
Neo4j 数据库的名称。如果未提供,则默认为数据库中的“neo4j”(请参阅文档参考)。
- 引发:
ValueError – 如果输入参数验证失败。
neo4j.exceptions.ClientError – 如果向量索引创建失败。
- 返回类型:
None
- neo4j_graphrag.indexes.create_fulltext_index(driver, name, label, node_properties, fail_if_exists=False, neo4j_database=None)[source]¶
此方法构造一个Cypher查询并执行它,以在Neo4j中创建新的全文索引。
请参阅Cypher手册关于创建全文索引。
确保提供的索引名称在数据库上下文中是唯一的。
示例
from neo4j import GraphDatabase from neo4j_graphrag.indexes import create_fulltext_index URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") INDEX_NAME = "fulltext-index-name" # Connect to Neo4j database driver = GraphDatabase.driver(URI, auth=AUTH) # Creating the index create_fulltext_index( driver, INDEX_NAME, label="Document", node_properties=["vectorProperty"], fail_if_exists=False, )
- 参数:
- 引发:
ValueError – 如果输入参数验证失败。
neo4j.exceptions.ClientError – 如果全文索引创建失败。
- 返回类型:
None
- neo4j_graphrag.indexes.drop_index_if_exists(driver, name, neo4j_database=None)[source]¶
此方法构造一个Cypher查询并执行它,以删除Neo4j中的索引(如果索引存在)。请参阅Cypher手册关于删除向量索引。
示例
from neo4j import GraphDatabase from neo4j_graphrag.indexes import drop_index_if_exists URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") INDEX_NAME = "fulltext-index-name" # Connect to Neo4j database driver = GraphDatabase.driver(URI, auth=AUTH) # Dropping the index if it exists drop_index_if_exists( driver, INDEX_NAME, )
- neo4j_graphrag.indexes.upsert_vector(driver, node_id, embedding_property, vector, neo4j_database=None)[source]¶
此方法构造一个Cypher查询并执行它,以在特定节点上更新(插入或更新)向量属性。
示例
from neo4j import GraphDatabase from neo4j_graphrag.indexes import upsert_vector URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") # Connect to Neo4j database driver = GraphDatabase.driver(URI, auth=AUTH) # Upsert the vector data upsert_vector( driver, node_id="nodeId", embedding_property="vectorProperty", vector=..., )
- neo4j_graphrag.indexes.upsert_vector_on_relationship(driver, rel_id, embedding_property, vector, neo4j_database=None)[source]¶
此方法构造一个Cypher查询并执行它,以在特定关系上更新(插入或更新)向量属性。
示例
from neo4j import GraphDatabase from neo4j_graphrag.indexes import upsert_vector_on_relationship URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") # Connect to Neo4j database driver = GraphDatabase.driver(URI, auth=AUTH) # Upsert the vector data upsert_vector_on_relationship( driver, node_id="nodeId", embedding_property="vectorProperty", vector=..., )
- async neo4j_graphrag.indexes.async_upsert_vector(driver, node_id, embedding_property, vector, neo4j_database=None)[source]¶
此方法构造一个Cypher查询并异步执行它,以在特定节点上更新(插入或更新)向量属性。
示例
from neo4j import AsyncGraphDatabase from neo4j_graphrag.indexes import upsert_vector URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") # Connect to Neo4j database driver = AsyncGraphDatabase.driver(URI, auth=AUTH) # Upsert the vector data async_upsert_vector( driver, node_id="nodeId", embedding_property="vectorProperty", vector=..., )
- async neo4j_graphrag.indexes.async_upsert_vector_on_relationship(driver, rel_id, embedding_property, vector, neo4j_database=None)[source]¶
此方法构建一个 Cypher 查询并异步执行它,以对特定关系上的向量属性进行 upsert 操作(插入或更新)。
示例
from neo4j import AsyncGraphDatabase from neo4j_graphrag.indexes import upsert_vector_on_relationship URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") # Connect to Neo4j database driver = AsyncGraphDatabase.driver(URI, auth=AUTH) # Upsert the vector data async_upsert_vector_on_relationship( driver, node_id="nodeId", embedding_property="vectorProperty", vector=..., )