资讯详情

【Use Cases】10. 使用LlamaCloud和Neo4J构建知识图谱

📅 2026/10/30 9:49:38 | 华诺云谱 👁 阅读
【Use Cases】10. 使用LlamaCloud和Neo4J构建知识图谱
1. 案例目标本案例展示了如何使用LlamaCloud套件和Neo4j构建知识图谱将非结构化的法律文档转换为结构化的知识表示。通过结合LlamaParse、LlamaClassify和LlamaExtract等工具实现从原始文档到可查询知识图谱的完整流程。主要目标包括使用LlamaClassify对合同进行分类联盟协议或品牌合作协议利用LlamaExtract从不同类型的合同中提取相关属性将所有结构化信息存储到Neo4j知识图谱中创建一个端到端的工作流程实现文档处理的自动化2. 技术栈与核心依赖LlamaIndexLlamaCloud ServicesNeo4jOpenAIPydanticAsync Programming核心依赖库llama-index-workflows llama-cloud-services jsonschema openai neo4j llama-index-llms-openaiLlamaCloud服务组件LlamaParse用于解析PDF文档LlamaClassify用于文档分类目前处于测试阶段LlamaExtract用于从文档中提取结构化信息3. 环境配置API密钥配置os.environ[LLAMA_CLOUD_API_KEY] your-llama-api-key os.environ[OPENAI_API_KEY] your-openai-api-keyNeo4j数据库配置db_url your-db-url username neo4j password your-password neo4j_driver AsyncGraphDatabase.driver( db_url, auth(username, password), )推荐使用免费的Aura数据库实例进行设置。4. 案例实现4.1 数据准备从Cuad数据集下载示例PDF合同文档!wget https://raw.githubusercontent.com/tomasonjo/blog-datasets/main/CybergyHoldingsInc_Affliate%20Agreement.pdf4.2 文档解析使用LlamaParse解析PDF文档parser LlamaParse(parse_modeparse_page_without_llm) pdf_path CybergyHoldingsInc_Affliate Agreement.pdf results await parser.aparse(pdf_path)4.3 合同分类定义分类规则并使用LlamaClassify对合同进行分类rules [ ClassifierRule( typeAffiliate Agreements, descriptionThis is a contract that outlines an affiliate agreement, ), ClassifierRule( typeCo Branding, descriptionThis is a contract that outlines a co-branding deal/agreement, ), ] classifier ClassifyClient( clientAsyncLlamaCloud( base_urlhttps://api.cloud.llamaindex.ai, tokenos.environ[LLAMA_CLOUD_API_KEY], ) ) result await classifier.aclassify_file_path( rulesrules, file_input_path/content/CybergyHoldingsInc_Affliate Agreement.pdf, )4.4 信息提取为不同类型的合同定义Pydantic模型并使用LlamaExtract提取结构化信息class BaseContract(BaseModel): Base contract class with common fields. parties: Optional[List[Party]] Field(None, descriptionAll contracting parties) agreement_date: Optional[str] Field(None, descriptionContract signing date. Use YYYY-MM-DD) effective_date: Optional[str] Field(None, descriptionWhen contract becomes effective. Use YYYY-MM-DD) # ... 其他字段 class AffiliateAgreement(BaseContract): Affiliate Agreement extraction. exclusivity: Optional[str] Field(None, descriptionExclusive territory or market rights) non_compete: Optional[str] Field(None, descriptionNon-compete restrictions) # ... 其他特定字段 # 根据分类结果选择相应的提取模式 extractor LlamaExtract() agent extractor.create_agent( namefextraction_workflow_import_{uuid.uuid4()}, data_schemamapping[classification.type], configExtractConfig(extraction_modeExtractMode.BALANCED), ) result await agent.aextract( filesSourceText( text_content .join([el.text for el in results.pages]), filenamepdf_path, ), )4.5 知识图谱构建将提取的结构化信息导入Neo4j知识图谱import_query WITH $contract AS contract MERGE (c:Contract {path: $path}) SET c apoc.map.clean(contract, [parties, agreement_date, effective_date, expiration_date], []) // Cast to date SET c.agreement_date date(contract.agreement_date), c.effective_date date(contract.effective_date), c.expiration_date date(contract.expiration_date) // Create parties with their locations WITH c, contract UNWIND coalesce(contract.parties, []) AS party MERGE (p:Party {name: party.name}) MERGE (c)-[:HAS_PARTY]-(p) // Create location nodes and link to parties WITH p, party WHERE party.location IS NOT NULL MERGE (p)-[:HAS_LOCATION]-(l:Location) SET l party.location response await neo4j_driver.execute_query( import_query, contractresult.data, pathpdf_path )4.6 工作流程整合使用LlamaIndex Workflow API将所有步骤整合为一个端到端的工作流程class KnowledgeGraphBuilder(Workflow): def __init__( self, classifier: ClassifyClient, rules: List[ClassifierRule], affiliate_extract_agent: LlamaExtract, cobranding_extract_agent: LlamaExtract, **kwargs, ): super().__init__(**kwargs) self.classifier classifier self.rules rules self.affiliate_extract_agent affiliate_extract_agent self.cobranding_extract_agent cobranding_extract_agent step async def classify_contract( self, ctx: Context, ev: StartEvent ) - ExtractAffiliate | ExtractCoBranding | StopEvent: result await self.classifier.aclassify_file_path( rulesself.rules, file_input_pathev.pdf_path ) contract_type result.items[0].result.type print(contract_type) if contract_type affiliate_agreements: return ExtractAffiliate(file_pathev.pdf_path) elif contract_type co_branding: return ExtractCoBranding(file_pathev.pdf_path) else: return StopEvent() # ... 其他步骤方法 # 运行工作流程 knowledge_graph_builder KnowledgeGraphBuilder( classifierclassifier, rulesrules, affiliate_extract_agentaffiliate_extraction_agent, cobranding_extract_agentcobranding_extraction_agent, timeoutNone, verboseTrue, ) response await knowledge_graph_builder.run( pdf_pathCybergyHoldingsInc_Affliate Agreement.pdf )5. 案例效果该案例实现了从原始PDF文档到结构化知识图谱的完整转换流程具体效果包括成功解析PDF合同文档提取文本内容准确识别合同类型联盟协议或品牌合作协议根据合同类型提取相应的结构化信息包括合同方、日期、条款等在Neo4j中构建包含合同、合同方和位置节点的知识图谱建立节点之间的关系如合同与合同方的关联、合同方与位置的关联通过工作流程实现整个处理流程的自动化提取的示例数据包括合同方信息Birch First Global Investments Inc.和Mount Knowledge Holdings Inc.合同日期2014年5月8日管辖法律内华达州收入分享根据年度购买水平提供15%-25%的购买折扣最低承诺前六个月内购买至少100个单位6. 案例实现思路本案例的实现思路遵循了典型的知识图谱构建流程将非结构化文档转换为结构化知识表示6.1 数据处理流程文档解析使用LlamaParse将PDF文档转换为可处理的文本内容文档分类利用LlamaClassify识别文档类型为后续提取提供上下文信息提取根据文档类型使用相应的Pydantic模型提取结构化信息知识图谱构建将提取的信息转换为Neo4j中的节点和关系6.2 技术架构案例采用分层架构设计数据层PDF文档作为原始数据源处理层LlamaCloud服务提供解析、分类和提取功能存储层Neo4j作为知识图谱存储和查询引擎流程层LlamaIndex Workflow API整合各组件为端到端流程6.3 关键设计决策异步编程全面采用异步编程模式提高处理效率类型安全使用Pydantic模型确保数据提取的结构化和类型安全模块化设计将不同功能分离为独立组件提高可维护性动态模式选择根据文档分类结果动态选择相应的提取模式7. 扩展建议1. 扩展文档类型支持添加更多合同类型的分类规则和提取模式如保密协议(NDA)、服务协议(SLA)、采购协议等。2. 增强关系提取除了提取实体属性外进一步提取实体间的关系如公司间的投资关系、人员任职关系等。3. 集成向量检索将知识图谱与向量检索结合实现基于语义相似度和图结构的混合检索。4. 添加时间维度增强对合同时间相关信息的处理如有效期、续约条件、里程碑事件等。5. 实现问答系统基于构建的知识图谱开发智能问答系统支持自然语言查询合同信息。6. 可视化界面开发Web界面支持文档上传、处理进度跟踪和知识图谱可视化。7. 批量处理能力优化系统以支持大规模文档批量处理提高处理效率和可扩展性。8. 总结本案例展示了如何利用LlamaCloud服务和Neo4j构建知识图谱的完整流程实现了从非结构化文档到结构化知识表示的转换。通过结合LlamaParse、LlamaClassify和LlamaExtract等工具以及LlamaIndex Workflow API创建了一个端到端的文档处理工作流程。该案例的价值在于提供了一种将法律文档转换为可查询知识图谱的实用方法展示了LlamaCloud套件各组件的协同工作方式演示了如何使用工作流API整合多个处理步骤为构建基于知识图谱的智能应用提供了基础这种方法可以扩展到其他领域如医疗记录分析、科研论文处理、技术文档管理等为各种非结构化文档的智能化处理提供了参考框架。
📝

华诺云谱内容团队

资深建站顾问 · 行业研究员

10年+企业数字化服务经验,专注智能建站、SEO优化与品牌营销,持续输出建站技巧、行业洞察与营销干货,已帮助5000+企业实现数字化增长。

你可能需要的服务

订阅华诺云谱资讯周报

每周一封,精选建站技巧、SEO与营销干货,直达邮箱。已有 8,000+ 企业主订阅,助你少走弯路。

↑