深入探索Llama Index中的知识图谱数据结构
在现代数据科学和人工智能领域,知识图谱(Knowledge Graph)已成为处理复杂信息的重要工具。知识图谱通过结构化的方式表示实体及其关系,使得信息的检索和理解变得更加高效。本文将深入探讨Llama Index中的KnowledgeGraphIndex
数据结构,帮助程序员全面理解其工作原理及实际应用。
前置知识
在开始之前,确保你具备以下基础知识:
- Python基础:熟悉Python编程。
- OpenAI API密钥:你需要一个OpenAI API密钥来使用
OpenAI
模型。 - Llama Index:使用
pip install llama-index
安装Llama Index库。
环境设置
首先,让我们通过安装所需的包并配置OpenAI API密钥来设置环境。
# 安装Llama Index
%pip install llama-index
# 设置OpenAI API密钥
import os
os.environ["OPENAI_API_KEY"] = "sk-..."
# 配置日志
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
KnowledgeGraphIndex概述
KnowledgeGraphIndex
是Llama Index中的一个核心数据结构,用于构建和查询知识图谱。它通过提取三元组(triplets)并利用这些三元组在查询时构建知识图谱。
参数说明
参数名 | 类型 | 描述 | 默认值 |
---|---|---|---|
kg_triplet_extract_template | BasePromptTemplate | 用于提取三元组的提示模板。 | None |
max_triplets_per_chunk | int | 每个块中提取的最大三元组数量。 | 10 |
storage_context | Optional[StorageContext] | 存储上下文。 | None |
graph_store | Optional[GraphStore] | 图存储。 | 必需 |
show_progress | bool | 是否显示tqdm进度条。 | False |
include_embeddings | bool | 是否在索引中包含嵌入。 | False |
max_object_length | int | 三元组中对象的最大长度。 | 128 |
kg_triplet_extract_fn | Optional[Callable] | 用于提取三元组的函数。 | None |
主要方法
ref_doc_info属性
ref_doc_info: Dict[str, RefDocInfo]
描述:检索已摄取文档及其节点和元数据的字典映射。
upsert_triplet方法
upsert_triplet(triplet: Tuple[str, str, str], include_embeddings: bool = False) -> None
描述:插入三元组并可选地插入嵌入。用于手动插入知识图谱三元组(形式为(subject, relationship, object))。
参数:
参数名 | 类型 | 描述 | 默认值 |
---|---|---|---|
triplet | tuple | 知识三元组 | 必需 |
include_embeddings | bool | 是否包含三元组的嵌入。 | False |
add_node方法
add_node(keywords: List[str], node: BaseNode) -> None
描述:添加节点。用于手动插入节点(按关键词索引)。
参数:
参数名 | 类型 | 描述 | 默认值 |
---|---|---|---|
keywords | List[str] | 索引节点的关键词 | 必需 |
node | Node | 要索引的节点 | 必需 |
upsert_triplet_and_node方法
upsert_triplet_and_node(triplet: Tuple[str, str, str], node: BaseNode, include_embeddings: bool = False) -> None
描述:插入知识图谱三元组和节点。调用upsert_triplet
和add_node
方法。行为是幂等的;如果节点已存在,则仅添加三元组。
参数:
参数名 | 类型 | 描述 | 默认值 |
---|---|---|---|
triplet | tuple | 知识三元组 | 必需 |
node | Node | 要索引的节点 | 必需 |
include_embeddings | bool | 是否包含三元组的嵌入。 | False |
get_networkx_graph方法
get_networkx_graph(limit: int = 100) -> Any
描述:获取图结构的networkx表示。
参数:
参数名 | 类型 | 描述 | 默认值 |
---|---|---|---|
limit | int | 图中包含的起始节点数量 | 100 |
注意:此函数需要安装networkx。此功能为测试版。
代码示例
创建KnowledgeGraphIndex
from llama_index.core import KnowledgeGraphIndex, StorageContext
from llama_index.core.graph_stores import SimpleGraphStore
from llama_index.llms.openai import OpenAI
# 定义LLM
llm = OpenAI(temperature=0, model="gpt-3.5-turbo")
# 创建图存储
graph_store = SimpleGraphStore()
storage_context = StorageContext.from_defaults(graph_store=graph_store)
# 创建KnowledgeGraphIndex
kg_index = KnowledgeGraphIndex(
storage_context=storage_context,
max_triplets_per_chunk=10,
include_embeddings=True,
)
插入三元组
triplet = ("Peter Quill", "is leader of", "Guardians of the Galaxy")
kg_index.upsert_triplet(triplet, include_embeddings=True)
添加节点
from llama_index.core.node_parser import SentenceSplitter
node_parser = SentenceSplitter()
nodes = node_parser.get_nodes_from_documents(documents)
kg_index.add_node(["Peter Quill", "Guardians of the Galaxy"], nodes[0])
插入三元组和节点
triplet = ("Peter Quill", "is leader of", "Guardians of the Galaxy")
kg_index.upsert_triplet_and_node(triplet, nodes[0], include_embeddings=True)
获取networkx图
import networkx as nx
from pyvis.network import Network
g = kg_index.get_networkx_graph(limit=100)
net = Network(notebook=True, cdn_resources="in_line", directed=True)
net.from_nx(g)
net.show("example.html")
总结
通过Llama Index的KnowledgeGraphIndex
,我们可以轻松地构建和查询知识图谱。无论是手动插入三元组和节点,还是获取图结构的networkx表示,Llama Index都提供了强大的工具来处理知识图谱任务。希望这篇博客能帮助你更好地理解和应用知识图谱技术。