Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.
feat: 新增 AutoHypergraph 示例,展示复杂叙事文本的超边关系提取与分析
yifanfeng978ff79edb2dae
diff --git a/examples/auto_hypergraph_demo.py b/examples/auto_hypergraph_demo.pynew file mode 100644index 0000000..97638d9--- /dev/null+++ b/examples/auto_hypergraph_demo.py@@ -0,0 +1,360 @@+"""+AutoHypergraph 演示:星际外交危机的故事线分析++这个例子展示了如何使用 AutoHypergraph 从复杂的叙事文本中提取多类型的超边关系。+超边可以代表不同类型的故事单元:冲突、结盟、持有关系、会议等。+"""++import os+import sys+import collections+from typing import List+from pathlib import Path++# 添加父目录到路径+sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from dotenv import load_dotenv+from pydantic import BaseModel, Field+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.hypergraphs import AutoHypergraph++load_dotenv()++# ==============================================================================+# 1. 定义 Schema:灵活的叙事结构+# ==============================================================================+++class StoryEntity(BaseModel):+ """+ 节点:故事中的基本元素。+ 可以是:人物(Character), 地点(Location), 物品(Item), 派系(Faction)+ """++ name: str = Field(..., description="实体名称,如 'Neo', 'Matrix', 'Excalibur'")+ category: str = Field(+ ...,+ description="实体类别: Character(人物), Location(地点), Item(物品), Faction(派系)",+ )+ description: str = Field(+ default="", description="实体的详细描述,如 '黑蛇'(Character) 的角色是 Which Snake"+ )+++class NarrativeUnit(BaseModel):+ """+ 超边:一个叙事单元。++ 这不仅仅是一个关系,它可以是一个发生的事件、一种复杂的联盟、或者一个状态。+ 关键在于:它通过一个 'type' 字段来区分语义,但结构上都是连接多个实体的超边。+ """++ summary: str = Field(..., description="简短描述这个单元发生了什么,或者是什么关系")++ # 这里体现了"多类型":LLM 会判断这具体是什么类型的连接+ edge_type: str = Field(+ ...,+ description="超边类型: Conflict(冲突), Alliance(结盟), Possession(持有), Meeting(会议), State(状态)",+ )++ # 核心:连接所有相关的实体+ participants: List[str] = Field(..., description="所有牵涉其中的实体名称列表")+++# ==============================================================================+# 2. 故事文本:星际外交危机+# ==============================================================================++source_text = """+【银河纪元 3042年 - 赤红星云事件报告】++危机在这一周达到了顶峰。整个银河系似乎都陷入了暗流涌动的政治漩涡。++【第一阶段:秘密接触】+臭名昭著的星际海盗黑蛇驾驶着他的旗舰复仇号,在泰坦空间站秘密会见了银河联邦的背叛者议员 Valerius。+目击者称,两人在午夜时分登上了空间站的顶层禁区。据情报部门推测,这是一次肮脏的交易——+双方达成了针对皇室的同盟关系。参与此会议的还有 Valerius 手下的特务头目 Shadow,+他负责处理所有不可告人的细节。这个同盟的形成标志着大麻烦即将到来。++【第二阶段:叛变与夺权】+在这次会议的两天后,事态急剧恶化。黑蛇这种疯狂的家伙竟然在极光星区伏击了皇家护卫队。+这场突然的冲突中,皇家护卫队的队长 Leona 与副队长 Marcus 奋力抵抗,+但他们陷入了黑蛇手下的精锐战士的包围。这场激战导致队长 Leona 身受重伤。+而黑蛇的目标不是为了杀戮,而是为了夺取一件神圣的物品——传说中的虚空水晶。+这枚水晶散发着幽蓝的光芒,据说能够打开先祖之门的第一道密封。+黑蛇在战斗中成功夺取了水晶,但 Leona 在临终前用最后的力量将其重新夺回。++【第三阶段:流亡与隐藏】+Leona 被迫带着虚空水晶,从极光星区逃往荒凉的废土行星 Z-9。+在这个被遗忘的角落,她向仅有的几个信任者求救:还有副队长 Marcus 以及隐秘组织"地下抵抗军"的领导人 Cipher。+同时,议员 Valerius 非法持有了开启先祖之门的钥匙——这把钥匙本应被安全保管在皇家金库中。+他现在藏匿在浮空都市中,与黑蛇遥相呼应,计划着下一步的政变。++【第四阶段:势力重组】+银河联邦的最高委员会得知了这一系列事件,决定采取行动。+高级顾问 Artemis 被任命为特使,她与 Leona 在废土行星 Z-9 进行了秘密会晤,+讨论如何制止这场即将到来的危机。同时,地下抵抗军的 Cipher 也加入了这次会议,+三人共同制定了一个大胆的计划。++【第五阶段:最后的筹码】+虽然黑蛇未能获得虚空水晶,但他已经从 Valerius 那里获得了先祖之门钥匙的复制品。+根据情报,这个复制品目前被秘密运往到黑蛇的秘密基地——位于辐射荒漠中的要塞。+参与此次运送的还有 Shadow 和黑蛇手下的精锐战士群体。+与此同时,Leona 和 Marcus 正在准备一场反击,他们计划在虚空水晶的力量下重新夺回局势的控制权。++目前局势:+- 黑蛇:手持复制品钥匙,掌控旗舰复仇号,计划进行最终的攻击+- 议员 Valerius:躲在浮空都市中,与黑蛇保持联系+- Leona:守护虚空水晶,在废土行星 Z-9 养伤,准备反击+- 银河联邦:通过特使 Artemis 支持 Leona,正在调集力量+- 地下抵抗军:Cipher 领导,与 Leona 和 Marcus 联手,准备对抗黑蛇和 Valerius 的同盟++这场战争的走向仍不确定。虚空水晶、先祖之门、以及隐藏在这一切背后的秘密,+都将在接下来的日子里浮出水面。银河的命运,可能就在这些关键人物和物品的碰撞中决定。+"""+++# ==============================================================================+# 3. 提取逻辑配置+# ==============================================================================+++def main():+ """主函数:完整的 AutoHypergraph 提取与分析流程"""++ # 初始化 LLM 和嵌入模型+ llm = ChatOpenAI(model="gpt-4o", temperature=0)+ embedder = OpenAIEmbeddings()++ # 1. 节点指纹:用名字即可+ node_key_fn = lambda x: x.name++ # 2. 边指纹:类型 + 摘要 + 参与者(排序)+ # 这样即使是同一群人,如果发生了两件事,也会被视为两条边+ def edge_key_fn(x: NarrativeUnit) -> str:+ participants = sorted(x.participants)+ return f"{x.edge_type}|{'-'.join(participants)}"++ # 3. 参与者映射:告诉框架谁在这个超边里+ participants_fn = lambda x: tuple(x.participants)++ print("=" * 70)+ print("🚀 AutoHypergraph 演示:赤红星云事件分析")+ print("=" * 70)+ print()++ # 创建 AutoHypergraph 实例+ hypergraph = AutoHypergraph(+ node_schema=StoryEntity,+ edge_schema=NarrativeUnit,+ node_key_extractor=node_key_fn,+ edge_key_extractor=edge_key_fn,+ nodes_in_edge_extractor=participants_fn,+ llm_client=llm,+ embedder=embedder,+ extraction_mode="two_stage", # 推荐:先识别实体,再梳理故事线+ show_progress=True,+ # 使用中文 Prompt 引导 LLM+ prompt_for_node_extraction=(+ "你的任务是从故事文本中提取所有重要的实体节点。\n"+ "实体可以是以下类别之一:\n"+ "- Character(人物):故事中出现的角色\n"+ "- Location(地点):故事发生的地方\n"+ "- Item(物品):故事中提到的重要物品或武器\n"+ "- Faction(派系):故事中的组织或势力\n\n"+ "请确保提取所有重要的实体,并正确分类它们的类别。"+ ),+ prompt_for_edge_extraction=(+ "你的任务是从故事文本中提取复杂的叙事关系,将其建模为超边。\n"+ "超边可以连接任意数量的实体(Character、Location、Item、Faction)。\n\n"+ "请根据故事内容,识别并分类以下类型的超边:\n"+ "- Conflict(冲突):两个或多个角色之间的战斗或对抗\n"+ "- Alliance(结盟):角色或派系之间的同盟或合作关系\n"+ "- Possession(持有):某个角色拥有或守护某件物品\n"+ "- Meeting(会议):多个角色在某个地点进行的会面\n"+ "- State(状态):描述某个角色或物品在某个地点的状态\n\n"+ "对于每个超边,请提供:\n"+ "1. summary:对这个叙事单元的简洁描述\n"+ "2. edge_type:上述分类之一\n"+ "3. participants:所有牵涉其中的实体名称列表\n\n"+ "确保 participants 列表包含故事中与该事件相关的所有实体。"+ ),+ chunk_size=1000,+ )++ print("📚 正在分析《赤红星云事件报告》...")+ print(f" 文本长度:{len(source_text)} 字符")+ print()++ # 执行提取+ hypergraph.feed_text(source_text)++ # ==============================================================================+ # 4. 结果展示:按类型分类+ # ==============================================================================++ print("\n" + "=" * 70)+ print(f"🎭 第一部分:登场角色与物品 ({len(hypergraph.nodes)} 个实体)")+ print("=" * 70)++ # 按类别打印+ nodes_by_cat = collections.defaultdict(list)+ for n in hypergraph.nodes:+ nodes_by_cat[n.category].append(n.name)++ category_emoji = {"Character": "👤", "Location": "📍", "Item": "⚔️", "Faction": "🏛️"}++ for cat in ["Character", "Location", "Item", "Faction"]:+ if cat in nodes_by_cat:+ emoji = category_emoji.get(cat, "•")+ names = ", ".join(nodes_by_cat[cat])+ print(+ f"\n {emoji} {cat}({cat == 'Character' and '人物' or cat == 'Location' and '地点' or cat == 'Item' and '物品' or '派系'}):"+ )+ print(f" {names}")++ # ==============================================================================+ # 5. 故事线展示:按超边类型分类+ # ==============================================================================++ print("\n" + "=" * 70)+ print(f"🎬 第二部分:故事线分析 ({len(hypergraph.edges)} 个叙事单元)")+ print("=" * 70)++ # 按类型分组+ edges_by_type = collections.defaultdict(list)+ for e in hypergraph.edges:+ edges_by_type[e.edge_type].append(e)++ type_emoji = {+ "Conflict": "⚔️",+ "Alliance": "🤝",+ "Possession": "🎁",+ "Meeting": "🤵",+ "State": "📊",+ }++ type_cn = {+ "Conflict": "冲突",+ "Alliance": "结盟",+ "Possession": "持有",+ "Meeting": "会议",+ "State": "状态",+ }++ for e_type in ["Conflict", "Alliance", "Meeting", "Possession", "State"]:+ if e_type in edges_by_type:+ emoji = type_emoji.get(e_type, "•")+ cn_name = type_cn.get(e_type, e_type)+ edges = edges_by_type[e_type]+ print(f"\n {emoji} 【{cn_name}】类型 ({len(edges)} 个事件):")+ for i, e in enumerate(edges, 1):+ print(f"\n {i}. 事件描述:{e.summary}")+ print(f" 🔗 参与方:{', '.join(e.participants)}")++ # ==============================================================================+ # 6. 实体中心性分析:哪个实体参与了最多的故事线+ # ==============================================================================++ print("\n" + "=" * 70)+ print("📊 第三部分:关键实体分析(超边参与度)")+ print("=" * 70)++ entity_participation = collections.defaultdict(int)+ for e in hypergraph.edges:+ for participant in e.participants:+ entity_participation[participant] += 1++ # 按参与度排序+ sorted_entities = sorted(+ entity_participation.items(), key=lambda x: x[1], reverse=True+ )++ print("\n 参与故事线最多的实体(中心性分析):\n")+ for rank, (entity, count) in enumerate(sorted_entities[:10], 1):+ bar = "█" * count+ print(f" {rank:2d}. {entity:12s} {bar} ({count} 个故事线)")++ # ==============================================================================+ # 7. 复杂查询演示+ # ==============================================================================++ print("\n" + "=" * 70)+ print("🔍 第四部分:语义搜索演示")+ print("=" * 70)++ # 建立索引+ print("\n 正在构建搜索索引...")+ hypergraph.build_index(index_nodes=True, index_edges=True)++ # 执行几个查询+ queries = [+ "虚空水晶在哪里?谁守护着它?",+ "Leona 发生了什么事?",+ "黑蛇的计划是什么?",+ ]++ for query in queries:+ print(f"\n 🎯 查询:{query}")+ results = hypergraph.search_edges(query, top_k=3)+ if results:+ for j, res in enumerate(results, 1):+ print(f" → 结果 {j} [{res.edge_type}]:{res.summary}")+ else:+ print(f" → 未找到相关信息")++ # ==============================================================================+ # 8. 关系图统计+ # ==============================================================================++ print("\n" + "=" * 70)+ print("📈 第五部分:图统计")+ print("=" * 70)++ print(f"\n 节点总数(实体):{len(hypergraph.nodes)}")+ print(f" 边总数(叙事单元):{len(hypergraph.edges)}")++ avg_participants = (+ sum(len(e.participants) for e in hypergraph.edges) / len(hypergraph.edges)+ if hypergraph.edges+ else 0+ )+ print(f" 平均每条边的参与度:{avg_participants:.2f} 个实体")++ max_participants_edge = (+ max(hypergraph.edges, key=lambda e: len(e.participants))+ if hypergraph.edges+ else None+ )+ if max_participants_edge:+ print(f" 最复杂的叙事单元:{max_participants_edge.summary}")+ print(f" 参与实体数:{len(max_participants_edge.participants)}")++ # ==============================================================================+ # 9. 保存超图到本地+ # ==============================================================================++ print("\n" + "=" * 70)+ print("💾 保存超图到本地")+ print("=" * 70)++ # 获取项目根目录+ project_root = Path(__file__).resolve().parent.parent+ save_path = project_root / "temp" / "auto_hypergraph_demo"++ try:+ hypergraph.dump(save_path)+ print(f"\n ✅ 超图已保存到: {save_path}")+ print(f" 节点数: {len(hypergraph.nodes)}")+ print(f" 边数: {len(hypergraph.edges)}")+ except Exception as e:+ print(f"\n ⚠️ 保存失败: {e}")++ print("\n" + "=" * 70)+ print("✅ 分析完成!")+ print("=" * 70)+++if __name__ == "__main__":+ main()diff --git a/examples/auto_list_operations_demo.py b/examples/auto_list_operations_demo.pydeleted file mode 100644index e302f20..0000000--- a/examples/auto_list_operations_demo.py+++ /dev/null@@ -1,202 +0,0 @@-"""-演示 AutoList 的 Pythonic 列表操作--这个示例展示了如何像使用 Python 原生 list 一样使用 AutoList:-- 索引访问和切片-- 迭代和成员测试-- 追加、插入和扩展-- 删除和弹出元素-- 查找和计数-- 复制、反转和排序-"""--import sys-from pathlib import Path--# 添加项目根目录到 Python 路径-project_root = Path(__file__).parent.parent-sys.path.insert(0, str(project_root))--import os-from dotenv import load_dotenv-from pydantic import BaseModel, Field-from langchain_openai import ChatOpenAI, OpenAIEmbeddings--from hyperextract import AutoList--# 加载环境变量-load_dotenv()---# 定义一个简单的任务Schema-class Task(BaseModel):- """项目任务"""-- name: str = Field(description="任务名称")- priority: int = Field(description="优先级 (1-5)")- status: str = Field(description="状态: pending, in_progress, done")---def main():- # 初始化 LLM 和 Embedder- llm = ChatOpenAI(- model="gpt-4o-mini",- api_key=os.getenv("OPENAI_API_KEY"),- base_url=os.getenv("OPENAI_BASE_URL"),- )-- embedder = OpenAIEmbeddings(- api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_BASE_URL")- )-- # 创建 AutoList 实例- a_task_list = AutoList(- item_schema=Task,- llm_client=llm,- embedder=embedder,- )-- print("=" * 70)- print("AutoList Pythonic 操作演示")- print("=" * 70)-- # 1. 使用 append 添加任务- print("\n1. 使用 append() 添加任务:")- a_task_list.append(Task(name="实现用户登录", priority=5, status="done"))- a_task_list.append(Task(name="设计数据库", priority=4, status="done"))- a_task_list.append(Task(name="编写API文档", priority=3, status="in_progress"))- print(f" 已添加 {len(a_task_list)} 个任务")-- # 2. 索引访问- print("\n2. 索引访问:")- print(f" 第一个任务: {a_task_list[0].name} (优先级 {a_task_list[0].priority})")- print(f" 最后一个任务: {a_task_list[-1].name} (状态: {a_task_list[-1].status})")-- # 3. 切片- print("\n3. 切片操作:")- high_priority = a_task_list[:2]- print(f" 前两个高优先级任务:")- for task in high_priority:- print(f" - {task.name} (P{task.priority})")-- # 4. 迭代- print("\n4. 遍历所有任务:")- for i, task in enumerate(a_task_list, 1):- print(f" {i}. {task.name} - {task.status}")-- # 5. 使用列表推导式- print("\n5. 列表推导式 - 获取所有任务名称:")- task_names = [task.name for task in a_task_list]- print(f" {task_names}")-- # 6. 成员测试- print("\n6. 成员测试 (in 操作符):")- test_task = Task(name="编写API文档", priority=3, status="in_progress")- print(f" 测试任务在列表中: {test_task in a_task_list}")-- # 7. 插入任务- print("\n7. 使用 insert() 在开头插入紧急任务:")- a_task_list.insert(0, Task(name="修复生产BUG", priority=5, status="in_progress"))- print(f" 新的第一个任务: {a_task_list[0].name}")-- # 8. 扩展多个任务- print("\n8. 使用 extend() 批量添加任务:")- new_tasks = [- Task(name="代码审查", priority=3, status="pending"),- Task(name="性能优化", priority=2, status="pending"),- ]- a_task_list.extend(new_tasks)- print(f" 现在共有 {len(a_task_list)} 个任务")-- # 9. 查找和计数- print("\n9. 查找和计数:")- in_progress_count = sum(1 for t in a_task_list if t.status == "in_progress")- print(f" 进行中的任务数量: {in_progress_count}")-- # 查找第一个 pending 任务的位置- for i, task in enumerate(a_task_list):- if task.status == "pending":- print(f" 第一个待处理任务位置: 索引 {i} - {task.name}")- break-- # 10. 修改任务- print("\n10. 修改任务状态 (通过索引赋值):")- print(f" 修改前: {a_task_list[-1].name} - {a_task_list[-1].status}")- updated_task = a_task_list[-1]- updated_task.status = "done"- a_task_list[-1] = updated_task- print(f" 修改后: {a_task_list[-1].name} - {a_task_list[-1].status}")-- # 11. 删除任务- print("\n11. 删除已完成的任务:")- print(f" 删除前共有 {len(a_task_list)} 个任务")- # 删除第一个任务- del a_task_list[0]- print(f" 删除后共有 {len(a_task_list)} 个任务")-- # 12. Pop 操作- print("\n12. 使用 pop() 移除并返回任务:")- last_task = a_task_list.pop()- print(f" 弹出的任务: {last_task.name}")- print(f" 剩余 {len(a_task_list)} 个任务")-- # 13. 复制- print("\n13. 创建任务列表的副本:")- tasks_backup = a_task_list.copy()- tasks_backup.append(Task(name="新任务", priority=1, status="pending"))- print(f" 原始列表: {len(a_task_list)} 个任务")- print(f" 副本列表: {len(tasks_backup)} 个任务")- print(" ✓ 副本是独立的")-- # 14. 排序- print("\n14. 按优先级排序任务 (降序):")- a_task_list.sort(key=lambda t: t.priority, reverse=True)- print(" 排序后的任务列表:")- for task in a_task_list:- print(f" - P{task.priority}: {task.name}")-- # 15. 反转- print("\n15. 反转任务列表:")- a_task_list.reverse()- print(" 反转后:")- for task in a_task_list:- print(f" - {task.name}")-- # 16. 字符串表示- print("\n16. 字符串表示:")- print(f" repr: {repr(a_task_list)}")- print(f" str: {str(a_task_list)}")-- # 17. 组合操作- print("\n17. 组合两个 AutoList (+ 操作符):")- more_tasks = AutoList(- item_schema=Task,- llm_client=llm,- embedder=embedder,- )- more_tasks.append(Task(name="部署到生产", priority=5, status="pending"))-- combined = a_task_list + more_tasks- print(f" 原始任务: {len(a_task_list)} 个")- print(f" 新增任务: {len(more_tasks)} 个")- print(f" 组合后: {len(combined)} 个")-- print("\n" + "=" * 70)- print("✨ 所有 Pythonic 操作演示完成!")- print("=" * 70)-- # 总结- print("\n📝 主要特性总结:")- print(" ✓ 索引访问: tasks[0], tasks[-1]")- print(" ✓ 切片: tasks[1:3], tasks[:2]")- print(" ✓ 迭代: for task in tasks")- print(" ✓ 成员测试: task in tasks")- print(" ✓ 修改方法: append, extend, insert, remove, pop")- print(" ✓ 查询方法: index, count")- print(" ✓ 工具方法: copy, reverse, sort")- print(" ✓ 自动 schema 验证")- print(" ✓ 语义搜索能力 (继承自基类)")---if __name__ == "__main__":- main()diff --git a/hyperextract/hypergraphs/__init__.py b/hyperextract/hypergraphs/__init__.pyindex e69de29..4a575e4 100644--- a/hyperextract/hypergraphs/__init__.py+++ b/hyperextract/hypergraphs/__init__.py@@ -0,0 +1,5 @@+from .base import AutoHypergraph++__all__ = [+ "AutoHypergraph",+]diff --git a/hyperextract/hypergraphs/base.py b/hyperextract/hypergraphs/base.pyindex 90f321e..291a8cd 100644--- a/hyperextract/hypergraphs/base.py+++ b/hyperextract/hypergraphs/base.py@@ -58,7 +58,9 @@ class EdgeListSchema(BaseModel, Generic[Edge]):)-class AutoHypergraph(BaseAutoType[AutoHypergraphSchema[Node, Edge]], Generic[Node, Edge]):+class AutoHypergraph(+ BaseAutoType[AutoHypergraphSchema[Node, Edge]], Generic[Node, Edge]+):"""AutoHypergraph - extracts complex relationships involving multiple entities.Suitable for:@@ -168,7 +170,7 @@ class AutoHypergraph(BaseAutoType[AutoHypergraphSchema[Node, Edge]], Generic[Nodself.graph_schema = create_model(graph_schema_name,nodes=(List[node_schema], Field(default_factory=list)),- hyperedges=(List[edge_schema], Field(default_factory=list)),+ edges=(List[edge_schema], Field(default_factory=list)),)# Helper Schemas for Batch Extraction@@ -229,7 +231,7 @@ class AutoHypergraph(BaseAutoType[AutoHypergraphSchema[Node, Edge]], Generic[Noddata_schema=self.graph_schema,llm_client=llm_client,embedder=embedder,- prompt=prompt or self._default_edge_prompt(),+ prompt=prompt or self._default_prompt(),chunk_size=chunk_size,chunk_overlap=chunk_overlap,max_workers=max_workers,@@ -238,8 +240,34 @@ class AutoHypergraph(BaseAutoType[AutoHypergraphSchema[Node, Edge]], Generic[Nod# ==================== Prompts ====================+ def _default_prompt(self) -> str:+ """Returns the default prompt for one-stage hypergraph extraction.++ This is the primary prompt used when extraction_mode is 'one_stage'.+ """+ return self._default_hypergraph_prompt++ @property+ def _default_hypergraph_prompt(self) -> str:+ """Default prompt for one-stage hypergraph extraction (nodes + edges together).++ Emphasizes comprehensive extraction of both entities and multi-entity relationships.+ For two-stage extraction, individual node and edge prompts are used instead.+ """+ return (+ "You are an expert hypergraph knowledge extraction assistant. "+ "Extract all entities (nodes) and their complex relationships (hyperedges) from the following text.\n\n"+ "CRITICAL RULES:\n"+ "1. Extract comprehensive Nodes (entities).\n"+ "2. Extract Hyperedges that connect multiple (2 or more) nodes simultaneously.\n"+ "3. STRUCTURAL CONSISTENCY: Every participant in a hyperedge MUST be present in the extracted Nodes list.\n"+ "4. Do not create hyperedges involving entities that are not in the Nodes list.\n"+ "5. A Hyperedge represents a Grouping, Event, or Complex Relation involving the listed participants.\n\n"+ "### Source Text:\n"+ )+def _default_node_prompt(self) -> str:- """Default prompt for node extraction."""+ """Default prompt for node extraction in two-stage mode."""return ("Extract all distinct entities from the text. ""Entities will serve as participants in complex events later.\n\n"@@ -247,7 +275,7 @@ class AutoHypergraph(BaseAutoType[AutoHypergraphSchema[Node, Edge]], Generic[Nod)def _default_edge_prompt(self) -> str:- """Default prompt for hyperedge extraction (multi-entity relationships)."""+ """Default prompt for hyperedge extraction in two-stage mode."""return ("You are an expert hypergraph extraction assistant. ""Extract complex relationships (hyperedges) that involve MULTIPLE entities simultaneously.\n\n"@@ -258,6 +286,34 @@ class AutoHypergraph(BaseAutoType[AutoHypergraphSchema[Node, Edge]], Generic[Nod"4. If an entity is not in the list, exclude it from the hyperedge.\n\n")+ def _create_empty_instance(self) -> "AutoHypergraph[Node, Edge]":+ """Creates a new empty AutoHypergraph instance with the same configuration.++ Overrides parent method to handle AutoHypergraph-specific parameters.++ Returns:+ A new empty AutoHypergraph instance with identical configuration.+ """+ return self.__class__(+ node_schema=self.node_schema,+ edge_schema=self.edge_schema,+ node_key_extractor=self.node_key_extractor,+ edge_key_extractor=self.edge_key_extractor,+ nodes_in_edge_extractor=self.nodes_in_edge_extractor,+ llm_client=self.llm_client,+ embedder=self.embedder,+ extraction_mode=self.extraction_mode,+ node_strategy_or_merger=self.node_merger,+ edge_strategy_or_merger=self.edge_merger,+ prompt=self.prompt,+ prompt_for_node_extraction=self.node_prompt,+ prompt_for_edge_extraction=self.edge_prompt,+ chunk_size=self.chunk_size,+ chunk_overlap=self.chunk_overlap,+ max_workers=self.max_workers,+ show_progress=self.show_progress,+ )+# ==================== State Management Lifecycle Hooks ====================def _init_data_state(self) -> None:@@ -321,7 +377,9 @@ class AutoHypergraph(BaseAutoType[AutoHypergraphSchema[Node, Edge]], Generic[Nodif self.extraction_mode == "two_stage":raw_graph = self._extract_data_by_two_stage(text)elif self.extraction_mode == "one_stage":- raise NotImplementedError("Single-stage extraction not yet supported for AutoHypergraph.")+ raise NotImplementedError(+ "Single-stage extraction not yet supported for AutoHypergraph."+ )else:raise ValueError(f"Invalid extraction_mode: {self.extraction_mode}")@@ -397,7 +455,9 @@ class AutoHypergraph(BaseAutoType[AutoHypergraphSchema[Node, Edge]], Generic[Nodreturn llm_chain.batch(inputs, config={"max_concurrency": self.max_workers})- def _prune_dangling_edges(self, graph: AutoHypergraphSchema) -> AutoHypergraphSchema:+ def _prune_dangling_edges(+ self, graph: AutoHypergraphSchema+ ) -> AutoHypergraphSchema:"""Prune hyperedges where ANY participating node does not exist (Strict Consistency).Args:@@ -408,7 +468,7 @@ class AutoHypergraph(BaseAutoType[AutoHypergraphSchema[Node, Edge]], Generic[Nod"""valid_nodes = graph.nodesvalid_node_keys = {self.node_key_extractor(n) for n in valid_nodes}-+# Also check long-term memoryif self._node_memory:valid_node_keys.update(self._node_memory.keys)@@ -447,7 +507,8 @@ class AutoHypergraph(BaseAutoType[AutoHypergraphSchema[Node, Edge]], Generic[Noddef merge_batch_data(self,- data_list_or_tuple: List[AutoHypergraphSchema] | Tuple[List[List[Node]], List[List[Edge]]],+ data_list_or_tuple: List[AutoHypergraphSchema]+ | Tuple[List[List[Node]], List[List[Edge]]],) -> AutoHypergraphSchema:"""Merge multiple hypergraphs or node/edge tuples into one.@@ -477,6 +538,12 @@ class AutoHypergraph(BaseAutoType[AutoHypergraphSchema[Node, Edge]], Generic[Nod"Invalid input format for batch merging")nodes_lists, edges_lists = data_list_or_tuple[0], data_list_or_tuple[1]+ assert isinstance(nodes_lists[0][0], self.node_schema), (+ "Invalid node list format for batch merging"+ )+ assert isinstance(edges_lists[0][0], self.edge_schema), (+ "Invalid edge list format for batch merging"+ )all_nodes, all_edges = [], []for node_list, edge_list in zip(nodes_lists, edges_lists):