#Createalocalenvironment$poetryconfigvirtualenvs.createfalse--local#Installdependencies.$poetryinstall
该库理解本体的以下模式。在幕后,本体论是一个迂腐的模型。
ontology=Ontology(#labelsoftheentitiestobeextracted.Canbeastringoranobject,likethefollowing.labels=[{"
erson":"
ersonnamewithoutanyadjectives,Rememberapersonmaybereferencesbytheirnameorusingapronoun"},{"Object":"Donotaddthedefinitearticle'the'intheobjectname"},{"Event":"Eventeventinvolvingmultiplepeople.Donotincludequalifiersorverbslikegives,leaves,worksetc."},"
lace","Document","Organisation","Action",{"Miscellanous":"Anyimportantconceptcannotbecategorisedwithanyothergivenlabel"},],#Relationshipsthatareimportantforyourapplication.#ThesearemorelikeinstructionsfortheLLMtonudgeittofocusonspecificrelationships.#Thereisnoguarenteethatonlytheserelationshipswillbeextracted,butsomemodelsdoagoodjoboverallatstickingtotheserelations.relationships=["RelationbetweenanypairofEntities",],)我已经调整了提示以产生与给定本体一致的结果。我认为它在这方面做得很好。然而,它仍然不是 100% 准确。准确性取决于我们选择生成图表的模型、应用程序、本体和数据质量。
我们可以使用尽可能多的文本语料库来创建大型知识图。然而,LLMs 现在有一个有限的上下文窗口。因此,我们需要对文本进行适当的分块,并一次创建一个图块。我们应该使用的块大小取决于模型上下文窗口。该项目中使用的提示消耗了大约 500 个代币。上下文的其余部分可以分为输入文本和输出图形。根据我的经验,800 到 1200 个令牌块非常合适。
Documents 是一个 pydantic 模型,具有以下架构
##PydanticdocumentmodelclassDocument(BaseModel):text:strmetadata:dict
我们在此处添加到文档的元数据被标记到从文档中提取的每个关系。我们可以将关系的上下文,例如页码、章节、文章名称等添加到元数据中。通常,每个节点对在多个文档中彼此具有多种关系。元数据有助于将这些关系置于上下文中。
图形制作器直接获取文档列表并迭代每个文档以为每个文档创建一个子图。最终输出是所有文档的完整图表。
这是简单的示例代码
from graph_maker import GraphMaker, Ontology, GroqClientfrom graph_maker import Document## Select a groq supported model## model = "mixtral-8x7b-32768"model ="llama3-8b-8192"## model = "llama3-70b-8192"## model="gemma-7b-it" ## This is probably the fastest of all models, though a tad inaccurate.llm = GroqClient(model=model, temperature=0.1, top_p=0.5)graph_maker = GraphMaker(ontology=ontology, llm_client=llm, verbose=False)## create a graph out of a list of Documents.graph = graph_maker.from_documents(list(docs),delay_s_between=10 ## delay_s_between because otherwise groq api maxes out pretty fast.)## result -> a list of Edges.print("Total number of Edges", len(graph))## 1503
输出是作为边列表的最终图,其中每条边都是如下所示的 pydantic 模型。
class Node(BaseModel):label: strname: strclass Edge(BaseModel):node_1: Nodenode_2: Noderelationship: strmetadata: dict = {}order: Union[int, None] = None
图形制作者通过模型运行每个文档并将响应解析为图形边缘。我已经将提示调整到了非常容错的程度。大多数 JSON 错误都会自动更正。如果 JSON 响应无法解析,它还会尝试手动将 JSON 字符串拆分为多个边字符串,然后尝试分别解析每个字符串。
我们可以将模型保存到 Neo4j 中,以创建 RAG 应用程序、运行网络算法,或者只是使用 Bloom 可视化图形
github.com/rahulnyk/graph_maker
| 欢迎光临 链载Ai (https://www.lianzai.com/) | Powered by Discuz! X3.5 |