148 使用Llama Index构建和查询知识图谱:全面指南

使用Llama Index构建和查询知识图谱:全面指南

在人工智能和数据科学的不断发展中,知识图谱已成为组织和查询复杂信息的强大工具。知识图谱是一种结构化的实体及其关系的表示,使得理解和检索信息变得更加容易。在本篇博客中,我们将深入探讨如何使用Llama Index的KnowledgeGraphIndex从非结构化文本中自动构建知识图谱,并进行基于实体的查询。

前置知识

在深入代码之前,确保你具备以下基础知识:

  1. Python基础:熟悉Python编程。
  2. OpenAI API密钥:你需要一个OpenAI API密钥来使用OpenAI模型。
  3. Llama Index:使用pip install llama-index-llms-openai安装Llama Index库。

环境设置

首先,让我们通过安装所需的包并配置OpenAI API密钥来设置环境。

# 安装Llama Index
%pip install llama-index-llms-openai

# 设置OpenAI API密钥
import os
os.environ["OPENAI_API_KEY"] = "INSERT OPENAI KEY"

# 配置日志
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO)

构建知识图谱

加载文档

要构建知识图谱,我们首先需要加载一些非结构化文本文档。Llama Index提供了SimpleDirectoryReader来从目录中加载文档。

from llama_index.core import SimpleDirectoryReader, KnowledgeGraphIndex
from llama_index.core.graph_stores import SimpleGraphStore
from llama_index.llms.openai import OpenAI
from llama_index.core import Settings

# 加载文档
documents = SimpleDirectoryReader(
    "../../../../examples/paul_graham_essay/data"
).load_data()

初始化语言模型

接下来,我们初始化OpenAI语言模型。该模型将帮助我们从文本中理解和提取关系。

# 定义LLM
llm = OpenAI(temperature=0, model="text-davinci-002")
Settings.llm = llm
Settings.chunk_size = 512

创建存储上下文

我们需要创建一个存储上下文来存储知识图谱。

from llama_index.core import StorageContext

graph_store = SimpleGraphStore()
storage_context = StorageContext.from_defaults(graph_store=graph_store)

构建知识图谱索引

现在,我们可以从文档中构建知识图谱索引。注意,这个过程可能需要一些时间。

# 构建知识图谱索引
index = KnowledgeGraphIndex.from_documents(
    documents,
    max_triplets_per_chunk=2,
    storage_context=storage_context,
)

查询知识图谱

基本查询

我们可以使用查询引擎来查询知识图谱。以下是一个简单的查询示例。

query_engine = index.as_query_engine(
    include_text=False, response_mode="tree_summarize"
)
response = query_engine.query(
    "Tell me more about Interleaf",
)
display(Markdown(f"<b>{response}</b>"))

包含文本的查询

我们还可以在查询中包含文本信息。

query_engine = index.as_query_engine(
    include_text=True, response_mode="tree_summarize"
)
response = query_engine.query(
    "Tell me more about what the author worked on at Interleaf",
)
display(Markdown(f"<b>{response}</b>"))

使用嵌入的查询

如果我们希望在查询中使用嵌入,可以构建一个包含嵌入的知识图谱索引。

new_index = KnowledgeGraphIndex.from_documents(
    documents,
    max_triplets_per_chunk=2,
    include_embeddings=True,
)

query_engine = new_index.as_query_engine(
    include_text=True,
    response_mode="tree_summarize",
    embedding_mode="hybrid",
    similarity_top_k=5,
)
response = query_engine.query(
    "Tell me more about what the author worked on at Interleaf",
)
display(Markdown(f"<b>{response}</b>"))

可视化知识图谱

我们可以使用pyvis库来可视化知识图谱。

from pyvis.network import Network

g = index.get_networkx_graph()
net = Network(notebook=True, cdn_resources="in_line", directed=True)
net.from_nx(g)
net.show("example.html")

手动添加三元组

我们还可以手动构建知识图谱并添加三元组。

from llama_index.core.node_parser import SentenceSplitter
node_parser = SentenceSplitter()
nodes = node_parser.get_nodes_from_documents(documents)

index = KnowledgeGraphIndex(
    [],
)

# 添加三元组
node_0_tups = [
    ("author", "worked on", "writing"),
    ("author", "worked on", "programming"),
]
for tup in node_0_tups:
    index.upsert_triplet_and_node(tup, nodes[0])

node_1_tups = [
    ("Interleaf", "made software for", "creating documents"),
    ("Interleaf", "added", "scripting language"),
    ("software", "generate", "web sites"),
]
for tup in node_1_tups:
    index.upsert_triplet_and_node(tup, nodes[1])

query_engine = index.as_query_engine(
    include_text=False, response_mode="tree_summarize"
)
response = query_engine.query(
    "Tell me more about Interleaf",
)
display(Markdown(f"<b>{response}</b>"))

总结

通过Llama Index的KnowledgeGraphIndex,我们可以轻松地从非结构化文本中构建知识图谱,并进行高效的查询。无论是自动构建还是手动添加三元组,Llama Index都提供了强大的工具来处理复杂的知识图谱任务。希望这篇博客能帮助你更好地理解和应用知识图谱技术。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

需要重新演唱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值