Skip to content

Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.

feat: 更新示例代码,调整 LLM 模型为 gpt-4o-mini,并优化超图提取的默认提示

yifanfeng97dccdd9601a1f
diff --git a/examples/auto_hypergraph_demo.py b/examples/auto_hypergraph_demo.py
index b7c499c..4fc98b1 100644
--- a/examples/auto_hypergraph_demo.py
+++ b/examples/auto_hypergraph_demo.py
@@ -38,7 +38,8 @@ class StoryEntity(BaseModel):
description="实体类别: Character(人物), Location(地点), Item(物品), Faction(派系)",
)
description: str = Field(
- default="", description="实体的详细描述,如 '黑蛇'(Character) 的角色是 Which Snake"
+ default="",
+ description="实体的详细描述,如 '黑蛇'(Character) 的角色是 Which Snake",
)
@@ -124,7 +125,7 @@ def main():
"""主函数:完整的 AutoHypergraph 提取与分析流程"""
# 初始化 LLM 和嵌入模型
- llm = ChatOpenAI(model="gpt-4o", temperature=0)
+ llm_client = ChatOpenAI(model="gpt-4o-mini", temperature=0)
embedder = OpenAIEmbeddings()
# 1. 节点指纹:用名字即可
@@ -151,7 +152,7 @@ def main():
node_key_extractor=node_key_fn,
edge_key_extractor=edge_key_fn,
nodes_in_edge_extractor=participants_fn,
- llm_client=llm,
+ llm_client=llm_client,
embedder=embedder,
extraction_mode="two_stage", # 推荐:先识别实体,再梳理故事线
verbose=True,
diff --git a/examples/auto_set_demo.py b/examples/auto_set_demo.py
index 4d4713e..211e010 100644
--- a/examples/auto_set_demo.py
+++ b/examples/auto_set_demo.py
@@ -222,7 +222,7 @@ def main():
print("[*] 保存怪物图鉴")
print("=" * 80)
- save_path = "temp/monster_codex"
+ save_path = project_root / "temp" / "auto_set_demo"
monster_codex.dump(save_path)
print(f"√ 已保存到:{save_path}")
print(" - state.json(结构化数据)")
diff --git a/examples/kg_gen_demo.py b/examples/kg_gen_demo.py
index e1b9a7b..fe297f1 100644
--- a/examples/kg_gen_demo.py
+++ b/examples/kg_gen_demo.py
@@ -66,7 +66,7 @@ def main():
# 1. 初始化
print("📦 初始化组件...")
- llm = ChatOpenAI(model="gpt-4o", temperature=0)
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
embedder = OpenAIEmbeddings()
print("🚀 创建 KGGenGraph 实例...")
diff --git a/hyperextract/graphs/kg_gen.py b/hyperextract/graphs/kg_gen.py
index c456c6c..296eff2 100644
--- a/hyperextract/graphs/kg_gen.py
+++ b/hyperextract/graphs/kg_gen.py
@@ -96,11 +96,11 @@ class KG_Gen(AutoGraph[NodeSchema, EdgeSchema]):
- Two-stage extraction: entities first, then relationships
Example:
- >>> llm = ChatOpenAI(model="gpt-4o", temperature=0)
+ >>> llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
>>> embedder = OpenAIEmbeddings()
>>> kg = KG_Gen(llm_client=llm, embedder=embedder)
>>> kg.feed_text(text)
- >>> triplets = kg.export_triplets()
+ >>> print(f"Extracted {len(kg.nodes)} entities and {len(kg.edges)} relationships.")
"""
def __init__(
diff --git a/hyperextract/hypergraphs/base.py b/hyperextract/hypergraphs/base.py
index eb4ea99..d733b52 100644
--- a/hyperextract/hypergraphs/base.py
+++ b/hyperextract/hypergraphs/base.py
@@ -31,6 +31,41 @@ Node = TypeVar("Node", bound=BaseModel)
Edge = TypeVar("Edge", bound=BaseModel) # Represents a Hyperedge
+# ============================================================================
+# Default Extraction Prompts
+# ============================================================================
+
+DEFAULT_HYPERGRAPH_PROMPT = """You are an expert hypergraph knowledge extraction assistant.
+Extract all entities (nodes) and their complex relationships (hyperedges) from the following text.
+
+CRITICAL RULES:
+1. Extract comprehensive Nodes (entities).
+2. Extract Hyperedges that connect multiple (2 or more) nodes simultaneously.
+3. STRUCTURAL CONSISTENCY: Every participant in a hyperedge MUST be present in the extracted Nodes list.
+4. Do not create hyperedges involving entities that are not in the Nodes list.
+5. A Hyperedge represents a Grouping, Event, or Complex Relation involving the listed participants.
+
+### Source Text:
+"""
+
+DEFAULT_NODE_PROMPT = """Extract all distinct entities from the text.
+Entities will serve as participants in complex events later.
+
+### Source Text:
+"""
+
+DEFAULT_EDGE_PROMPT = """You are an expert hypergraph extraction assistant.
+Extract complex relationships (hyperedges) that involve MULTIPLE entities simultaneously.
+
+CRITICAL RULES:
+1. A hyperedge can connect 2, 3, or more entities (e.g., a meeting with multiple people).
+2. Identify ALL participants for each relationship.
+3. ONLY use entities from the provided 'Known Entities' list.
+4. If an entity is not in the list, exclude it from the hyperedge.
+
+"""
+
+
class AutoHypergraphSchema(BaseModel, Generic[Node, Edge]):
"""Generic schema container for hypergraph data."""
@@ -175,8 +210,8 @@ class AutoHypergraph(
self.verbose = verbose
# Initialize prompts
- self.node_prompt = prompt_for_node_extraction or self._default_node_prompt()
- self.edge_prompt = prompt_for_edge_extraction or self._default_edge_prompt()
+ self.node_prompt = prompt_for_node_extraction or DEFAULT_NODE_PROMPT
+ self.edge_prompt = prompt_for_edge_extraction or DEFAULT_EDGE_PROMPT
# Create dynamic HypergraphSchema
graph_schema_name = f"{node_schema.__name__}{edge_schema.__name__}Hypergraph"
@@ -246,7 +281,7 @@ class AutoHypergraph(
data_schema=self.graph_schema,
llm_client=llm_client,
embedder=embedder,
- prompt=prompt or self._default_prompt(),
+ prompt=prompt or DEFAULT_HYPERGRAPH_PROMPT,
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
max_workers=max_workers,
@@ -257,52 +292,14 @@ class AutoHypergraph(
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()
- 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.
+ This is the primary prompt used when extraction_mode is 'one_stage'.
"""
- 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 in two-stage mode."""
- return (
- "Extract all distinct entities from the text. "
- "Entities will serve as participants in complex events later.\n\n"
- "### Source Text:\n"
- )
-
- def _default_edge_prompt(self) -> str:
- """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"
- "CRITICAL RULES:\n"
- "1. A hyperedge can connect 2, 3, or more entities (e.g., a meeting with multiple people).\n"
- "2. Identify ALL participants for each relationship.\n"
- "3. ONLY use entities from the provided 'Known Entities' list.\n"
- "4. If an entity is not in the list, exclude it from the hyperedge.\n\n"
- )
+ return DEFAULT_HYPERGRAPH_PROMPT
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: