Skip to main content

图形问答(Graph QA)

本笔记本介绍了如何在图形数据结构上进行问答。

创建图形

在本节中,我们构建一个示例图形。目前,这对于小段文本效果最好。

from langchain.indexes import GraphIndexCreator
from langchain.llms import OpenAI
from langchain.document_loaders import TextLoader
index_creator = GraphIndexCreator(llm=OpenAI(temperature=0))
with open("../../state_of_the_union.txt") as f:
all_text = f.read()

我们只使用一个小片段,因为目前提取知识三元组有点耗时。

text = "\n".join(all_text.split("\n\n")[105:108])
text
    'It won’t look like much, but if you stop and look closely, you’ll see a “Field of dreams,” the ground on which America’s future will be built. \nThis is where Intel, the American company that helped build Silicon Valley, is going to build its $20 billion semiconductor “mega site”. \nUp to eight state-of-the-art factories in one place. 10,000 new good-paying jobs. '
graph = index_creator.from_text(text)

我们可以检查创建的图形。

graph.get_triples()
    [('Intel', '$20 billion semiconductor "mega site"', 'is going to build'),
('Intel', 'state-of-the-art factories', 'is building'),
('Intel', '10,000 new good-paying jobs', 'is creating'),
('Intel', 'Silicon Valley', 'is helping build'),
('Field of dreams',
"America's future will be built",
'is the ground on which')]

查询图形

现在我们可以使用图形问答链来对图形进行提问。

from langchain.chains import GraphQAChain
chain = GraphQAChain.from_llm(OpenAI(temperature=0), graph=graph, verbose=True)
chain.run("Intel将要建造什么?")
    

> 进入新的GraphQAChain链...
提取的实体:
Intel
完整上下文:
Intel将要建造$200亿的半导体“超级工厂”
Intel正在建造先进的工厂
Intel正在创造1万个新的高薪工作
Intel正在帮助建设硅谷

> 完成链。



' Intel将要建造一个价值200亿美元的半导体“超级工厂”,配备先进的工厂,创造1万个新的高薪工作,并帮助建设硅谷。'

保存图形

我们还可以保存和加载图形。

graph.write_to_gml("graph.gml")
from langchain.indexes.graph import NetworkxEntityGraph
loaded_graph = NetworkxEntityGraph.from_gml("graph.gml")
loaded_graph.get_triples()
    [('Intel', '$20 billion semiconductor "mega site"', 'is going to build'),
('Intel', 'state-of-the-art factories', 'is building'),
('Intel', '10,000 new good-paying jobs', 'is creating'),
('Intel', 'Silicon Valley', 'is helping build'),
('Field of dreams',
"America's future will be built",
'is the ground on which')]