Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.
feat: 统一模板中的源文本变量为{source_text}并添加known_nodes支持
yifanfeng978c5720f6fdf4
diff --git a/examples/auto_graph_demo.py b/examples/auto_graph_demo.pyindex e73ae31..b029112 100644--- a/examples/auto_graph_demo.py+++ b/examples/auto_graph_demo.py@@ -296,12 +296,18 @@ def run_demo():prompt_for_node_extraction=("提取文本中的所有游戏实体作为节点。关键:必须提取BOSS(如深渊魔龙)、公会(如星辰阁)以及关键玩家。""如果文中提到'全团'或'所有人',也将其作为一个群体实体提取。"- "注意识别ID和别名,将别名(如'团长')标准化为具体ID。"+ "注意识别ID和别名,将别名(如'团长')标准化为具体ID。\n\n"+ "## 源文本:\n"+ "{source_text}"),prompt_for_edge_extraction=("提取实体之间的互动行为。""重要规则:互动中的 source 和 target 必须是你刚才提取过的实体名称。""例如,如果之前提取了节点'深渊魔龙',那么攻击BOSS的互动 target 必须填'深渊魔龙'。"+ "### 已知的实体列表\n"+ "{known_nodes}\n\n"+ "## 源文本:\n"+ "{source_text}\n\n"),verbose=True,)diff --git a/examples/auto_hypergraph_demo.py b/examples/auto_hypergraph_demo.pyindex 42a444d..25653a6 100644--- a/examples/auto_hypergraph_demo.py+++ b/examples/auto_hypergraph_demo.py@@ -159,7 +159,9 @@ def main():"- Location(地点):故事发生的地方\n""- Item(物品):故事中提到的重要物品或武器\n""- Faction(派系):故事中的组织或势力\n\n"- "请确保提取所有重要的实体,并正确分类它们的类别。"+ "请确保提取所有重要的实体,并正确分类它们的类别。\n\n"+ "## 源文本:\n"+ "{source_text}"),prompt_for_edge_extraction=("你的任务是从故事文本中提取复杂的叙事关系,将其建模为超边。\n"@@ -174,7 +176,11 @@ def main():"1. summary:对这个叙事单元的简洁描述\n""2. edge_type:上述分类之一\n""3. participants:所有牵涉其中的实体名称列表\n\n"- "确保 participants 列表包含故事中与该事件相关的所有实体。"+ "确保 participants 列表包含故事中与该事件相关的所有实体。\n"+ "### 已知的实体列表\n"+ "{known_nodes}\n\n"+ "## 源文本:\n"+ "{source_text}\n\n"),chunk_size=1000,)diff --git a/examples/auto_set_demo.py b/examples/auto_set_demo.pyindex 9fe65a3..40a2a8d 100644--- a/examples/auto_set_demo.py+++ b/examples/auto_set_demo.py@@ -75,7 +75,10 @@ def main():- weaknesses: 已知的弱点和克制方法- loot_drops: 击败后可能掉落的物品-要尽可能准确和详细,包括所有提到的怪物和它们的属性。如果信息不完整,请基于已有信息做出合理推断。""",+要尽可能准确和详细,包括所有提到的怪物和它们的属性。如果信息不完整,请基于已有信息做出合理推断。++### 冒险者日志:+{source_text}""",verbose=True,)diff --git a/examples/auto_spatial_graph_demo.py b/examples/auto_spatial_graph_demo.pyindex 74585e8..303ac0d 100644--- a/examples/auto_spatial_graph_demo.py+++ b/examples/auto_spatial_graph_demo.py@@ -169,13 +169,19 @@ def run_demo():edge_strategy_or_merger=MergeStrategy.LLM.BALANCED,prompt_for_node_extraction=("提取深海空间站中的所有关键实体(船员、设备、怪物等)。\n"- "注意:不要在节点中提取位置信息,位置将作为关系属性提取。"+ "注意:不要在节点中提取位置信息,位置将作为关系属性提取。\n\n"+ "## 源文本:\n"+ "{source_text}"),prompt_for_edge_extraction=("提取实体之间的互动关系,并精确捕获它们发生的地理位置。\n""特别是:\n""- 解析相对位置(如'这里'解析为 observation_location)\n""- 注意 3D 空间层级(上层甲板、中央枢纽、反应堆舱)"+ "### 已知的实体列表\n"+ "{known_nodes}\n\n"+ "## 源文本:\n"+ "{source_text}\n\n"),verbose=True,chunk_size=2048,diff --git a/examples/auto_spatio_temporal_graph_demo.py b/examples/auto_spatio_temporal_graph_demo.pyindex d620a8f..c425f75 100644--- a/examples/auto_spatio_temporal_graph_demo.py+++ b/examples/auto_spatio_temporal_graph_demo.py@@ -116,6 +116,10 @@ def run_demo():"特别是:\n""- 如果提到'这里',指 Brandenburg Gate\n""- 提取具体的车站名、建筑物名或房间号"+ "### 已知的实体列表\n"+ "{known_nodes}\n\n"+ "## 源文本:\n"+ "{source_text}\n\n"),verbose=True)diff --git a/examples/auto_temporal_graph_demo.py b/examples/auto_temporal_graph_demo.pyindex 8a17749..af73551 100644--- a/examples/auto_temporal_graph_demo.py+++ b/examples/auto_temporal_graph_demo.py@@ -158,7 +158,9 @@ def run_demo():"1. 提取所有人名(Elias、Viktor、Bond、Katya、Sarah等)及其别称或代称\n""2. 提取所有地点(柏林、Black Swan酒吧、Charlottenburg Palace等)\n""3. 提取组织(CIA、KGB等)和物品(炸弹、枪、起爆器等)\n"- "4. 将代称和别名标准化为主要名称"+ "4. 将代称和别名标准化为主要名称\n\n"+ "## 源文本:\n"+ "{source_text}"),prompt_for_edge_extraction=("提取人物之间和与物品/地点之间的**时间感知的行动**。\n"@@ -169,6 +171,10 @@ def run_demo():"4. 提取精确到分钟级别(HH:MM格式),日期使用 YYYY-MM-DD\n""5. 在 description 字段中记录行动发生的地点或其他上下文信息\n""6. 如果时间不明确,填写空值而不是猜测"+ "### 已知的实体列表\n"+ "{known_nodes}\n\n"+ "## 源文本:\n"+ "{source_text}\n\n"),verbose=True,chunk_size=2048,diff --git a/examples/method_cog_rag_demo.py b/examples/method_cog_rag_demo.pyindex a3fac67..c473bbd 100644--- a/examples/method_cog_rag_demo.py+++ b/examples/method_cog_rag_demo.py@@ -121,7 +121,7 @@ if __name__ == "__main__":print("\n--- MACRO LAYER: Themes (Narrative Arcs) ---")for i, edge in enumerate(rag.theme_layer.edges, 1):print(f"\nTheme {i}: {edge.description}")- print(f" Participants: {', '.join(edge.participants)}")+ print(f" Participants: {', '.join([n.name for n in edge.participants])}")print(f"\n✓ Total Themes extracted: {len(rag.theme_layer.edges)}")diff --git a/examples/hyper_rag_demo.py b/examples/method_hyper_rag_demo.pysimilarity index 100%rename from examples/hyper_rag_demo.pyrename to examples/method_hyper_rag_demo.pydiff --git a/examples/hypergraph_rag_demo.py b/examples/method_hypergraph_rag_demo.pysimilarity index 97%rename from examples/hypergraph_rag_demo.pyrename to examples/method_hypergraph_rag_demo.pyindex dbb45b1..17a9a92 100644--- a/examples/hypergraph_rag_demo.py+++ b/examples/method_hypergraph_rag_demo.py@@ -116,13 +116,13 @@ if __name__ == "__main__":print(f"\n--- Low-Order Edges (Pairwise) ---")for i, edge in enumerate(low_order_edges, 1):- print(f"\n{i}. Participants: {' <-> '.join(edge.related_entities)}")+ print(f"\n{i}. Participants: {' <-> '.join(e.name for e in edge.related_entities)}")print(f" Knowledge Segment: {edge.knowledge_segment}")print(f" Completeness Score: {edge.completeness_score}/10")print(f"\n--- High-Order Edges (Hyperedges) ---")for i, edge in enumerate(high_order_edges, 1):- print(f"\n{i}. Participants: {' <-> '.join(edge.related_entities)}")+ print(f"\n{i}. Participants: {' <-> '.join(e.name for e in edge.related_entities)}")print(f" Knowledge Segment: {edge.knowledge_segment}")print(f" Completeness Score: {edge.completeness_score}/10")@@ -167,7 +167,7 @@ if __name__ == "__main__":centrality = {}for edge in rag.edges:for participant in edge.related_entities:- centrality[participant] = centrality.get(participant, 0) + 1+ centrality[participant.name] = centrality.get(participant.name, 0) + 1for entity, count in sorted(centrality.items(), key=lambda x: x[1], reverse=True)[:10diff --git a/examples/itext2kg_demo.py b/examples/method_itext2kg_demo.pysimilarity index 100%rename from examples/itext2kg_demo.pyrename to examples/method_itext2kg_demo.pydiff --git a/examples/itext2kg_star_demo.py b/examples/method_itext2kg_star_demo.pysimilarity index 100%rename from examples/itext2kg_star_demo.pyrename to examples/method_itext2kg_star_demo.pydiff --git a/examples/kg_gen_demo.py b/examples/method_kg_gen_demo.pysimilarity index 100%rename from examples/kg_gen_demo.pyrename to examples/method_kg_gen_demo.pydiff --git a/examples/light_rag_demo.py b/examples/method_light_rag_demo.pysimilarity index 100%rename from examples/light_rag_demo.pyrename to examples/method_light_rag_demo.pydiff --git a/hyperextract/methods/rag/cog_rag.py b/hyperextract/methods/rag/cog_rag.pyindex 3a81272..ab4e16e 100644--- a/hyperextract/methods/rag/cog_rag.py+++ b/hyperextract/methods/rag/cog_rag.py@@ -38,30 +38,14 @@ class NodeSchema(BaseModel):class ThemeSchema(BaseModel):"""Represents a Theme or Narrative Arc connecting multiple entities (Hyperedge)."""- participants: List[str] = Field(- description="Names of key entities involved in this theme"- )- description: str = Field(- description="A sentence that describes the primary theme, reflecting the main conflict, resolution, or key message"- )---class TEMP_ThemeSchema(BaseModel):- """Temporary schema for extracting Themes with nested Entities."""-- description: str = Field(- description="A sentence that describes the primary theme, reflecting the main conflict, resolution, or key message"- )+ # participants: List[str] = Field(+ # description="Names of key entities involved in this theme"+ # )participants: List[NodeSchema] = Field(description="List of key entities involved in this theme, with their details.")---class TEMP_ThemeListSchema(BaseModel):- """List of extracted themes."""-- items: List[TEMP_ThemeSchema] = Field(- description="List of extracted themes and their participants."+ description: str = Field(+ description="A sentence that describes the primary theme, reflecting the main conflict, resolution, or key message")@@ -104,6 +88,9 @@ For each Theme, you must also identify the key **Participants** (Entities) invol1. Analyze the text to identify primary themes/events.2. For each theme, identify the entities involved.3. Output the Theme description and the list of Participant Entities.++### Source Text:+{source_text}"""COG_RAG_NODE_EXTRACTION_PROMPT = """@@ -112,6 +99,7 @@ Identify relevant entities from the text.Entities will serve as participants in complex events later.### Source Text:+{source_text}"""COG_RAG_EDGE_EXTRACTION_PROMPT = """@@ -129,6 +117,11 @@ It treats all involved entities as **participants** in a shared context2. Do NOT create edges for entities that represent strictly different concepts with no interaction.3. Ensure every edge has at least 2 participants.+# Provided Entities+{known_nodes}++### Source Text:+{source_text}"""# ============================================================================@@ -196,7 +189,7 @@ class Cog_RAG_ThemeLayer(AutoHypergraph[NodeSchema, ThemeSchema]):edge_key_fn = lambda x: md5(x.description.encode()).hexdigest()# Nodes in theme- nodes_in_edge_fn = lambda x: x.participants+ nodes_in_edge_fn = lambda x: [n.name for n in x.participants]# 2. Create custom Mergersnode_merger = CustomRuleMerger(@@ -240,20 +233,13 @@ class Cog_RAG_ThemeLayer(AutoHypergraph[NodeSchema, ThemeSchema]):Extract Themes and nested Participants (One-Stage).Implements the HyperGraph_RAG extraction pattern."""- prompt_template = ChatPromptTemplate.from_template(- f"{self.edge_prompt}\n\n### Source Text:\n{{chunk_text}}"- )- llm_chain = prompt_template | self.llm_client.with_structured_output(- TEMP_ThemeListSchema- )-# Batch Processingif len(text) <= self.chunk_size:- raw_results_list = [llm_chain.invoke({"chunk_text": text})]+ raw_results_list = [self.edge_extractor.invoke({"source_text": text})]else:chunks = self.text_splitter.split_text(text)- inputs = [{"chunk_text": chunk} for chunk in chunks]- raw_results_list = llm_chain.batch(+ inputs = [{"source_text": chunk} for chunk in chunks]+ raw_results_list = self.edge_extractor.batch(inputs, config={"max_concurrency": self.max_workers})@@ -269,18 +255,11 @@ class Cog_RAG_ThemeLayer(AutoHypergraph[NodeSchema, ThemeSchema]):cur_edges = []for item in result.items:- item: TEMP_ThemeSchema+ item: ThemeSchemaextracted_nodes = item.participantscur_nodes.extend(extracted_nodes)- cur_edges.append(- ThemeSchema(- description=item.description,- participants=[- self.node_key_extractor(n) for n in extracted_nodes- ],- )- )+ cur_edges.append(item)all_nodes_list.append(cur_nodes)all_edges_list.append(cur_edges)@@ -436,7 +415,7 @@ class Cog_RAG:context_parts.append("=== MACRO THEMES (Narrative Context) ===")for t in results["themes"]:context_parts.append(- f"- {t.description} (Involved: {', '.join(t.participants)})"+ f"- {t.description} (Involved: {', '.join([n.name for n in t.participants])})")if results["entities"]:diff --git a/hyperextract/methods/rag/hyper_rag.py b/hyperextract/methods/rag/hyper_rag.pyindex 8075d58..92e9839 100644--- a/hyperextract/methods/rag/hyper_rag.py+++ b/hyperextract/methods/rag/hyper_rag.py@@ -58,8 +58,10 @@ class EdgeSchema(BaseModel):Hyper_RAG_NODE_EXTRACTION_PROMPT = """-Goal-Identify relevant entities from the text.-Entities will serve as participants in complex events later.\n\n+Entities will serve as participants in complex events later.+### Source Text:+{source_text}"""Hyper_RAG_EDGE_EXTRACTION_PROMPT = """@@ -77,6 +79,11 @@ It treats all involved entities as **participants** in a shared context2. Do NOT create edges for entities that represent strictly different concepts with no interaction.3. Ensure every edge has at least 2 participants.+# Provided Entities+{known_nodes}++### Source Text:+{source_text}"""# ============================================================================diff --git a/hyperextract/methods/rag/hypergraph_rag.py b/hyperextract/methods/rag/hypergraph_rag.pyindex 800d4a4..ebe14da 100644--- a/hyperextract/methods/rag/hypergraph_rag.py+++ b/hyperextract/methods/rag/hypergraph_rag.py@@ -15,7 +15,6 @@ from hashlib import md5from pydantic import BaseModel, Fieldfrom langchain_core.embeddings import Embeddingsfrom langchain_core.language_models import BaseChatModel-from langchain_core.prompts.chat import ChatPromptTemplatefrom ontomem.merger import MergeStrategyfrom hyperextract.types.hypergraph import AutoHypergraph, AutoHypergraphSchema@@ -56,34 +55,14 @@ class EdgeSchema(BaseModel):completeness_score: int = Field(description="A score from 0 to 10 indicating how complete and meaningful this knowledge segment is on its own.")- related_entities: List[str] = Field(- description="A list of all entity names involved in or referenced by this knowledge segment."- )---# Below Schema is used for Information Extraction with LLM-class TEMP_EdgeSchema(BaseModel):- """Represents a knowledge segment (hyper-edge) that connects multiple entities through a specific context or event."""-- knowledge_segment: str = Field(- description="A complete sentence or phrase from the text that captures a specific relationship, event, or context connecting the entities."- )- completeness_score: int = Field(- description="A score from 0 to 10 indicating how complete and meaningful this knowledge segment is on its own."- )+ # related_entities: List[str] = Field(+ # description="A list of all entity names involved in or referenced by this knowledge segment."+ # )related_entities: List[NodeSchema] = Field(description="A list of all entities involved in or referenced by this knowledge segment.")-class TEMP_EdgeListSchema(BaseModel):- """Intermediate schema for batch hyperedge extraction."""-- items: List[TEMP_EdgeSchema] = Field(- description="List of extracted hyperedges with their knowledge segments and related entities."- )--# ============================================================================# Extraction Prompts# ============================================================================@@ -115,24 +94,24 @@ A **Hyper-edge** represents a specific "knowledge segment" (a sentence or event**Output**:[- {+ {{"knowledge_segment": "Alex clenched his jaw, the buzz of frustration dull against the backdrop of Taylor's authoritarian certainty.","completeness_score": 8,"related_entities": [- {+ {{"name": "Alex","type": "person","description": "Alex is a person displaying frustration by clenching his jaw.","key_score": 90- },- {+ }},+ {{"name": "Taylor","type": "person","description": "Taylor is a person exhibiting authoritarian certainty causing Alex's frustration.","key_score": 85- }+ }}]- }+ }}]## Example 2@@ -141,28 +120,28 @@ A **Hyper-edge** represents a specific "knowledge segment" (a sentence or event**Output**:[- {+ {{"knowledge_segment": "\"The device could change the game for us,\" Taylor said, observing the machine with reverence.","completeness_score": 9,"related_entities": [- {+ {{"name": "Taylor","type": "person","description": "Taylor is a person who believes the device is game-changing and observes it with reverence.","key_score": 95- },- {+ }},+ {{"name": "device","type": "object","description": "An object that Taylor believes could change the game.","key_score": 90- }+ }}]- }+ }}]-\n\n-### Source Text:+## Source Text:+{source_text}"""# ============================================================================@@ -225,7 +204,7 @@ class HyperGraph_RAG(AutoHypergraph[NodeSchema, EdgeSchema]):# 1. Define Key Extractorsnode_key_fn = lambda x: x.nameedge_key_fn = lambda x: md5(x.knowledge_segment.encode()).hexdigest()- nodes_in_edge_fn = lambda x: x.related_entities+ nodes_in_edge_fn = lambda x: [entity.name for entity in x.related_entities]# 4. Call parent class initializationsuper().__init__(@@ -269,22 +248,14 @@ class HyperGraph_RAG(AutoHypergraph[NodeSchema, EdgeSchema]):deduplicated and merged entities (nodes) and knowledge segments (hyperedges)."""# 1. Extract Hyperedges-- prompt_template = ChatPromptTemplate.from_template(- f"{self.prompt}{{chunk_text}}"- )- llm_chain = prompt_template | self.llm_client.with_structured_output(- TEMP_EdgeListSchema- )-# Extract from single chunk or multiple chunksif len(text) <= self.chunk_size:- raw_hyperedges = llm_chain.invoke({"chunk_text": text})+ raw_hyperedges = self.edge_extractor.invoke({"source_text": text})raw_hyperedges_list = [raw_hyperedges]else:chunks = self.text_splitter.split_text(text)- inputs = [{"chunk_text": chunk} for chunk in chunks]- raw_hyperedges_list = llm_chain.batch(+ inputs = [{"source_text": chunk} for chunk in chunks]+ raw_hyperedges_list = self.edge_extractor.batch(inputs, config={"max_concurrency": self.max_workers})@@ -295,18 +266,9 @@ class HyperGraph_RAG(AutoHypergraph[NodeSchema, EdgeSchema]):cur_nodes, cur_edges = [], []data_list = raw_hyperedges.itemsfor data in data_list:- data: TEMP_EdgeSchema+ data: EdgeSchemacur_nodes.extend(data.related_entities)- cur_edges.append(- EdgeSchema(- knowledge_segment=data.knowledge_segment,- completeness_score=data.completeness_score,- related_entities=[- self.node_key_extractor(node)- for node in data.related_entities- ],- )- )+ cur_edges.append(data)all_nodes_list.append(cur_nodes)all_edges_list.append(cur_edges)diff --git a/hyperextract/methods/rag/light_rag.py b/hyperextract/methods/rag/light_rag.pyindex b128e76..b33f2a4 100644--- a/hyperextract/methods/rag/light_rag.py+++ b/hyperextract/methods/rag/light_rag.py@@ -56,8 +56,10 @@ class EdgeSchema(BaseModel):Light_RAG_NODE_EXTRACTION_PROMPT = """-Goal-Identify relevant entities from the text.-Entities will serve as nodes in the knowledge graph.\n\n+Entities will serve as nodes in the knowledge graph.+### Source Text:+{source_text}"""Light_RAG_EDGE_EXTRACTION_PROMPT = """@@ -73,6 +75,11 @@ An Edge represents a specific connection (action, relation, ownership, etc.) fro2. Ensure every edge has exactly one Source and one Target.3. Provide a clear, comprehensive description for each edge.+# Provided Entities+{known_nodes}++### Source Text:+{source_text}"""# ============================================================================diff --git a/hyperextract/methods/typical/atom.py b/hyperextract/methods/typical/atom.pyindex 7f5b407..578fb1b 100644--- a/hyperextract/methods/typical/atom.py+++ b/hyperextract/methods/typical/atom.py@@ -161,14 +161,14 @@ Given an input paragraph and an `observation_time`, generate a list of all disti- Convert ALL time references to absolute dates/times using the observation_time#### Conversion Rules:-- "today" 鈫?exact observation_time-- "yesterday" 鈫?observation_time minus 1 day-- "this week" 鈫?Monday of observation_time's week-- "last week" 鈫?Monday of the week before observation_time-- "this month" 鈫?first day of observation_time's month-- "last month" 鈫?first day of the month before observation_time-- "this year" 鈫?January 1st of observation_time's year-- "last year" 鈫?January 1st of the year before observation_time+- "today" → exact observation_time+- "yesterday" → observation_time minus 1 day+- "this week" → Monday of observation_time's week+- "last week" → Monday of the week before observation_time+- "this month" → first day of observation_time's month+- "last month" → first day of the month before observation_time+- "this year" → January 1st of observation_time's year+- "last year" → January 1st of the year before observation_time- Keep explicit dates as-is (e.g., "June 18, 2024")#### Additional Temporal Guidelines:@@ -195,15 +195,19 @@ Given an input paragraph and an `observation_time`, generate a list of all disti- Real Madrid won the Champions League final on June 18, 2024- The Champions League final ended with a 2-1 victory for Real Madrid on June 18, 2024- Fans of Real Madrid celebrated the Champions League victory across the city on June 18, 2024++## Source Text:+{source_text}"""+# Atom FACToid prompt ends, edge prompt beginsAtom_EDGE_EXTRACTION_PROMPT = """Observation Date: {observation_time}You are a precise knowledge extraction engine designed to distill unstructured text into a structured Knowledge Graph.Your goal is to extract all meaningful relationships (edges) between entities, while rigorously capturing their temporal bounds and grounding evidence.-### 馃幆 Objective+### ObjectiveExtract a list of relationships where each relationship consists of:1. **Start Node**: The subject entity (Name + Label).2. **End Node**: The object entity (Name + Label).@@ -260,6 +264,12 @@ Extract a list of relationships where each relationship consists of:- Use the **Observation Date** as the anchor for all relative temporal expressions.- Maintain consistency: The same entity name should be used across multiple relations.- Ensure `atomic_facts` contains exact copies of the source text strings.++### Known Nodes:+{known_nodes}++### Source Text:+{source_text}"""@@ -418,7 +428,7 @@ class Atom(AutoGraph[NodeSchema, EdgeSchema]):# 2. Define Fact Extraction Chainfact_prompt_template = ChatPromptTemplate.from_template(- f"{Atom_FACTOID_EXTRACTION_PROMPT}\n\nObservation Date: {{observation_time}}\n\n### Source Text:\n{{chunk_text}}"+ Atom_FACTOID_EXTRACTION_PROMPT)fact_chain = fact_prompt_template | self.llm_client.with_structured_output(AtomicFactSchema@@ -426,7 +436,7 @@ class Atom(AutoGraph[NodeSchema, EdgeSchema]):# 3. Batch Extract Factsfact_inputs = [- {"chunk_text": chunk, "observation_time": obs_date_str}+ {"source_text": chunk, "observation_time": obs_date_str}for chunk in raw_chunks]chunk_fact_lists: List[AtomicFactSchema] = fact_chain.batch(@@ -453,51 +463,49 @@ class Atom(AutoGraph[NodeSchema, EdgeSchema]):fact_chunks = []current_batch = []current_char_count = 0-+# Estimate overhead: "[Fact 99]: " + newline is approx 12 charsPREFIX_OVERHEAD = 12for fact in all_facts:fact_len = len(fact) + PREFIX_OVERHEAD-+# Check constraints:# 1. Size limit (fuzzy check to keep under chunk_size)# 2. Count limit (facts_per_chunk)size_limit_reached = (current_char_count + fact_len) > self.chunk_sizecount_limit_reached = len(current_batch) >= self.facts_per_chunk-+if (size_limit_reached or count_limit_reached) and current_batch:# Flush current batchformatted_chunk = "\n".join(- [f"[Fact {i+1}]: {f}" for i, f in enumerate(current_batch)]+ [f"[Fact {i + 1}]: {f}" for i, f in enumerate(current_batch)])fact_chunks.append(formatted_chunk)-+# Resetcurrent_batch = []current_char_count = 0-+current_batch.append(fact)current_char_count += fact_len-+# Flush remaining itemsif current_batch:formatted_chunk = "\n".join(- [f"[Fact {i+1}]: {f}" for i, f in enumerate(current_batch)]+ [f"[Fact {i + 1}]: {f}" for i, f in enumerate(current_batch)])fact_chunks.append(formatted_chunk)# 6. Batch Extract Edges directly from Fact Chunks# Format the edge prompt with observation dateedge_prompt_with_date = self.edge_prompt.format(observation_time=obs_date_str)- edge_prompt_template = ChatPromptTemplate.from_template(- f"{edge_prompt_with_date}\n\n### Source Text:\n{{chunk_text}}"- )+ edge_prompt_template = ChatPromptTemplate.from_template(edge_prompt_with_date)edge_chain = edge_prompt_template | self.llm_client.with_structured_output(self.edge_list_schema)- edge_inputs = [{"chunk_text": chunk} for chunk in fact_chunks]+ edge_inputs = [{"source_text": chunk} for chunk in fact_chunks]chunk_edge_lists = edge_chain.batch(edge_inputs, config={"max_concurrency": self.max_workers})@@ -611,4 +619,3 @@ class Atom(AutoGraph[NodeSchema, EdgeSchema]):f"鉁?Node matching complete: Nodes {len(nodes)} -> {len(self.nodes)}, Edges: {len(edges)}")return self-diff --git a/hyperextract/methods/typical/graphiti.py b/hyperextract/methods/typical/graphiti.pydeleted file mode 100644index 74e128c..0000000--- a/hyperextract/methods/typical/graphiti.py+++ /dev/null@@ -1,2 +0,0 @@-# graphiti.py - Reserved for Graphiti implementation-diff --git a/hyperextract/methods/typical/itext2kg.py b/hyperextract/methods/typical/itext2kg.pyindex 808e500..0c43653 100644--- a/hyperextract/methods/typical/itext2kg.py+++ b/hyperextract/methods/typical/itext2kg.py@@ -77,6 +77,7 @@ and possibly a Relationship('Haira' -> 'plans' -> 'Escape')."- Act like an experienced knowledge graph builder.### Source Text:+{source_text}"""iText2KG_EDGE_EXTRACTION_PROMPT = """@@ -89,6 +90,12 @@ The predicates should be chosen with precision to accurately reflect the express- Do not change the name or label of the provided entities list.- Do not add any entity outside the provided list.- Avoid reflexive relations.++# Provided Entities+{known_nodes}++### Source Text:+{source_text}"""diff --git a/hyperextract/methods/typical/itext2kg_star.py b/hyperextract/methods/typical/itext2kg_star.pyindex 71f1bc0..4d7937a 100644--- a/hyperextract/methods/typical/itext2kg_star.py+++ b/hyperextract/methods/typical/itext2kg_star.py@@ -95,6 +95,9 @@ iText2KG_Star_EDGE_EXTRACTION_PROMPT = """- Avoid reflexive relations (entity relating to itself).- IMPORTANT: Set 'observation_date' to null in all cases. Do NOT extract or infer dates from the context.- The observation_date field should be populated by the user manually after extraction.++### Source Text:+{source_text}"""@@ -214,15 +217,8 @@ class iText2KG_Star(AutoGraph[NodeSchema, EdgeSchema]):chunks = self.text_splitter.split_text(text)# 2. Batch Extract Edges directly- prompt_template = ChatPromptTemplate.from_template(- f"{self.edge_prompt}\n\n### Source Text:\n{{chunk_text}}"- )- llm_chain = prompt_template | self.llm_client.with_structured_output(- self.edge_list_schema- )-- inputs = [{"chunk_text": chunk} for chunk in chunks]- chunk_edge_lists = llm_chain.batch(+ inputs = [{"source_text": chunk} for chunk in chunks]+ chunk_edge_lists = self.edge_extractor.batch(inputs, config={"max_concurrency": self.max_workers})diff --git a/hyperextract/methods/typical/kg_gen.py b/hyperextract/methods/typical/kg_gen.pyindex 56da4b1..f5f1d21 100644--- a/hyperextract/methods/typical/kg_gen.py+++ b/hyperextract/methods/typical/kg_gen.py@@ -58,6 +58,7 @@ Requirements:- Each entity should be a single name or brief identifier### Source Text:+{source_text}"""KG_Gen_EDGE_EXTRACTION_PROMPT = """@@ -70,7 +71,11 @@ CRITICAL RULES:4. Each triple must be faithful to the source text5. Be thorough - extract all relationships mentioned+# Provided Entities+{known_nodes}+### Source Text:+{source_text}"""diff --git a/hyperextract/templates/en/INSTRUCTION.md b/hyperextract/templates/en/INSTRUCTION.mdindex e0cee29..a287379 100644--- a/hyperextract/templates/en/INSTRUCTION.md+++ b/hyperextract/templates/en/INSTRUCTION.md@@ -207,9 +207,43 @@ Different domains have specialized terminology or specific expressions. You may- Finance: Professional terminology should remain in original form- Medical: Professional abbreviations should remain in original form+### Special Placeholders (Required)+**Each Prompt must include special placeholders** to receive the text to be extracted:++- **_PROMPT / _NODE_PROMPT**: Must include `{source_text}` placeholder+ ```python+ ## Source Text:+ {source_text}+ ```++- **_EDGE_PROMPT**: Taking AutoGraph/AutoHypergraph as examples, must include `{known_nodes}` and `{source_text}` placeholders. For spatio-temporal graph types, additional `{observation_time}` or `{observation_location}` placeholders will be included (see table below for details).+ ```python+ ## Known Entities+ {known_nodes}++ ## Source Text:+ {source_text}+ ```++#### Placeholders by AutoType++| AutoType | Node Extraction | Edge Extraction |+|----------|-----------------|-----------------|+| `AutoModel` / `AutoList` / `AutoSet` | `{source_text}` | - |+| `AutoGraph` / `AutoHypergraph` | `{source_text}` | `{source_text}`, `{known_nodes}` |+| `AutoTemporalGraph` | `{source_text}` | `{source_text}`, `{known_nodes}`, `{observation_time}` |+| `AutoSpatialGraph` | `{source_text}` | `{source_text}`, `{known_nodes}`, `{observation_location}` |+| `AutoSpatioTemporalGraph` | `{source_text}` | `{source_text}`, `{known_nodes}`, `{observation_time}`, `{observation_location}` |++#### Placeholder Description++- **`{source_text}`**: The original text to be analyzed (required)+- **`{known_nodes}`**: Known nodes list in two-stage extraction mode (for edge extraction)+- **`{observation_time}`**: Observation time, used to resolve relative time expressions (e.g., "last year", "last month")+- **`{observation_location}`**: Observation location, used to resolve relative location expressions (e.g., "here", "nearby")+### Spatio-Temporal Resolution Rules (required for spatio-temporal graph types only)- Time/location resolution rules...-```**Why concept definitions are needed?**- Let the LLM understand "what" to extract first, before telling it "how" to extract@@ -223,47 +257,27 @@ Different domains have specialized terminology or specific expressions. You may### 4.4 Core Concept Definition Templates for Each AutoType-#### AutoModel-```-## Core Concept Definitions-- **Object**: A single structured object extracted from the text, containing multiple fields-```--#### AutoList-```-## Core Concept Definitions-- **Item**: Repeating pattern instances extracted from the text-```--#### AutoSet-```-## Core Concept Definitions-- **Element**: Knowledge units with unique keys, used for accumulating information-```-#### AutoGraph-```## Core Concept Definitions- **Node**: Entities extracted from the document- **Edge**: Relationships between nodes-```+#### AutoHypergraph-```+## Core Concept Definitions- **Node**: Entities extracted from the document- **Edge**: Connects multiple nodes, expressing complex relationships among multiple entities-```#### AutoTemporalGraph / AutoSpatialGraph / AutoSpatioTemporalGraphIn addition to node and edge definitions, time/location definitions must also be added:-```+## Core Concept Definitions- **Node**: Entities extracted from the document- **Edge**: Relationships between nodes- **Time**: xxx (define according to actual needs)- **Location**: xxx (define according to actual needs)-```+---@@ -293,6 +307,12 @@ In addition to node and edge definitions, time/location definitions must also be## 6. Show Function Design Specifications+### 7.1 Design Pattern++The `show()` method should follow the decorator pattern, wrapping the parent class implementation.++### 7.2 Implementation Example+```pythondef show(self,@@ -376,7 +396,8 @@ You are a professional [domain] expert, extract all entities as nodes from the t1. Each node must correspond to a single independent entity; do not merge multiple entities into one node2. Entity names should remain consistent with the source text-### Source Text:+## Pending Text to Analyze:+{source_text}"""_EDGE_PROMPT = """## Role and Task@@ -400,6 +421,12 @@ Current Observation Date: {observation_time}2. Exact time → keep as-is3. Missing time → leave empty++## Known Entities+{known_nodes}++## Pending Text to Analyze+{source_text}"""_PROMPT = """## Role and Task@@ -426,7 +453,8 @@ Current Observation Date: {observation_time}2. Exact time → keep as-is3. Missing time → leave empty-### Source Text:+## Pending Text to Analyze:+{source_text}"""# ==============================================================================diff --git a/hyperextract/templates/en/__init__.py b/hyperextract/templates/en/__init__.pyindex ed105a7..e69de29 100644--- a/hyperextract/templates/en/__init__.py+++ b/hyperextract/templates/en/__init__.py@@ -1,40 +0,0 @@-from .general import (- # Arbitrary Text- KnowledgeGraph,- EntityRegistry,- KeywordList,- # Wikipedia/Baidu Baike Entries- EncyclopediaItem,- ConceptHierarchy,- CrossReferenceNet,- # Biographies and Memoirs- PersonalProfile,- SocialNetwork,- LifeEventTimeline,- # Rules and Compliance Documents- RegulationProfile,- ClauseList,- PenaltyRegistry,- OperationalProcedure,- PenaltyMapping,- ComplianceLogic,-)--__all__ = [- # general- "KnowledgeGraph",- "EntityRegistry",- "KeywordList",- "EncyclopediaItem",- "ConceptHierarchy",- "CrossReferenceNet",- "PersonalProfile",- "SocialNetwork",- "LifeEventTimeline",- "RegulationProfile",- "ClauseList",- "PenaltyRegistry",- "OperationalProcedure",- "PenaltyMapping",- "ComplianceLogic",-]diff --git a/hyperextract/templates/en/general/__init__.py b/hyperextract/templates/en/general/__init__.pyindex d7304a5..e69de29 100644--- a/hyperextract/templates/en/general/__init__.py+++ b/hyperextract/templates/en/general/__init__.py@@ -1,48 +0,0 @@-from .knowledge_graph import KnowledgeGraph-from .entity_registry import EntityRegistry-from .keyword_list import KeywordList-from .encyclopedia_item import EncyclopediaItem-from .concept_hierarchy import ConceptHierarchy-from .cross_reference_net import CrossReferenceNet-from .personal_profile import PersonalProfile-from .social_network import SocialNetwork-from .life_event_timeline import LifeEventTimeline-from .regulation_profile import RegulationProfile-from .clause_list import ClauseList-from .penalty_registry import PenaltyRegistry-from .operational_procedure import OperationalProcedure-from .penalty_mapping import PenaltyMapping-from .compliance_logic import ComplianceLogic--__all__ = [- # Knowledge Graph- "KnowledgeGraph",- # Entity Registry- "EntityRegistry",- # Keyword List- "KeywordList",- # Encyclopedia Item- "EncyclopediaItem",- # Concept Hierarchy- "ConceptHierarchy",- # Cross Reference Network- "CrossReferenceNet",- # Personal Profile- "PersonalProfile",- # Social Network- "SocialNetwork",- # Life Event Timeline- "LifeEventTimeline",- # Regulation Profile- "RegulationProfile",- # Clause List- "ClauseList",- # Penalty Registry- "PenaltyRegistry",- # Operational Procedure- "OperationalProcedure",- # Penalty Mapping- "PenaltyMapping",- # Compliance Logic- "ComplianceLogic"-]diff --git a/hyperextract/templates/en/general/clause_list.py b/hyperextract/templates/en/general/clause_list.pydeleted file mode 100644index d64796b..0000000--- a/hyperextract/templates/en/general/clause_list.py+++ /dev/null@@ -1,105 +0,0 @@-"""Clause List - Break down regulations into atomic clauses for quick indexing.--Suitable for clause retrieval, full-text comparison, etc.-"""--from typing import Any-from pydantic import BaseModel, Field-from langchain_core.language_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoList---class Clause(BaseModel):- """Regulation clause"""- clauseId: str = Field(description="Clause ID, e.g., Article 1, Section 2.1")- title: str = Field(description="Clause title/subject", default="")- content: str = Field(description="Clause content")- category: str = Field(description="Clause category: GeneralProvisions, RightsAndObligations, Procedures, Penalties, SupplementaryProvisions, Other", default="Other")---_PROMPT = """## Role and Task-You are a professional regulation clause breakdown expert. Please break down the text into atomic clauses.--## Extraction Rules-1. Break down the regulation into independent clauses according to its natural structure-2. Assign an ID to each clause (e.g., Article 1, Section 2.1, etc.)-3. Extract the content of each clause-4. Add an appropriate title or subject to the clause (if available)-5. Assign a category to each clause: GeneralProvisions, RightsAndObligations, Procedures, Penalties, SupplementaryProvisions, Other--### Constraints-- Keep clause content consistent with the original text-- Do not omit any clauses-- Maintain the integrity of clauses--### Source text:-"""---class ClauseList(AutoList[Clause]):- """- Applicable documents: Company internal management systems, administrative regulations, operation manuals, compliance guidelines-- Function introduction:- Break down regulations into atomic clauses for quick indexing. Suitable for clause retrieval, full-text comparison, etc.-- Example:- >>> template = ClauseList(llm_client=llm, embedder=embedder)- >>> template.feed_text("Universe First Slacker Company Employee Attendance Management System...")- >>> for clause in template:- ... print(f"{clause.clauseId}: {clause.content}")- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- Initialize clause list template.-- Args:- llm_client: LLM client for knowledge extraction- embedder: Embedding model for semantic search- max_workers: Maximum number of worker threads, default: 10- verbose: Whether to output detailed logs, default: False- **kwargs: Other technical parameters, passed to base class- """- super().__init__(- item_schema=Clause,- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- max_workers=max_workers,- verbose=verbose,- **kwargs,- )-- def show(- self,- *,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,- ):- """- Display clause list.-- Args:- top_k_for_search: Number of clauses to return for semantic search, default: 3- top_k_for_chat: Number of clauses to use for chat, default: 3- """- def itemLabelExtractor(item: Clause) -> str:- if item.title:- return f"{item.clauseId}: {item.title}"- return f"{item.clauseId}"-- super().show(- item_label_extractor=itemLabelExtractor,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,- )diff --git a/hyperextract/templates/en/general/compliance_logic.py b/hyperextract/templates/en/general/compliance_logic.pydeleted file mode 100644index af91965..0000000--- a/hyperextract/templates/en/general/compliance_logic.py+++ /dev/null@@ -1,192 +0,0 @@-"""Compliance Logic - Model complex logic of "under what conditions, which subjects must/may not perform which actions".--Suitable for compliance auditing, risk identification, etc.-"""--from typing import Any, List-from pydantic import BaseModel, Field-from langchain_core.language_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoHypergraph---class ComplianceElement(BaseModel):- """Compliance Element - Node"""-- name: str = Field(description="Element name, exact name from text")- category: str = Field(- description="Element category: Subject, Action, Condition, Other"- )- description: str = Field(description="Brief description", default="")---class ComplianceRule(BaseModel):- """Compliance Rule - Hyperedge"""-- ruleType: str = Field(description="Rule type: Must, MustNot, May, Other")- participants: List[str] = Field(- description="List of participating element names, must use names from extracted nodes"- )- action: str = Field(description="Required or prohibited action content")- condition: str = Field(- description="Applicable conditions/prerequisites", default=""- )- consequence: str = Field(- description="Violation consequences/incentives", default=""- )- sourceClause: str = Field(description="Source clause of the rule", default="")---_PROMPT = """## Role and Task-You are a professional compliance assessor, skilled in extracting compliance elements and analyzing rule logic from documents. Please extract compliance elements and rules from the text to build a compliance behavior hypergraph.--## Core Concept Definitions-- **Node**: In this template, "Node" refers to basic elements that make up rules, divided into four categories:- - **Subject**: Entities that perform actions (individuals, departments, organizations, roles, etc.)- - **Action**: Specific actions or behaviors (submit, approve, execute, prohibit, etc.)- - **Condition**: Prerequisites or scenarios where the rule applies (time, location, status, quantity, etc.)- - **Other**: Elements that don't fall into the above categories (documents, files, status, results, etc.)-- **Hyperedge(Edge)**: In this template, "Hyperedge" is also known as "rule", connects multiple nodes and expresses the logic of "under what conditions, which subjects must/may not perform which actions".--## Extraction Rules-### Node Extraction-1. Extract elements involved in rules as nodes-2. Assign category to each element: Subject, Action, Condition, Other-3. Add brief description for each element--### Hyperedge Extraction-1. Only create rules from extracted nodes-2. Rule type: Must, MustNot, May, Other-3. Must contain ruleType, participants, and action-4. participants must strictly use names from extracted nodes-5. Try to fill other fields, use empty string for missing fields--### Source text:-"""--_NODE_PROMPT = """## Role and Task-You are a professional compliance element recognition expert, skilled in accurately identifying core compliance-related elements from documents. Please extract all compliance-related elements as nodes from the text.--## Core Concept Definitions-- **Node**: In this template, "Node" refers to basic elements that make up rules, divided into four categories:- - **Subject**: Entities that perform actions (individuals, departments, organizations, roles, etc.)- - **Action**: Specific actions or behaviors (submit, approve, execute, prohibit, etc.)- - **Condition**: Prerequisites or scenarios where the rule applies (time, location, status, quantity, etc.)- - **Other**: Elements that don't fall into the above categories (documents, files, status, results, etc.)--## Extraction Rules-1. Extract concrete, atomic elements, not abstract "processes" or "comparison tables"-2. Use exact nouns or verbs from the text as element names-3. Assign correct category to each element-4. Add brief description (1-2 sentences) for each element--### Source text:-"""--_EDGE_PROMPT = """## Role and Task-You are a professional compliance rule analyst, skilled in building clear compliance rule relationships from given elements. Please extract compliance rule hyperedges from the given node list.--## Core Concept Definitions-- **Node**: In this template, "Node" refers to basic elements that make up rules, serving as participants in hyperedges.-- **Hyperedge(Edge)**: In this template, "Hyperedge" is also known as "rule", connects multiple nodes and expresses the logic of "under what conditions, which subjects must/may not perform which actions".--## Extraction Rules-1. **participants must strictly use names from the "Known Elements List" below**, do not create new names-2. Rules must contain ruleType, participants, and action-3. participants should include: involved subjects, executed actions, and related other elements--### Rule Types-- **Must**: Mandatory actions to perform-- **MustNot**: Prohibited actions-- **May**: Permissible actions-- **Other**: Rules that don't fall into the above categories--"""---class ComplianceLogic(AutoHypergraph[ComplianceElement, ComplianceRule]):- """- Applicable documents: Compliance guidelines, administrative regulations, company management systems-- Function introduction:- Model complex logic of "under what conditions, which subjects must/may not perform which actions". Suitable for compliance auditing, risk identification, etc.-- Example:- >>> template = ComplianceLogic(llm_client=llm, embedder=embedder)- >>> template.feed_text("Company Compliance Manual...")- >>> template.show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- extraction_mode: str = "two_stage",- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- Initialize compliance logic hypergraph template.-- Args:- llm_client: LLM client for knowledge extraction- embedder: Embedding model for semantic search- extraction_mode: Extraction mode, either "one_stage" (extract nodes and edges simultaneously)- or "two_stage" (extract nodes first, then edges), default: "two_stage"- max_workers: Maximum number of worker threads, default: 10- verbose: Whether to output detailed logs, default: False- **kwargs: Other technical parameters, passed to base class- """- super().__init__(- node_schema=ComplianceElement,- edge_schema=ComplianceRule,- node_key_extractor=lambda x: x.name,- edge_key_extractor=lambda x: (- f"{sorted(x.participants)}_{x.ruleType}_{x.action}"- ),- nodes_in_edge_extractor=lambda x: tuple(x.participants),- llm_client=llm_client,- embedder=embedder,- extraction_mode=extraction_mode,- max_workers=max_workers,- verbose=verbose,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- **kwargs,- )-- def show(- self,- *,- top_k_nodes_for_search: int = 3,- top_k_edges_for_search: int = 3,- top_k_nodes_for_chat: int = 3,- top_k_edges_for_chat: int = 3,- ):- """- Display compliance logic hypergraph.-- Args:- top_k_nodes_for_search: Number of nodes to return for semantic search, default: 3- top_k_edges_for_search: Number of edges to return for semantic search, default: 3- top_k_nodes_for_chat: Number of nodes to use for chat, default: 3- top_k_edges_for_chat: Number of edges to use for chat, default: 3- """-- def node_label_extractor(node: ComplianceElement) -> str:- return f"{node.name} ({node.category})"-- def edge_label_extractor(edge: ComplianceRule) -> str:- return f"[{edge.ruleType}] {edge.action}"-- super().show(- node_label_extractor=node_label_extractor,- edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_nodes_for_search,- top_k_edges_for_search=top_k_edges_for_search,- top_k_nodes_for_chat=top_k_nodes_for_chat,- top_k_edges_for_chat=top_k_edges_for_chat,- )diff --git a/hyperextract/templates/en/general/concept_hierarchy.py b/hyperextract/templates/en/general/concept_hierarchy.pydeleted file mode 100644index ea9ad9c..0000000--- a/hyperextract/templates/en/general/concept_hierarchy.py+++ /dev/null@@ -1,162 +0,0 @@-"""Concept Hierarchy - Build subclass relationships (Subclass-Of) or composition relationships (Part-Of).--Suitable for scientific disciplines, textbook knowledge points, etc.-"""--from typing import Any, Optional-from pydantic import BaseModel, Field-from langchain_core.language_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoGraph---class ConceptNode(BaseModel):- """Concept node"""-- name: str = Field(description="Concept name")- category: str = Field(- description="Concept type: CoreConcept, Subconcept, Attribute, Instance, Other"- )- description: str = Field(description="Brief concept description", default="")---class HierarchyRelation(BaseModel):- """Hierarchy relationship edge"""-- source: str = Field(description="Parent concept/whole concept")- target: str = Field(description="Subconcept/part concept")- relationType: str = Field(- description="Relationship type: Subclass-Of (taxonomy), Part-Of (composition), Instance-Of (instance), Other"- )- details: str = Field(description="Detailed relationship explanation", default="")---_PROMPT = """## Role and Task-You are a professional concept structure analysis expert. Please extract concepts and their hierarchical relationships from the text.--## Core Concept Definitions-- **Node**: concept unit-- **Edge**: hierarchical relationship between concepts--## Extraction Rules-### Node Extraction Rules-1. Extract all concepts-2. Assign a type to each concept--### Edge Extraction Rules-1. Only create edges from extracted concepts-2. Each edge must connect extracted nodes--### Source text:-"""--_NODE_PROMPT = """## Role and Task-Please extract concepts as nodes from the text.--## Core Concept Definitions-- **Node**: concept unit--## Extraction Rules-1. Extract all concepts-2. Assign a type to each concept--### Source text:-"""--_EDGE_PROMPT = """## Role and Task-Please extract hierarchical relationships between concepts from the known concept list.--## Core Concept Definitions-- **Edge**: hierarchical relationship between concepts--## Constraints-1. Only extract edges from the known concept list-2. Do not create unlisted concepts-"""---class ConceptHierarchy(AutoGraph[ConceptNode, HierarchyRelation]):- """- Applicable Documents: Scientific disciplines, textbook knowledge points, ontology documents-- Function Introduction:- Extract concepts and build subclass relationships (Subclass-Of) or composition relationships (Part-Of),- suitable for scientific disciplines, textbook knowledge points, etc.-- Example:- >>> template = ConceptHierarchy(llm_client=llm, embedder=embedder)- >>> template.feed_text("Animals are divided into mammals, birds, reptiles, amphibians and fish...")- >>> template.show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- extraction_mode: str = "two_stage",- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- Initialize the concept hierarchy template.-- Args:- llm_client: LLM client for knowledge extraction- embedder: Embedding model for semantic retrieval- extraction_mode: Extraction mode, optional "one_stage" (extract nodes and edges simultaneously)- or "two_stage" (extract nodes first, then edges), default is "two_stage"- max_workers: Maximum worker threads, default is 10- verbose: Whether to output detailed logs, default is False- **kwargs: Other technical parameters, passed to the base class- """- super().__init__(- node_schema=ConceptNode,- edge_schema=HierarchyRelation,- node_key_extractor=lambda x: x.name,- edge_key_extractor=lambda x: f"{x.source}|{x.relationType}|{x.target}",- nodes_in_edge_extractor=lambda x: (x.source, x.target),- llm_client=llm_client,- embedder=embedder,- extraction_mode=extraction_mode,- max_workers=max_workers,- verbose=verbose,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- **kwargs,- )-- def show(- self,- *,- top_k_nodes_for_search: int = 3,- top_k_edges_for_search: int = 3,- top_k_nodes_for_chat: int = 3,- top_k_edges_for_chat: int = 3,- ):- """- Display the concept hierarchy.-- Args:- top_k_nodes_for_search: Number of nodes returned by semantic search, default is 3- top_k_edges_for_search: Number of edges returned by semantic search, default is 3- top_k_nodes_for_chat: Number of nodes used for Q&A, default is 3- top_k_edges_for_chat: Number of edges used for Q&A, default is 3- """-- def node_label_extractor(node: ConceptNode) -> str:- return f"{node.name} ({node.category})"-- def edge_label_extractor(edge: HierarchyRelation) -> str:- return edge.relationType-- super().show(- node_label_extractor=node_label_extractor,- edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_nodes_for_search,- top_k_edges_for_search=top_k_edges_for_search,- top_k_nodes_for_chat=top_k_nodes_for_chat,- top_k_edges_for_chat=top_k_edges_for_chat,- )diff --git a/hyperextract/templates/en/general/cross_reference_net.py b/hyperextract/templates/en/general/cross_reference_net.pydeleted file mode 100644index 8339784..0000000--- a/hyperextract/templates/en/general/cross_reference_net.py+++ /dev/null@@ -1,184 +0,0 @@-"""Cross Reference Network - Map hyperlinks or mutual reference relationships between concepts.--Suitable for encyclopedia internal links, cross-entry association graphs, etc.-"""--from typing import Any, Optional-from pydantic import BaseModel, Field-from langchain_core.language_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoGraph---class ReferenceNode(BaseModel):- """Reference node"""-- name: str = Field(description="Concept/entry name")- type: str = Field(- description="Node type: Entry, Section, Concept, Person, Location, Other"- )- description: str = Field(description="Brief description", default="")---class ReferenceRelation(BaseModel):- """Reference relationship edge"""-- source: str = Field(description="Source entry/concept")- target: str = Field(description="Referenced entry/concept")- relationType: str = Field(- description="Relationship type: Hyperlink, Reference, SeeAlso, Related, Other"- )- context: str = Field(description="Reference context description", default="")---_PROMPT = """## Role and Task-You are a professional knowledge network analysis expert. Please extract concepts/entries and their mutual reference relationships from the text to build a cross-reference network.--## Core Concept Definitions-- **Node**: In this template, "Node" refers to a concept or entry unit, including types such as Entry, Section, Concept, Person, Location, etc., used to represent entities in a knowledge network.-- **Edge**: In this template, "Edge" refers to a reference relationship between concepts/entries, including binary relationships such as Hyperlink, Reference, SeeAlso, and Related.--## Extraction Rules-### Node Extraction Rules-1. Extract all mentioned concepts or entries-2. Assign a type to each node: Entry, Section, Concept, Person, Location, Other-3. Add a brief description for each node--### Edge Extraction Rules-1. Only create edges from extracted nodes-2. Relationship types include:- - Hyperlink: Hyperlink relationship- - Reference: Reference relationship- - SeeAlso: See also relationship- - Related: Related relationship- - Other: Other relationships-3. Record reference context description--### Constraints-- Each edge must connect extracted nodes-- Do not create nodes or relationships not mentioned in the text-- Maintain objectivity and accuracy, do not add information not in the text--### Source text:-"""--_NODE_PROMPT = """## Role and Task-You are a professional entry recognition expert. Please extract all concepts or entries as nodes from the text.--## Core Concept Definitions-- **Node**: In this template, "Node" refers to a concept or entry unit, including types such as Entry, Section, Concept, Person, Location, etc., used to represent entities in a knowledge network.--## Extraction Rules-1. Extract all mentioned concepts or entries-2. Assign a type to each node: Entry, Section, Concept, Person, Location, Other-3. Add a brief description for each node--### Source text:-"""--_EDGE_PROMPT = """## Role and Task-You are a professional reference relationship extraction expert. Please extract mutual reference relationships between nodes from the given node list.--## Core Concept Definitions-- **Node**: In this template, "Node" refers to a concept or entry unit, as participants in reference relationships.-- **Edge**: In this template, "Edge" refers to a reference relationship between concepts/entries, including binary relationships such as Hyperlink, Reference, SeeAlso, and Related.--## Extraction Rules-### Relationship Type Explanation-- Hyperlink: Hyperlink relationship-- Reference: Reference relationship-- SeeAlso: See also relationship-- Related: Related relationship-- Other: Other relationships--### Constraints-1. Only extract edges from the known node list below-2. Do not create unlisted nodes--"""---class CrossReferenceNet(AutoGraph[ReferenceNode, ReferenceRelation]):- """- Applicable documents: Wikipedia entries, knowledge base documents, web content with internal links-- Function introduction:- Map hyperlinks or mutual reference relationships between concepts. Suitable for encyclopedia internal links, cross-entry association graphs, etc.-- Example:- >>> template = CrossReferenceNet(llm_client=llm, embedder=embedder)- >>> template.feed_text("Machine Learning is a branch of Artificial Intelligence...")- >>> template.show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- extraction_mode: str = "two_stage",- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- Initialize cross-reference network template.-- Args:- llm_client: LLM client for knowledge extraction- embedder: Embedding model for semantic search- extraction_mode: Extraction mode, either "one_stage" (extract nodes and edges simultaneously)- or "two_stage" (extract nodes first, then edges), default: "two_stage"- max_workers: Maximum number of worker threads, default: 10- verbose: Whether to output detailed logs, default: False- **kwargs: Other technical parameters, passed to base class- """- super().__init__(- node_schema=ReferenceNode,- edge_schema=ReferenceRelation,- node_key_extractor=lambda x: x.name,- edge_key_extractor=lambda x: f"{x.source}|{x.relationType}|{x.target}",- nodes_in_edge_extractor=lambda x: (x.source, x.target),- llm_client=llm_client,- embedder=embedder,- extraction_mode=extraction_mode,- max_workers=max_workers,- verbose=verbose,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- **kwargs,- )-- def show(- self,- *,- top_k_nodes_for_search: int = 3,- top_k_edges_for_search: int = 3,- top_k_nodes_for_chat: int = 3,- top_k_edges_for_chat: int = 3,- ):- """- Display cross-reference network.-- Args:- top_k_nodes_for_search: Number of nodes to return for semantic search, default: 3- top_k_edges_for_search: Number of edges to return for semantic search, default: 3- top_k_nodes_for_chat: Number of nodes to use for chat, default: 3- top_k_edges_for_chat: Number of edges to use for chat, default: 3- """-- def node_label_extractor(node: ReferenceNode) -> str:- return f"{node.name} ({node.type})"-- def edge_label_extractor(edge: ReferenceRelation) -> str:- return edge.relationType-- super().show(- node_label_extractor=node_label_extractor,- edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_nodes_for_search,- top_k_edges_for_search=top_k_edges_for_search,- top_k_nodes_for_chat=top_k_nodes_for_chat,- top_k_edges_for_chat=top_k_edges_for_chat,- )diff --git a/hyperextract/templates/en/general/encyclopedia_item.py b/hyperextract/templates/en/general/encyclopedia_item.pydeleted file mode 100644index 55ea48a..0000000--- a/hyperextract/templates/en/general/encyclopedia_item.py+++ /dev/null@@ -1,107 +0,0 @@-"""Encyclopedia Item - Extract structured attribute information for a single subject (similar to an Infobox).--Suitable for Wikipedia, professional dictionary entries, etc.-"""--from typing import Any, Optional, List-from pydantic import BaseModel, Field-from langchain_core.language_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoModel---class EncyclopediaInfo(BaseModel):- """Encyclopedia item infobox"""- title: str = Field(description="Entry title")- entityType: str = Field(description="Entity type: Person, Location, Organization, Event, Concept, Item, Other")- alternativeNames: List[str] = Field(description="Aliases, common names, foreign names", default_factory=list)- category: List[str] = Field(description="Category tags", default_factory=list)- summary: str = Field(description="Abstract/introduction", default="")- attributes: List[str] = Field(description="Key attribute list, each element in format 'AttributeName: AttributeValue'", default_factory=list)- keyEvents: List[str] = Field(description="Important events/milestones", default_factory=list)- relatedConcepts: List[str] = Field(description="Related concepts/entries", default_factory=list)---_PROMPT = """## Role and Task-You are a professional encyclopedia editor. Please extract structured attribute information for a single subject from the text to build an encyclopedia item infobox.--## Extraction Rules-1. Identify the core subject of the text (Person, Location, Organization, Event, Concept, etc.)-2. Assign a type to the subject: Person, Location, Organization, Event, Concept, Item, Other-3. Extract all aliases, common names, or foreign names-4. Extract category tags (e.g., "Scientist", "Mathematics", "Ancient China")-5. Write a 100-200 word summary-6. Extract key attributes, each in format 'AttributeName: AttributeValue' (e.g., 'Date of Birth: 429', 'Nationality: China')-7. Extract important events or milestones-8. Extract related concepts or entries--### Constraints-- Only extract information explicitly mentioned in the text, do not add additional content-- Keep attribute names concise and clear-- Maintain objectivity and accuracy, consistent with encyclopedia style--### Source text:-"""---class EncyclopediaItem(AutoModel[EncyclopediaInfo]):- """- Applicable documents: Wikipedia entries, encyclopedia entries, professional dictionary entries-- Function introduction:- Extract structured attribute information for a single subject (similar to an Infobox). Suitable for Wikipedia, professional dictionary entries, etc.-- Example:- >>> template = EncyclopediaItem(llm_client=llm, embedder=embedder)- >>> template.feed_text("Zu Chongzhi (429-500), courtesy name Wenyuan, was from Qiuxian, Fanyang...")- >>> print(template.data.title)- >>> print(template.data.summary)- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- Initialize encyclopedia item template.-- Args:- llm_client: LLM client for knowledge extraction- embedder: Embedding model for semantic search- max_workers: Maximum number of worker threads, default: 10- verbose: Whether to output detailed logs, default: False- **kwargs: Other technical parameters, passed to base class- """- super().__init__(- data_schema=EncyclopediaInfo,- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- max_workers=max_workers,- verbose=verbose,- **kwargs,- )-- def show(- self,- *,- top_k: int = 3,- ):- """- Display encyclopedia item.-- Args:- top_k: Number of items to use for chat, default: 3- """- def label_extractor(item: EncyclopediaInfo) -> str:- return f"{item.title} ({item.entityType})"-- super().show(- label_extractor=label_extractor,- top_k=top_k,- )diff --git a/hyperextract/templates/en/general/entity_registry.py b/hyperextract/templates/en/general/entity_registry.pydeleted file mode 100644index 446217b..0000000--- a/hyperextract/templates/en/general/entity_registry.py+++ /dev/null@@ -1,101 +0,0 @@-"""Entity Registry - Deduplicate and summarize all unique entities appearing in the text.--Suitable for entity discovery, named entity recognition, etc.-"""--from typing import Any-from pydantic import BaseModel, Field-from langchain_core.language_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoSet---class RegistryEntry(BaseModel):- """Registry entry"""- name: str = Field(description="Entity name, consistent with original text")- category: str = Field(description="Entity type: Person, Organization, Location, Product, Concept, Other")- description: str = Field(description="Brief description", default="")---_PROMPT = """## Role and Task-You are a professional entity recognition expert. Please extract all unique entities from the text to form an entity registry.--## Extraction Rules-1. Extract all entities: Person, Organization, Location, Product, Concept, etc.-2. Assign a type to each entity: Person, Organization, Location, Product, Concept, Other-3. Keep entity names consistent with the original text-4. Add a brief description for each entity--### Constraints-- Deduplication: Only keep one record for the same entity-- Maintain objectivity and accuracy, do not add information not in the text-- Entity name case should be consistent with the original text--### Source text:-"""---class EntityRegistry(AutoSet[RegistryEntry]):- """- Applicable documents: Arbitrary text, web scraped content, news reports-- Function introduction:- Deduplicate and summarize all unique entities (e.g., person names, organization names) appearing in the text to form an entity registry. Supports entity discovery and named entity recognition.-- Example:- >>> template = EntityRegistry(llm_client=llm, embedder=embedder)- >>> template.feed_text("Galaxy Interstellar announces successful maiden flight of Shenzhou-50...")- >>> print(list(template))- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- Initialize entity registry template.-- Args:- llm_client: LLM client for knowledge extraction- embedder: Embedding model for semantic search- max_workers: Maximum number of worker threads, default: 10- verbose: Whether to output detailed logs, default: False- **kwargs: Other technical parameters, passed to base class- """- super().__init__(- item_schema=RegistryEntry,- key_extractor=lambda x: x.name,- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- max_workers=max_workers,- verbose=verbose,- **kwargs,- )-- def show(- self,- *,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,- ):- """- Display entity registry.-- Args:- top_k_for_search: Number of items to return for semantic search, default: 3- top_k_for_chat: Number of items to use for chat, default: 3- """- def itemLabelExtractor(item: RegistryEntry) -> str:- return f"{item.name} ({item.category})"-- super().show(- item_label_extractor=itemLabelExtractor,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,- )diff --git a/hyperextract/templates/en/general/keyword_list.py b/hyperextract/templates/en/general/keyword_list.pydeleted file mode 100644index 2ebc59a..0000000--- a/hyperextract/templates/en/general/keyword_list.py+++ /dev/null@@ -1,99 +0,0 @@-"""Keyword List - Extract keywords from text with category and description information.--Suitable for content tag generation, topic analysis, etc.-"""--from typing import Any-from pydantic import BaseModel, Field-from langchain_core.language_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoList---class Keyword(BaseModel):- """Keyword entry"""- term: str = Field(description="Keyword")- category: str = Field(description="Category: CoreConcept, Term, PersonName, OrganizationName, Other")- description: str = Field(description="Brief description or context explanation of the keyword", default="")---_PROMPT = """## Role and Task-You are a professional keyword extraction expert. Please extract all keywords from the text with category and description information.--## Extraction Rules-1. Extract all keywords and core phrases from the text-2. Assign a category to each keyword: CoreConcept, Term, PersonName, OrganizationName, Other-3. Add a brief description for each keyword, explaining its meaning or context in the text--### Constraints-- Ensure keyword accuracy, do not add information not in the text-- Keep keyword case consistent with the original text--### Source text:-"""---class KeywordList(AutoList[Keyword]):- """- Applicable documents: Arbitrary text, blog articles, academic papers-- Function introduction:- Extract keywords from text with category and description information. Suitable for content tag generation and topic analysis.-- Example:- >>> template = KeywordList(llm_client=llm, embedder=embedder)- >>> template.feed_text("Galaxy Interstellar announces successful maiden flight of Shenzhou-50...")- >>> for keyword in template:- ... print(f"{keyword.term} ({keyword.category}): {keyword.description}")- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- Initialize keyword list template.-- Args:- llm_client: LLM client for knowledge extraction- embedder: Embedding model for semantic search- max_workers: Maximum number of worker threads, default: 10- verbose: Whether to output detailed logs, default: False- **kwargs: Other technical parameters, passed to base class- """- super().__init__(- item_schema=Keyword,- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- max_workers=max_workers,- verbose=verbose,- **kwargs,- )-- def show(- self,- *,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,- ):- """- Display keyword list.-- Args:- top_k_for_search: Number of keywords to return for semantic search, default: 3- top_k_for_chat: Number of keywords to use for chat, default: 3- """- def itemLabelExtractor(item: Keyword) -> str:- return f"{item.term} ({item.category})"-- super().show(- item_label_extractor=itemLabelExtractor,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,- )diff --git a/hyperextract/templates/en/general/knowledge_graph.py b/hyperextract/templates/en/general/knowledge_graph.pydeleted file mode 100644index ddde61a..0000000--- a/hyperextract/templates/en/general/knowledge_graph.py+++ /dev/null@@ -1,163 +0,0 @@-"""General Knowledge Graph - Extract entities and relationships from any text.--Suitable for unstructured documents like arbitrary text, web scraped content, etc., to extract general entities and their relationships.-"""--from typing import Any, Optional, Tuple-from pydantic import BaseModel, Field-from langchain_core.language_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoGraph---class GeneralEntity(BaseModel):- """General entity node"""-- name: str = Field(- description="Entity name, e.g., person name, organization name, product name"- )- category: str = Field(- description="Entity type: Person, Organization, Location, Product, Concept, Other"- )- description: str = Field(description="Brief description", default="")---class GeneralRelation(BaseModel):- """General relationship edge"""-- source: str = Field(description="Source entity")- target: str = Field(description="Target entity")- relationType: str = Field(- description="Relationship type: BelongsTo, LocatedIn, CollaboratesWith, CompetesWith, InventedBy, CreatedBy, RelatedTo, etc."- )- details: str = Field(description="Detailed description", default="")---_PROMPT = """## Role and Task-You are a professional knowledge graph extraction expert. Please extract entities and their relationships from the text.--## Core Concept Definitions-- **Node**: general entity-- **Edge**: binary relationship between entities--## Extraction Rules-### Node Extraction Rules-1. Extract all entities-2. Assign a type to each entity--### Edge Extraction Rules-1. Only create edges from extracted entities-2. Each edge must connect extracted nodes--### Source text:-"""--_NODE_PROMPT = """## Role and Task-Please extract key entities as nodes from the text.--## Core Concept Definitions-- **Node**: general entity--## Extraction Rules-1. Extract all entities-2. Assign a type to each entity--### Source text:-"""--_EDGE_PROMPT = """## Role and Task-Please extract relationships between entities from the known entity list.--## Core Concept Definitions-- **Edge**: binary relationship between entities--## Constraints-1. Only extract edges from the known entity list-2. Do not create unlisted entities-"""---class KnowledgeGraph(AutoGraph[GeneralEntity, GeneralRelation]):- """- Applicable documents: Arbitrary text, web scraped content, blog articles, news reports-- Function introduction:- Extract general entities and their relationships from any text to build a knowledge graph. Supports multiple entity types including Person, Organization, Location, Product, Concept, etc.-- Example:- >>> template = KnowledgeGraph(llm_client=llm, embedder=embedder)- >>> template.feed_text("Galaxy Interstellar announces successful maiden flight of Shenzhou-50...")- >>> template.show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- extraction_mode: str = "two_stage",- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- Initialize the general knowledge graph template.-- Args:- llm_client: LLM client for knowledge extraction- embedder: Embedding model for semantic retrieval- extraction_mode: Extraction mode, optional "one_stage" (extract nodes and edges simultaneously)- or "two_stage" (extract nodes first, then edges), default is "two_stage"- max_workers: Maximum worker threads, default is 10- verbose: Whether to output detailed logs, default is False- **kwargs: Other technical parameters, passed to the base class- """- super().__init__(- node_schema=GeneralEntity,- edge_schema=GeneralRelation,- node_key_extractor=lambda x: x.name,- edge_key_extractor=lambda x: f"{x.source}|{x.relationType}|{x.target}",- nodes_in_edge_extractor=lambda x: (x.source, x.target),- llm_client=llm_client,- embedder=embedder,- extraction_mode=extraction_mode,- max_workers=max_workers,- verbose=verbose,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- **kwargs,- )-- def show(- self,- *,- top_k_nodes_for_search: int = 3,- top_k_edges_for_search: int = 3,- top_k_nodes_for_chat: int = 3,- top_k_edges_for_chat: int = 3,- ):- """- Display the knowledge graph.-- Args:- top_k_nodes_for_search: Number of nodes returned by semantic search, default is 3- top_k_edges_for_search: Number of edges returned by semantic search, default is 3- top_k_nodes_for_chat: Number of nodes used for Q&A, default is 3- top_k_edges_for_chat: Number of edges used for Q&A, default is 3- """-- def node_label_extractor(node: GeneralEntity) -> str:- return f"{node.name} ({node.category})"-- def edge_label_extractor(edge: GeneralRelation) -> str:- return edge.relationType-- super().show(- node_label_extractor=node_label_extractor,- edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_nodes_for_search,- top_k_edges_for_search=top_k_edges_for_search,- top_k_nodes_for_chat=top_k_nodes_for_chat,- top_k_edges_for_chat=top_k_edges_for_chat,- )diff --git a/hyperextract/templates/en/general/life_event_timeline.py b/hyperextract/templates/en/general/life_event_timeline.pydeleted file mode 100644index 04e3d1a..0000000--- a/hyperextract/templates/en/general/life_event_timeline.py+++ /dev/null@@ -1,231 +0,0 @@-"""Life Event Timeline - Extract timestamped events and arrange them chronologically.--Suitable for biographies, chronologies, memoirs, etc.-"""--from typing import Any, Optional-from pydantic import BaseModel, Field-from langchain_core.language_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoTemporalGraph---class LifeEntity(BaseModel):- """Life entity node"""-- name: str = Field(description="Entity name")- type: str = Field(- description="Entity type: Person, Location, Organization, Item, Concept, Other"- )- description: str = Field(description="Brief description", default="")---class LifeEvent(BaseModel):- """Life event edge (with optional timestamp)"""-- source: str = Field(description="Event subject/related entity")- target: str = Field(description="Event object/related entity")- eventType: str = Field(- description="Event type: Birth, Death, Education, Work, Achievement, Interaction, Travel, Other"- )- eventDate: Optional[str] = Field(- description="Event date, format: YYYY-MM-DD or YYYY, optional", default=None- )- details: str = Field(description="Detailed event description", default="")---_PROMPT = """## Role and Task-You are a professional biography chronology expert. Please extract entities such as people, locations, organizations, etc., and life events from the text to build a life event timeline.--## Core Concept Definitions-- **Node**: In this template, "Node" refers to a life entity, including types such as Person, Location, Organization, Item, and Concept, used to represent entities in a life timeline.-- **Edge**: In this template, "Edge" refers to a life event, connecting multiple entities to record binary relationships of life experiences such as birth, education, work, and achievements.-- **Time**: In this template, "Time" refers to the temporal information of when events occur, used to arrange life events in chronological order, supporting relative time parsing.--## Extraction Rules-### Node Extraction Rules-1. Extract all related entities: Person, Location, Organization, Item, Concept, etc.-2. Assign a type to each entity: Person, Location, Organization, Item, Concept, Other-3. Add a brief description for each entity--### Event Extraction Rules-1. Only create event edges from extracted entities-2. Event types include:- - Birth: Birth events- - Death: Death events- - Education: Learning, education events- - Work: Work, career events- - Achievement: Achievement, honor events- - Interaction: Interpersonal interaction, social activity events- - Travel: Travel, relocation events- - Other: Other events-3. Event date is optional, only extract when explicitly mentioned in the text-4. Date format: YYYY-MM-DD (e.g., 429-01-01) or year only (e.g., 429)-5. Each edge must connect extracted nodes--### Time Parsing Rules-Current observation date: {observation_time}--1. Relative time parsing (based on observation date):- - "last year" → the year before {observation_time}- - "last month" → the month before {observation_time}- - "this quarter" → the quarter of {observation_time}- - "recent" → the last 3 months from {observation_time}--2. Exact time → Keep as is-3. Missing time → Leave blank, do not guess--### Constraints-- Do not create entities or events not mentioned in the text-- Maintain objectivity and accuracy, do not add information not in the text--### Source text:-"""--_NODE_PROMPT = """## Role and Task-You are a professional entity recognition expert. Please extract all related entities as nodes from the text.--## Core Concept Definitions-- **Node**: In this template, "Node" refers to a life entity, including types such as Person, Location, Organization, Item, and Concept, used to represent entities in a life timeline.--## Extraction Rules-1. Extract all related entities: Person, Location, Organization, Item, Concept, etc.-2. Assign a type to each entity: Person, Location, Organization, Item, Concept, Other-3. Add a brief description for each entity--### Source text:-"""--_EDGE_PROMPT = """## Role and Task-You are a professional life event extraction expert. Please extract life events from the given entity list.--## Core Concept Definitions-- **Node**: In this template, "Node" refers to a life entity, as participants in life events.-- **Edge**: In this template, "Edge" refers to a life event, connecting multiple entities to record binary relationships of life experiences such as birth, education, work, and achievements.-- **Time**: In this template, "Time" refers to the temporal information of when events occur, used to arrange life events in chronological order, supporting relative time parsing.--## Extraction Rules-### Event Type Explanation-- Birth: Birth events-- Death: Death events-- Education: Learning, education events-- Work: Work, career events-- Achievement: Achievement, honor events-- Interaction: Interpersonal interaction, social activity events-- Travel: Travel, relocation events-- Other: Other events--### Time Parsing Rules-Current observation date: {observation_time}--1. Relative time parsing (based on observation date):- - "last year" → the year before {observation_time}- - "last month" → the month before {observation_time}- - "this quarter" → the quarter of {observation_time}- - "recent" → the last 3 months from {observation_time}--2. Exact time → Keep as is-3. Missing time → Leave blank, do not guess--### Date Format Requirements-- All date information should be converted to "YYYY-MM-DD" format (e.g., 429-01-01) or year only (e.g., 429)-- Time information is optional, only extract when explicitly mentioned in the text--### Constraints-1. Only extract events from the known entity list below-2. Do not create unlisted entities-3. Time information is optional, only extract when explicitly mentioned in the text--"""---class LifeEventTimeline(AutoTemporalGraph[LifeEntity, LifeEvent]):- """- Applicable documents: Biographies, chronologies, memoirs, autobiographies-- Function introduction:- Extract timestamped events and arrange them chronologically. Suitable for biographies, chronologies, memoirs, etc.-- Example:- >>> template = LifeEventTimeline(llm_client=llm, embedder=embedder)- >>> template.feed_text("Zu Chongzhi (429-500), courtesy name Wenyuan, was from Qiuxian, Fanyang...")- >>> template.show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- observation_time: str | None = None,- extraction_mode: str = "two_stage",- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- Initialize life event timeline template.-- Args:- llm_client: LLM client for knowledge extraction- embedder: Embedding model for semantic search- observation_time: Observation date, used for parsing relative time expressions, default: today- extraction_mode: Extraction mode, either "one_stage" (extract nodes and edges simultaneously)- or "two_stage" (extract nodes first, then edges), default: "two_stage"- max_workers: Maximum number of worker threads, default: 10- verbose: Whether to output detailed logs, default: False- **kwargs: Other technical parameters, passed to base class- """- super().__init__(- node_schema=LifeEntity,- edge_schema=LifeEvent,- node_key_extractor=lambda x: x.name,- edge_key_extractor=lambda x: f"{x.source}|{x.eventType}|{x.target}",- time_in_edge_extractor=lambda x: x.eventDate,- nodes_in_edge_extractor=lambda x: (x.source, x.target),- llm_client=llm_client,- embedder=embedder,- observation_time=observation_time,- extraction_mode=extraction_mode,- max_workers=max_workers,- verbose=verbose,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- **kwargs,- )-- def show(- self,- *,- top_k_nodes_for_search: int = 3,- top_k_edges_for_search: int = 3,- top_k_nodes_for_chat: int = 3,- top_k_edges_for_chat: int = 3,- ):- """- Display life event timeline.-- Args:- top_k_nodes_for_search: Number of nodes to retrieve for search callback (default: 3)- top_k_edges_for_search: Number of edges to retrieve for search callback (default: 3)- top_k_nodes_for_chat: Number of nodes to retrieve for chat callback (default: 3)- top_k_edges_for_chat: Number of edges to retrieve for chat callback (default: 3)- """-- def node_label_extractor(node: LifeEntity) -> str:- return f"{node.name} ({node.type})"-- def edge_label_extractor(edge: LifeEvent) -> str:- if edge.eventDate:- return f"{edge.eventType} ({edge.eventDate})"- return edge.eventType-- super().show(- node_label_extractor=node_label_extractor,- edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_nodes_for_search,- top_k_edges_for_search=top_k_edges_for_search,- top_k_nodes_for_chat=top_k_nodes_for_chat,- top_k_edges_for_chat=top_k_edges_for_chat,- )diff --git a/hyperextract/templates/en/general/operational_procedure.py b/hyperextract/templates/en/general/operational_procedure.pydeleted file mode 100644index 4dfca72..0000000--- a/hyperextract/templates/en/general/operational_procedure.py+++ /dev/null@@ -1,179 +0,0 @@-"""Operational Procedure - Extract the specific sequential steps for declaration, approval, or operations specified in regulations.--Suitable for operation guidance, SOP process visualization, etc.-"""--from typing import Any-from pydantic import BaseModel, Field-from langchain_core.language_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoGraph---class ProcedureStep(BaseModel):- """Procedure step node"""-- stepId: str = Field(description="Step ID, e.g., Step 1, Step 2")- name: str = Field(description="Step name")- description: str = Field(description="Detailed step description")- role: str = Field(description="Executor role", default="")- inputRequired: str = Field(description="Required inputs/materials", default="")- outputResult: str = Field(description="Output/result", default="")---class ProcedureTransition(BaseModel):- """Procedure transition edge"""-- source: str = Field(description="Source step ID")- target: str = Field(description="Target step ID")- condition: str = Field(description="Transition condition", default="")- details: str = Field(description="Detailed explanation", default="")---_PROMPT = """## Role and Task-You are a professional process analysis expert. Please extract the specific sequential steps for declaration, approval, or operations specified in regulations from the text to build an operational procedure flowchart.--## Core Concept Definitions-- **Node**: In this template, "Node" refers to a process step unit, an operational unit that includes fields such as step ID, name, description, executor role, inputs, and outputs.-- **Edge**: In this template, "Edge" refers to a transition relationship between process steps, a binary relationship that records the sequential order and transition conditions between steps.--## Extraction Rules-### Node Extraction Rules-1. Extract all process steps-2. Assign an ID to each step (e.g., Step 1, Step 2)-3. Add a name and detailed description to each step-4. Record the executor role (if available)-5. Record required inputs or materials (if available)-6. Record output or result (if available)--### Edge Extraction Rules-1. Only create transition edges from extracted steps-2. Record the sequential relationship between steps-3. Record transition conditions (if available)-4. Record detailed explanations (if available)--### Constraints-- Ensure the sequential order of process steps is accurate-- Maintain objectivity and accuracy, do not add information not in the text--### Source text:-"""--_NODE_PROMPT = """## Role and Task-You are a professional process step recognition expert. Please extract all process steps as nodes from the text.--## Core Concept Definitions-- **Node**: In this template, "Node" refers to a process step unit, an operational unit that includes fields such as step ID, name, description, executor role, inputs, and outputs.--## Extraction Rules-1. Extract all process steps-2. Assign an ID to each step (e.g., Step 1, Step 2)-3. Add a name and detailed description to each step-4. Record the executor role (if available)-5. Record required inputs or materials (if available)-6. Record output or result (if available)--### Source text:-"""--_EDGE_PROMPT = """## Role and Task-You are a professional process transition recognition expert. Please extract the sequential relationship between steps from the given step list.--## Core Concept Definitions-- **Node**: In this template, "Node" refers to a process step unit, as participants in process transitions.-- **Edge**: In this template, "Edge" refers to a transition relationship between process steps, a binary relationship that records the sequential order and transition conditions between steps.--## Extraction Rules-### Constraints-1. Only extract edges from the known step list below-2. Do not create unlisted steps--"""---class OperationalProcedure(AutoGraph[ProcedureStep, ProcedureTransition]):- """- Applicable documents: Operation manuals, SOPs, compliance guidelines, approval processes-- Function introduction:- Extract the specific sequential steps for declaration, approval, or operations specified in regulations. Suitable for operation guidance, SOP process visualization, etc.-- Example:- >>> template = OperationalProcedure(llm_client=llm, embedder=embedder)- >>> template.feed_text("Universe First Slacker Company Leave Approval Process...")- >>> template.show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- extraction_mode: str = "two_stage",- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- Initialize operational procedure template.-- Args:- llm_client: LLM client for knowledge extraction- embedder: Embedding model for semantic search- extraction_mode: Extraction mode, either "one_stage" (extract nodes and edges simultaneously)- or "two_stage" (extract nodes first, then edges), default: "two_stage"- max_workers: Maximum number of worker threads, default: 10- verbose: Whether to output detailed logs, default: False- **kwargs: Other technical parameters, passed to base class- """- super().__init__(- node_schema=ProcedureStep,- edge_schema=ProcedureTransition,- node_key_extractor=lambda x: x.stepId,- edge_key_extractor=lambda x: f"{x.source}|{x.target}",- nodes_in_edge_extractor=lambda x: (x.source, x.target),- llm_client=llm_client,- embedder=embedder,- extraction_mode=extraction_mode,- max_workers=max_workers,- verbose=verbose,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- **kwargs,- )-- def show(- self,- *,- top_k_nodes_for_search: int = 3,- top_k_edges_for_search: int = 3,- top_k_nodes_for_chat: int = 3,- top_k_edges_for_chat: int = 3,- ):- """- Display operational procedure flowchart.-- Args:- top_k_nodes_for_search: Number of nodes to return for semantic search, default: 3- top_k_edges_for_search: Number of edges to return for semantic search, default: 3- top_k_nodes_for_chat: Number of nodes to use for chat, default: 3- top_k_edges_for_chat: Number of edges to use for chat, default: 3- """-- def node_label_extractor(node: ProcedureStep) -> str:- return f"{node.stepId}: {node.name}"-- def edge_label_extractor(edge: ProcedureTransition) -> str:- if edge.condition:- return edge.condition- return "→"-- super().show(- node_label_extractor=node_label_extractor,- edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_nodes_for_search,- top_k_edges_for_search=top_k_edges_for_search,- top_k_nodes_for_chat=top_k_nodes_for_chat,- top_k_edges_for_chat=top_k_edges_for_chat,- )diff --git a/hyperextract/templates/en/general/penalty_mapping.py b/hyperextract/templates/en/general/penalty_mapping.pydeleted file mode 100644index 48afe95..0000000--- a/hyperextract/templates/en/general/penalty_mapping.py+++ /dev/null@@ -1,172 +0,0 @@-"""Penalty Mapping - Describe the evolution path from "violation behavior" to "handling procedure" to "final result".--Suitable for risk tracing, penalty logic analysis, etc.-"""--from typing import Any-from pydantic import BaseModel, Field-from langchain_core.language_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoGraph---class PenaltyNode(BaseModel):- """Penalty causal node"""-- name: str = Field(description="Node name")- type: str = Field(- description="Node type: Violation, HandlingProcedure, PenaltyResult, Other"- )- description: str = Field(description="Detailed description")---class PenaltyPath(BaseModel):- """Penalty causal path edge"""-- source: str = Field(description="Source node name")- target: str = Field(description="Target node name")- relation: str = Field(- description="Relationship type: Causes, Triggers, Executes, Produces, Other"- )- details: str = Field(description="Detailed explanation", default="")---_PROMPT = """## Role and Task-You are a professional penalty logic analysis expert. Please extract the evolution path from "violation behavior" to "handling procedure" to "final result" from the text to build a penalty mapping.--## Core Concept Definitions-- **Node**: In this template, "Node" refers to a key unit in the penalty causal chain, including types such as Violation, HandlingProcedure, and PenaltyResult, used to represent key links in the penalty process.-- **Edge**: In this template, "Edge" refers to a causal relationship between nodes, including binary relationships such as Causes, Triggers, Executes, and Produces, used to represent the evolution path from violation to penalty.--## Extraction Rules-### Node Extraction Rules-1. Extract all key nodes: Violation, HandlingProcedure, PenaltyResult, etc.-2. Assign a type to each node: Violation, HandlingProcedure, PenaltyResult, Other-3. Add a detailed description to each node--### Edge Extraction Rules-1. Only create causal path edges from extracted nodes-2. Record the causal relationship between nodes-3. Relationship types include: Causes, Triggers, Executes, Produces, Other-4. Add detailed explanations (if available)--### Constraints-- Ensure the logical order of causal relationships is correct-- Maintain objectivity and accuracy, do not add information not in the text--### Source text:-"""--_NODE_PROMPT = """## Role and Task-You are a professional penalty node recognition expert. Please extract all key nodes from the text.--## Core Concept Definitions-- **Node**: In this template, "Node" refers to a key unit in the penalty causal chain, including types such as Violation, HandlingProcedure, and PenaltyResult, used to represent key links in the penalty process.--## Extraction Rules-1. Extract all key nodes: Violation, HandlingProcedure, PenaltyResult, etc.-2. Assign a type to each node: Violation, HandlingProcedure, PenaltyResult, Other-3. Add a detailed description to each node--### Source text:-"""--_EDGE_PROMPT = """## Role and Task-You are a professional penalty causal relationship recognition expert. Please extract the causal relationship between nodes from the given node list.--## Core Concept Definitions-- **Node**: In this template, "Node" refers to a key unit in the penalty causal chain, as participants in causal relationships.-- **Edge**: In this template, "Edge" refers to a causal relationship between nodes, including binary relationships such as Causes, Triggers, Executes, and Produces, used to represent the evolution path from violation to penalty.--## Extraction Rules-### Constraints-1. Only extract edges from the known node list below-2. Do not create unlisted nodes--"""---class PenaltyMapping(AutoGraph[PenaltyNode, PenaltyPath]):- """- Applicable documents: Company internal management systems, administrative regulations, compliance guidelines, penalty cases-- Function introduction:- Describe the evolution path from "violation behavior" to "handling procedure" to "final result". Suitable for risk tracing, penalty logic analysis, etc.-- Example:- >>> template = PenaltyMapping(llm_client=llm, embedder=embedder)- >>> template.feed_text("Universe First Slacker Company Employee Penalty Regulations...")- >>> template.show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- extraction_mode: str = "two_stage",- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- Initialize penalty mapping template.-- Args:- llm_client: LLM client for knowledge extraction- embedder: Embedding model for semantic search- extraction_mode: Extraction mode, either "one_stage" (extract nodes and edges simultaneously)- or "two_stage" (extract nodes first, then edges), default: "two_stage"- max_workers: Maximum number of worker threads, default: 10- verbose: Whether to output detailed logs, default: False- **kwargs: Other technical parameters, passed to base class- """- super().__init__(- node_schema=PenaltyNode,- edge_schema=PenaltyPath,- node_key_extractor=lambda x: x.name,- edge_key_extractor=lambda x: f"{x.source}|{x.relation}|{x.target}",- nodes_in_edge_extractor=lambda x: (x.source, x.target),- llm_client=llm_client,- embedder=embedder,- extraction_mode=extraction_mode,- max_workers=max_workers,- verbose=verbose,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- **kwargs,- )-- def show(- self,- *,- top_k_nodes_for_search: int = 3,- top_k_edges_for_search: int = 3,- top_k_nodes_for_chat: int = 3,- top_k_edges_for_chat: int = 3,- ):- """- Display penalty mapping.-- Args:- top_k_nodes_for_search: Number of nodes to return for semantic search, default: 3- top_k_edges_for_search: Number of edges to return for semantic search, default: 3- top_k_nodes_for_chat: Number of nodes to use for chat, default: 3- top_k_edges_for_chat: Number of edges to use for chat, default: 3- """-- def node_label_extractor(node: PenaltyNode) -> str:- return f"{node.name} ({node.type})"-- def edge_label_extractor(edge: PenaltyPath) -> str:- return edge.relation-- super().show(- node_label_extractor=node_label_extractor,- edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_nodes_for_search,- top_k_edges_for_search=top_k_edges_for_search,- top_k_nodes_for_chat=top_k_nodes_for_chat,- top_k_edges_for_chat=top_k_edges_for_chat,- )diff --git a/hyperextract/templates/en/general/penalty_registry.py b/hyperextract/templates/en/general/penalty_registry.pydeleted file mode 100644index 60532cc..0000000--- a/hyperextract/templates/en/general/penalty_registry.py+++ /dev/null@@ -1,104 +0,0 @@-"""Penalty Registry - Deduplicate and summarize specific violations and their corresponding consequences to form a clear penalty ledger.--Suitable for internal risk control, compliance checks, etc.-"""--from typing import Any-from pydantic import BaseModel, Field-from langchain_core.language_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoSet---class PenaltyEntry(BaseModel):- """Violation penalty entry"""- violation: str = Field(description="Violation description")- severity: str = Field(description="Severity: Minor, Moderate, Serious, VerySerious")- penalty: str = Field(description="Penalty measure")- applicableClause: str = Field(description="Applicable clause", default="")- notes: str = Field(description="Notes", default="")---_PROMPT = """## Role and Task-You are a professional compliance analysis expert. Please extract all violations and their corresponding penalty measures from the text to form a violation penalty registry.--## Extraction Rules-1. Extract all violations and their corresponding penalty measures-2. Assign a severity level to each violation: Minor, Moderate, Serious, VerySerious-3. Maintain the accuracy of violations and penalty measures-4. Record applicable clauses (if available)-5. Add notes (if available)--### Constraints-- Deduplication: Only keep one record for the same violation and penalty measure combination-- Maintain objectivity and accuracy, do not add information not in the text--### Source text:-"""---class PenaltyRegistry(AutoSet[PenaltyEntry]):- """- Applicable documents: Company internal management systems, administrative regulations, compliance guidelines-- Function introduction:- Deduplicate and summarize specific violations and their corresponding consequences to form a clear penalty ledger. Suitable for internal risk control, compliance checks, etc.-- Example:- >>> template = PenaltyRegistry(llm_client=llm, embedder=embedder)- >>> template.feed_text("Universe First Slacker Company Employee Attendance Management System...")- >>> for entry in template:- ... print(f"{entry.violation} -> {entry.penalty}")- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- Initialize penalty registry template.-- Args:- llm_client: LLM client for knowledge extraction- embedder: Embedding model for semantic search- max_workers: Maximum number of worker threads, default: 10- verbose: Whether to output detailed logs, default: False- **kwargs: Other technical parameters, passed to base class- """- super().__init__(- item_schema=PenaltyEntry,- key_extractor=lambda x: f"{x.violation}_{x.penalty}",- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- max_workers=max_workers,- verbose=verbose,- **kwargs,- )-- def show(- self,- *,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,- ):- """- Display penalty registry.-- Args:- top_k_for_search: Number of entries to return for semantic search, default: 3- top_k_for_chat: Number of entries to use for chat, default: 3- """- def itemLabelExtractor(item: PenaltyEntry) -> str:- return f"{item.violation} ({item.severity})"-- super().show(- item_label_extractor=itemLabelExtractor,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,- )diff --git a/hyperextract/templates/en/general/personal_profile.py b/hyperextract/templates/en/general/personal_profile.pydeleted file mode 100644index 555053a..0000000--- a/hyperextract/templates/en/general/personal_profile.py+++ /dev/null@@ -1,115 +0,0 @@-"""Personal Profile - Aggregate static attributes of a person (birth/death dates, education, core identity).--Suitable for resumes, person introductions, obituary summaries, etc.-"""--from typing import Any, Optional, List-from pydantic import BaseModel, Field-from langchain_core.language_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoModel---class PersonalInfo(BaseModel):- """Personal profile information"""- name: str = Field(description="Name")- gender: Optional[str] = Field(description="Gender", default=None)- birthDate: Optional[str] = Field(description="Date of birth, format: YYYY-MM-DD or YYYY", default=None)- deathDate: Optional[str] = Field(description="Date of death, format: YYYY-MM-DD or YYYY", default=None)- nationality: Optional[str] = Field(description="Nationality", default=None)- birthPlace: Optional[str] = Field(description="Place of birth", default=None)- education: List[str] = Field(description="Education background", default_factory=list)- occupations: List[str] = Field(description="Occupations/identities", default_factory=list)- coreIdentity: List[str] = Field(description="Core identity/tags", default_factory=list)- majorAchievements: List[str] = Field(description="Major achievements", default_factory=list)- affiliations: List[str] = Field(description="Affiliated organizations/institutions", default_factory=list)- summary: str = Field(description="Personal introduction", default="")---_PROMPT = """## Role and Task-You are a professional personal profile editor. Please extract static attribute information of this person from the text to build a personal profile.--## Extraction Rules-1. Extract basic information: name, gender, date of birth, date of death, nationality, place of birth, etc.-2. Extract education background-3. Extract occupation or identity information-4. Extract core identity tags-5. Extract major achievements-6. Extract affiliated organizations or institutions-7. Write a 100-200 word personal introduction--### Date Format Requirements-All date information should be converted to "YYYY-MM-DD" format (e.g., 429-01-01) or year only (e.g., 429).--### Constraints-- Only extract information explicitly mentioned in the text, do not add additional content-- Maintain objectivity and accuracy-- Leave blank if information is missing, do not fabricate--### Source text:-"""---class PersonalProfile(AutoModel[PersonalInfo]):- """- Applicable documents: Resumes, person introductions, obituary summaries, Wikipedia person entries-- Function introduction:- Aggregate static attributes of a person (birth/death dates, education, core identity). Suitable for resumes, person introductions, obituary summaries, etc.-- Example:- >>> template = PersonalProfile(llm_client=llm, embedder=embedder)- >>> template.feed_text("Zu Chongzhi (429-500), courtesy name Wenyuan, was from Qiuxian, Fanyang...")- >>> print(template.data.name)- >>> print(template.data.birthDate)- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- Initialize personal profile template.-- Args:- llm_client: LLM client for knowledge extraction- embedder: Embedding model for semantic search- max_workers: Maximum number of worker threads, default: 10- verbose: Whether to output detailed logs, default: False- **kwargs: Other technical parameters, passed to base class- """- super().__init__(- data_schema=PersonalInfo,- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- max_workers=max_workers,- verbose=verbose,- **kwargs,- )-- def show(- self,- *,- top_k: int = 3,- ):- """- Display personal profile.-- Args:- top_k: Number of items to use for chat, default: 3- """- def label_extractor(item: PersonalInfo) -> str:- if item.birthDate and item.deathDate:- return f"{item.name} ({item.birthDate}-{item.deathDate})"- return item.name-- super().show(- label_extractor=label_extractor,- top_k=top_k,- )diff --git a/hyperextract/templates/en/general/regulation_profile.py b/hyperextract/templates/en/general/regulation_profile.pydeleted file mode 100644index abbb922..0000000--- a/hyperextract/templates/en/general/regulation_profile.py+++ /dev/null@@ -1,113 +0,0 @@-"""Regulation Profile - Extract the name, version, scope, effective date, and core purpose of a regulation.--Suitable for regulation overview, version management, etc.-"""--from typing import Any, Optional, List-from pydantic import BaseModel, Field-from langchain_core.language_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoModel---class RegulationInfo(BaseModel):- """Regulation metadata information"""- title: str = Field(description="Regulation title")- version: Optional[str] = Field(description="Version number", default=None)- issuer: Optional[str] = Field(description="Issuing authority", default=None)- issueDate: Optional[str] = Field(description="Issue date", default=None)- effectiveDate: Optional[str] = Field(description="Effective date", default=None)- expiryDate: Optional[str] = Field(description="Expiry date", default=None)- scope: List[str] = Field(description="Applicable scope", default_factory=list)- targetAudience: List[str] = Field(description="Target audience", default_factory=list)- corePurpose: str = Field(description="Core purpose/objective", default="")- keywords: List[str] = Field(description="Keywords/tags", default_factory=list)- relatedRegulations: List[str] = Field(description="Related regulations", default_factory=list)---_PROMPT = """## Role and Task-You are a professional regulation analysis expert. Please extract metadata information of this regulation from the text to build a regulation profile.--## Extraction Rules-1. Extract the full name of the regulation-2. Extract version number (if available)-3. Extract issuing authority-4. Extract issue date, effective date, expiry date (if available)-5. Extract applicable scope-6. Extract target audience-7. Extract core purpose or objective (100-200 words)-8. Extract keywords or tags-9. Extract related other regulations--### Constraints-- Only extract information explicitly mentioned in the text, do not add additional content-- Maintain objectivity and accuracy-- Leave blank if information is missing, do not fabricate--### Source text:-"""---class RegulationProfile(AutoModel[RegulationInfo]):- """- Applicable documents: Company internal management systems, administrative regulations, operation manuals, compliance guidelines-- Function introduction:- Extract the name, version, scope, effective date, and core purpose of a regulation. Suitable for regulation overview, version management, etc.-- Example:- >>> template = RegulationProfile(llm_client=llm, embedder=embedder)- >>> template.feed_text("Universe First Slacker Company Employee Attendance Management System...")- >>> print(template.data.title)- >>> print(template.data.effectiveDate)- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- Initialize regulation profile template.-- Args:- llm_client: LLM client for knowledge extraction- embedder: Embedding model for semantic search- max_workers: Maximum number of worker threads, default: 10- verbose: Whether to output detailed logs, default: False- **kwargs: Other technical parameters, passed to base class- """- super().__init__(- data_schema=RegulationInfo,- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- max_workers=max_workers,- verbose=verbose,- **kwargs,- )-- def show(- self,- *,- top_k: int = 3,- ):- """- Display regulation profile.-- Args:- top_k: Number of items to use for chat, default: 3- """- def label_extractor(item: RegulationInfo) -> str:- if item.version:- return f"{item.title} (v{item.version})"- return item.title-- super().show(- label_extractor=label_extractor,- top_k=top_k,- )diff --git a/hyperextract/templates/en/general/social_network.py b/hyperextract/templates/en/general/social_network.pydeleted file mode 100644index 38cf4e3..0000000--- a/hyperextract/templates/en/general/social_network.py+++ /dev/null@@ -1,161 +0,0 @@-"""Social Network Graph - Focus on extracting interpersonal relationships, interactions, and organizational affiliations.--Suitable for biography analysis, character setting research, etc.-"""--from typing import Any-from pydantic import BaseModel, Field-from langchain_core.language_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoGraph---class PersonNode(BaseModel):- """Person/organization node"""-- name: str = Field(description="Name")- type: str = Field(description="Node type: Person, Organization, Institution, Other")- description: str = Field(description="Brief description", default="")- role: str = Field(description="Role/identity", default="")---class SocialRelation(BaseModel):- """Social relationship edge"""-- source: str = Field(description="Source node")- target: str = Field(description="Target node")- relationType: str = Field(- description="Relationship type: Family, Friend, Colleague, TeacherStudent, SupervisorSubordinate, Collaboration, Competition, Affiliation, Other"- )- details: str = Field(description="Detailed relationship explanation", default="")---_PROMPT = """## Role and Task-You are a professional social relationship analysis expert. Please extract people, organizations, and their mutual relationships from the text.--## Core Concept Definitions-- **Node**: person or organization unit-- **Edge**: social relationship between people/organizations--## Extraction Rules-### Node Extraction Rules-1. Extract all people, organizations, institutions-2. Assign a type to each node--### Edge Extraction Rules-1. Only create edges from extracted nodes-2. Each edge must connect extracted nodes--### Source text:-"""--_NODE_PROMPT = """## Role and Task-Please extract people and organizations as nodes from the text.--## Core Concept Definitions-- **Node**: person or organization unit--## Extraction Rules-1. Extract all people, organizations, institutions-2. Assign a type to each node--### Source text:-"""--_EDGE_PROMPT = """## Role and Task-Please extract social relationships between nodes from the known node list.--## Core Concept Definitions-- **Edge**: social relationship between people/organizations--## Constraints-1. Only extract edges from the known node list-2. Do not create unlisted nodes-"""---class SocialNetwork(AutoGraph[PersonNode, SocialRelation]):- """- Applicable Documents: Biographies, news articles, literary works, organizational documents-- Function Introduction:- Extract people, organizations, and their mutual relationships to build a social network graph.- Suitable for biography analysis, character setting research, organizational structure analysis, etc.-- Example:- >>> template = SocialNetwork(llm_client=llm, embedder=embedder)- >>> template.feed_text("John works at ABC Company as a manager...")- >>> template.show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- extraction_mode: str = "two_stage",- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- Initialize the social network graph template.-- Args:- llm_client: LLM client for knowledge extraction- embedder: Embedding model for semantic retrieval- extraction_mode: Extraction mode, optional "one_stage" (extract nodes and edges simultaneously)- or "two_stage" (extract nodes first, then edges), default is "two_stage"- max_workers: Maximum worker threads, default is 10- verbose: Whether to output detailed logs, default is False- **kwargs: Other technical parameters, passed to the base class- """- super().__init__(- node_schema=PersonNode,- edge_schema=SocialRelation,- node_key_extractor=lambda x: x.name,- edge_key_extractor=lambda x: f"{x.source}|{x.relationType}|{x.target}",- nodes_in_edge_extractor=lambda x: (x.source, x.target),- llm_client=llm_client,- embedder=embedder,- extraction_mode=extraction_mode,- max_workers=max_workers,- verbose=verbose,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- **kwargs,- )-- def show(- self,- *,- top_k_nodes_for_search: int = 3,- top_k_edges_for_search: int = 3,- top_k_nodes_for_chat: int = 3,- top_k_edges_for_chat: int = 3,- ):- """- Display the social network graph.-- Args:- top_k_nodes_for_search: Number of nodes returned by semantic search, default is 3- top_k_edges_for_search: Number of edges returned by semantic search, default is 3- top_k_nodes_for_chat: Number of nodes used for Q&A, default is 3- top_k_edges_for_chat: Number of edges used for Q&A, default is 3- """-- def node_label_extractor(node: PersonNode) -> str:- return f"{node.name} ({node.type})"-- def edge_label_extractor(edge: SocialRelation) -> str:- return edge.relationType-- super().show(- node_label_extractor=node_label_extractor,- edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_nodes_for_search,- top_k_edges_for_search=top_k_edges_for_search,- top_k_nodes_for_chat=top_k_nodes_for_chat,- top_k_edges_for_chat=top_k_edges_for_chat,- )diff --git a/hyperextract/templates/zh/INSTRUCTION.md b/hyperextract/templates/zh/INSTRUCTION.mdindex 91f4206..00e33aa 100644--- a/hyperextract/templates/zh/INSTRUCTION.md+++ b/hyperextract/templates/zh/INSTRUCTION.md@@ -181,7 +181,6 @@ class FinancialRelation(BaseModel):**图类型(AutoGraph/AutoHypergraph 等)必须遵循以下前置结构**:-```## 角色与任务你是一位专业的 xxx 专家,请从文本中提取 xxx...@@ -205,9 +204,43 @@ class FinancialRelation(BaseModel):- 金融领域:专业术语保持原文表述- 医学领域:专业缩写保持原文+### 特殊占位符(必须)+**每个 Prompt 都必须包含特殊占位符**,用于接收待提取的文本:++- **_PROMPT / _NODE_PROMPT**:必须包含 `{source_text}` 占位符+ ```python+ ## 源文本:+ {source_text}+ ```++- **_EDGE_PROMPT**:以 AutoGraph/AutoHypergraph 为例,必须包含 `{known_nodes}` 和 `{source_text}` 占位符。对于时空图类型,还会额外包含 `{observation_time}` 或 `{observation_location}` 占位符(详见下方表格)。+ ```python+ ## 已知实体+ {known_nodes}++ ## 源文本:+ {source_text}+ ```++#### 各 AutoType 支持的占位符++| AutoType | 节点提取 | 边提取 |+|----------|---------|--------|+| `AutoModel` / `AutoList` / `AutoSet` | `{source_text}` | - |+| `AutoGraph` / `AutoHypergraph` | `{source_text}` | `{source_text}`, `{known_nodes}` |+| `AutoTemporalGraph` | `{source_text}` | `{source_text}`, `{known_nodes}`, `{observation_time}` |+| `AutoSpatialGraph` | `{source_text}` | `{source_text}`, `{known_nodes}`, `{observation_location}` |+| `AutoSpatioTemporalGraph` | `{source_text}` | `{source_text}`, `{known_nodes}`, `{observation_time}`, `{observation_location}` |++#### 占位符说明++- **`{source_text}`**: 待分析的原始文本(必填)+- **`{known_nodes}`**: 两阶段提取模式下,已知节点列表(用于边提取)+- **`{observation_time}`**: 观测时间,用于解析相对时间表达(如"去年"、"上个月")+- **`{observation_location}`**: 观测位置,用于解析相对位置表达(如"这里"、"附近")+### 时空解析规则(仅时空图类型需要)- 时间/位置解析规则...-```**为什么需要概念定义?**- 让大模型先理解要提取的"是什么",再告诉它"怎么提取"@@ -221,24 +254,6 @@ class FinancialRelation(BaseModel):### 4.4 各 AutoType 的核心概念定义模板-#### AutoModel-```-## 核心概念定义-- **对象 (Object)**:从文本中提取的单一结构化对象,包含多个字段-```--#### AutoList-```-## 核心概念定义-- **条目 (Item)**:从文本中提取的重复模式实例-```--#### AutoSet-```-## 核心概念定义-- **元素 (Element)**:具有唯一键的知识单元,用于累积信息-```-#### AutoGraph```## 核心概念定义@@ -374,7 +389,8 @@ _NODE_PROMPT = """## 角色与任务1. 每个节点只能对应一个独立的实体,禁止将多个实体合并为一个节点2. 实体名称与原文保持一致-### 源文本:+## 待分析文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -398,6 +414,12 @@ _EDGE_PROMPT = """## 角色与任务2. 精确时间 → 保持原样3. 时间缺失 → 留空++## 已知实体列表+{known_nodes}++## 待分析文本+{source_text}"""_PROMPT = """## 角色与任务@@ -424,7 +446,8 @@ _PROMPT = """## 角色与任务2. 精确时间 → 保持原样3. 时间缺失 → 留空-### 源文本:+## 待分析文本:+{source_text}"""# ==============================================================================diff --git a/hyperextract/templates/zh/agriculture/amendment_plan.py b/hyperextract/templates/zh/agriculture/amendment_plan.pyindex b77e4be..465f094 100644--- a/hyperextract/templates/zh/agriculture/amendment_plan.py+++ b/hyperextract/templates/zh/agriculture/amendment_plan.py@@ -51,7 +51,8 @@ _PROMPT = """## 角色与任务- 改良措施:如施用生石灰、增施有机肥、施用复合肥等- 预期目标:如pH提高至6.0、有机质提升至22g/kg等-### 源文本:+## 土壤改良方案报告:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -71,7 +72,8 @@ _NODE_PROMPT = """## 角色与任务- 改良措施:针对问题采取的措施,如施用生石灰、增施有机肥- 预期目标:改良后达到的目标,如pH提高至6.0、产量提升10%-### 源文本:+## 土壤改良方案报告:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -90,6 +92,11 @@ _EDGE_PROMPT = """## 角色与任务- 关系类型"针对":表示改良措施针对某个限制因子- 关系类型"达成":表示预期目标与改良措施的关联+## 已知节点+{known_nodes}++## 土壤改良方案报告:+{source_text}"""diff --git a/hyperextract/templates/zh/agriculture/crop_growth_cycle.py b/hyperextract/templates/zh/agriculture/crop_growth_cycle.pyindex 85f5866..d2443b5 100644--- a/hyperextract/templates/zh/agriculture/crop_growth_cycle.py+++ b/hyperextract/templates/zh/agriculture/crop_growth_cycle.py@@ -66,7 +66,8 @@ _PROMPT = """## 角色与任务- "移栽后5-7天" → 相对于移栽期的时间偏移4. 时间缺失 → 留空,不要猜测-### 源文本:+## 农业技术手册:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -85,7 +86,8 @@ _NODE_PROMPT = """## 角色与任务- 农事操作:如苗床准备、种子处理、移栽、施肥、病虫害防治- 环境条件:如温度、湿度、光照、水分要求-### 源文本:+## 农业技术手册:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -123,6 +125,11 @@ _EDGE_PROMPT = """## 角色与任务- "移栽后5-7天" → 相对于移栽期的时间偏移4. 时间缺失 → 留空,不要猜测+# 已知农业实体列表+{known_nodes}++## 农业技术手册:+{source_text}"""diff --git a/hyperextract/templates/zh/agriculture/field_observation_list.py b/hyperextract/templates/zh/agriculture/field_observation_list.pyindex 8bbbaaf..10dec47 100644--- a/hyperextract/templates/zh/agriculture/field_observation_list.py+++ b/hyperextract/templates/zh/agriculture/field_observation_list.py@@ -40,7 +40,8 @@ _PROMPT = """## 角色与任务- 问题类型:杂草、虫害、病害、生长异常、肥害、药害- 严重等级:轻微(可忽略或轻微影响)、中等(需要关注或部分影响)、严重(必须处理或严重影响)-### 源文本:+## 巡田报告:+{source_text}"""diff --git a/hyperextract/templates/zh/agriculture/pest_control_hypergraph.py b/hyperextract/templates/zh/agriculture/pest_control_hypergraph.pyindex 790f6d7..6c027a5 100644--- a/hyperextract/templates/zh/agriculture/pest_control_hypergraph.py+++ b/hyperextract/templates/zh/agriculture/pest_control_hypergraph.py@@ -52,7 +52,8 @@ _PROMPT = """## 角色与任务- 药剂名称:25%噻嗪酮可湿性粉剂、20%氯虫苯甲酰胺悬浮剂等- 安全间隔期:最后一次施药至收获的天数-### 源文本:+## 农业技术手册:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -72,7 +73,8 @@ _NODE_PROMPT = """## 角色与任务- 作物:如水稻、小麦、玉米- 生长阶段:如播种期、分蘖期、孕穗期、灌浆期-### 源文本:+## 农业技术手册:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -85,7 +87,7 @@ _EDGE_PROMPT = """## 角色与任务## 提取规则### 核心约束1. 超边连接作物、生长阶段、病虫害、药剂等多类实体-2. 仅从已知实体列表中选择参与者,不要创建未列出的实体+2. 仅从已知农业实体列表中选择参与者,不要创建未列出的实体3. 每条超边必须包含作物、生长阶段、病虫害、药剂、剂量、安全间隔期### 领域特定规则@@ -93,6 +95,11 @@ _EDGE_PROMPT = """## 角色与任务- 病虫害名称保持原文- 药剂名称保持原文,包括商品名和有效成分+## 已知农业实体列表+{known_nodes}++## 农业技术手册:+{source_text}"""diff --git a/hyperextract/templates/zh/agriculture/soil_nutrient_model.py b/hyperextract/templates/zh/agriculture/soil_nutrient_model.pyindex 0f298eb..d1f65f4 100644--- a/hyperextract/templates/zh/agriculture/soil_nutrient_model.py+++ b/hyperextract/templates/zh/agriculture/soil_nutrient_model.py@@ -54,7 +54,8 @@ _PROMPT = """## 角色与任务- 丰缺等级:缺乏、偏低、适宜、丰富、极丰富- pH等级:酸性(<6.0)、弱酸性(6.0-6.5)、中性(6.5-7.0)、弱碱性(7.0-7.5)、碱性(>7.5)-### 源文本:+## 土壤检测报告:+{source_text}"""diff --git a/hyperextract/templates/zh/biology/binding_site_model.py b/hyperextract/templates/zh/biology/binding_site_model.pyindex 09e44c4..c0c0f48 100644--- a/hyperextract/templates/zh/biology/binding_site_model.py+++ b/hyperextract/templates/zh/biology/binding_site_model.py@@ -39,9 +39,6 @@ class BindingSite(BaseModel):_PROMPT = """## 角色与任务你是一位专业的结构生物学专家,请从文本中提取蛋白质的关键位点信息。-## 核心概念定义-- **对象 (Object)**:从文本中提取的单一结构化对象,包含蛋白质结合位点的详细信息-## 提取规则### 核心约束1. 识别文本中描述的核心蛋白质及其位点@@ -54,7 +51,8 @@ _PROMPT = """## 角色与任务- 位点类型:活性位点(直接参与催化)、结合位点(结合底物或配体)、修饰位点(可被修饰)- 化学性质:疏水、亲水、极性、带电荷等-### 源文本:+## 蛋白质结构描述源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/biology/biochemical_reaction_hypergraph.py b/hyperextract/templates/zh/biology/biochemical_reaction_hypergraph.pyindex c59ef5a..8328d62 100644--- a/hyperextract/templates/zh/biology/biochemical_reaction_hypergraph.py+++ b/hyperextract/templates/zh/biology/biochemical_reaction_hypergraph.py@@ -29,7 +29,7 @@ class BiochemicalReactionEdge(BaseModel):_PROMPT = """## 角色与任务-你是一位专业的生物化学专家,请从文本中提取生化分子及其反应关系。+你是一位专业的生物化学专家,请从代谢通路文献中提取生化分子及其反应关系。## 核心概念定义- **节点 (Node)**:从文档中提取的生化分子实体@@ -49,11 +49,12 @@ _PROMPT = """## 角色与任务- 反应类型:水解、氧化还原、转移、裂解、合成、异构- 反应方向:正向、逆向、可逆-### 源文本:+## 代谢通路文献:+{source_text}"""_NODE_PROMPT = """## 角色与任务-你是一位专业的生物化学专家,请从文本中提取所有生化分子(酶、底物、产物、辅因子)作为节点。+你是一位专业的生物化学专家,请从“代谢通路文献”中提取所有生化分子(酶、底物、产物、辅因子)作为节点。## 核心概念定义- **节点 (Node)**:从文档中提取的生化分子实体@@ -71,7 +72,8 @@ _NODE_PROMPT = """## 角色与任务- 辅因子:协助酶催化的分子,如NAD+、ATP、Mg2+- 分子式使用标准化学式-### 源文本:+## 代谢通路文献:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -92,6 +94,11 @@ _EDGE_PROMPT = """## 角色与任务- 反应方向:正向、逆向、可逆- 格式:{酶 + 底物A + 底物B → 产物C + 产物D}+## 已知分子列表:+{known_nodes}++## 代谢通路文献:+{source_text}"""diff --git a/hyperextract/templates/zh/biology/biodiversity_registry.py b/hyperextract/templates/zh/biology/biodiversity_registry.pyindex 27c8bac..e727dd7 100644--- a/hyperextract/templates/zh/biology/biodiversity_registry.py+++ b/hyperextract/templates/zh/biology/biodiversity_registry.py@@ -22,10 +22,7 @@ class SpeciesRecord(BaseModel):_PROMPT = """## 角色与任务-你是一位专业的生态学专家,请从文本中提取所有物种观测记录,构建物种名录。--## 核心概念定义-- **元素 (Element)**:具有唯一键的知识单元,用于累积信息+你是一位专业的生态学专家,请从“调查报告”中提取所有物种观测记录,构建物种名录。## 提取规则### 核心约束@@ -38,7 +35,8 @@ _PROMPT = """## 角色与任务- 类别:脊椎动物(鱼类、两栖类、爬行类、鸟类、哺乳动物)、无脊椎动物(昆虫、螺类、蚌类等)、植物(高等植物、藻类、苔藓)- 种群数量:使用原文中的数量描述,如"约120只"、"约850尾"-### 源文本:+## 调查报告:+{source_text}"""diff --git a/hyperextract/templates/zh/biology/phylogenetic_relation_graph.py b/hyperextract/templates/zh/biology/phylogenetic_relation_graph.pyindex 9de1b52..5d936d3 100644--- a/hyperextract/templates/zh/biology/phylogenetic_relation_graph.py+++ b/hyperextract/templates/zh/biology/phylogenetic_relation_graph.py@@ -28,7 +28,7 @@ class PhylogeneticRelation(BaseModel):_PROMPT = """## 角色与任务-你是一位专业的进化生物学专家,请从文本中提取物种或分类单元及其系统发育关系。+你是一位专业的进化生物学专家,请从“生物学文献”中提取物种或分类单元及其系统发育关系。## 核心概念定义- **节点 (Node)**:从文档中提取的物种或分类单元实体@@ -48,11 +48,13 @@ _PROMPT = """## 角色与任务- 演化距离可用分支时间(百万年)或序列差异度表示- 分支点信息包括共同的祖先和分化时间-### 源文本:+## 生物学文献:+{source_text}"""_NODE_PROMPT = """## 角色与任务-你是一位专业的进化生物学专家,请从文本中提取所有物种或分类单元作为系统发育节点。+你是一位专业的进化生物学专家,请从“生物学文献”中提取所有物种或分类单元作为系统发育节点。+## 核心概念定义- **节点 (Node)**:从文档中提取的物种或分类单元实体@@ -67,11 +69,12 @@ _NODE_PROMPT = """## 角色与任务- 分类等级:界(kingdom)、门(phylum)、纲(class)、目(order)、科(family)、属(genus)、种(species)- 系统发育关系包括:亲缘关系、演化距离、分支、姐妹群关系-### 源文本:+### 生物学文献:+{source_text}"""_EDGE_PROMPT = """## 角色与任务-请从已知物种或分类单元列表中提取它们之间的系统发育关系。+请从“生物学文献”中提取它们之间的系统发育关系。## 核心概念定义- **节点 (Node)**:从文档中提取的物种或分类单元实体@@ -79,7 +82,7 @@ _EDGE_PROMPT = """## 角色与任务## 提取规则### 核心约束-1. 仅从已知列表中提取边,不要创建未列出的物种+1. 仅从已知的实体中提取边,不要创建未列出的物种2. 关系描述应与原文保持一致### 领域特定规则@@ -87,6 +90,11 @@ _EDGE_PROMPT = """## 角色与任务- 演化距离可用分支时间(百万年)或序列差异度表示- 分支点信息包括共同的祖先和分化时间+## 已知物种或分类单元实体:+{known_entities}++## 生物学文献:+{source_text}"""diff --git a/hyperextract/templates/zh/biology/protein_complex_map.py b/hyperextract/templates/zh/biology/protein_complex_map.pyindex 039a4a7..22b7cf4 100644--- a/hyperextract/templates/zh/biology/protein_complex_map.py+++ b/hyperextract/templates/zh/biology/protein_complex_map.py@@ -27,7 +27,7 @@ class ProteinComplexEdge(BaseModel):_PROMPT = """## 角色与任务-你是一位专业的结构生物学专家,请从文本中提取蛋白质及其复合物组成关系。+你是一位专业的结构生物学专家,请从“蛋白质结构文献”中提取蛋白质及其复合物组成关系。## 核心概念定义- **节点 (Node)**:从文档中提取的蛋白质实体@@ -46,7 +46,8 @@ _PROMPT = """## 角色与任务- G蛋白异源三聚体:包括Gα、Gβ、Gγ三个亚基- 复合物类型:G蛋白异源三聚体、信号转导复合物、酶复合物等-### 源文本:+## 蛋白质结构文献:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -67,7 +68,8 @@ _NODE_PROMPT = """## 角色与任务- 效应器:如腺苷酸环化酶(AC)- 基因名称使用标准缩写-### 源文本:+## 蛋白质结构文献:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -79,14 +81,19 @@ _EDGE_PROMPT = """## 角色与任务## 提取规则### 核心约束-1. 超边连接2个或多个蛋白质节点-2. 仅从已知蛋白质列表中选择参与者,不要创建未列出的蛋白质+1. 超边连接2个或多个蛋白质实体节点+2. 仅从已知蛋白质实体列表中选择参与者,不要创建未列出的蛋白质实体3. 每条超边必须至少有2个成员### 领域特定规则- 复合物类型:G蛋白异源三聚体、信号转导复合物、酶复合物等- 组装信息:亚基之间的相互作用关系+## 已知蛋白质实体列表:+{known_nodes}++## 蛋白质结构文献:+{source_text}"""diff --git a/hyperextract/templates/zh/biology/regulatory_network.py b/hyperextract/templates/zh/biology/regulatory_network.pyindex d50f4df..ea31fbf 100644--- a/hyperextract/templates/zh/biology/regulatory_network.py+++ b/hyperextract/templates/zh/biology/regulatory_network.py@@ -48,7 +48,8 @@ _PROMPT = """## 角色与任务- 调控类型:激活(促进表达)、抑制(阻止表达)、协同激活- 调控机制:结合启动子、组蛋白修饰、DNA甲基化等-### 源文本:+## 生物学文献:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -68,7 +69,8 @@ _NODE_PROMPT = """## 角色与任务- 启动子:基因转录起始区域- 基因符号使用标准缩写,如HK2(己糖激酶2)、PFKFB3-### 源文本:+## 生物学文献:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -87,6 +89,11 @@ _EDGE_PROMPT = """## 角色与任务- 调控类型:激活(促进表达)、抑制(阻止表达)、协同激活- 调控机制:结合启动子、组蛋白修饰、DNA甲基化等+## 已知基因实体列表:+{known_nodes}++## 生物学文献:+{source_text}"""diff --git a/hyperextract/templates/zh/biology/species_interaction_web.py b/hyperextract/templates/zh/biology/species_interaction_web.pyindex d5beae9..d40c967 100644--- a/hyperextract/templates/zh/biology/species_interaction_web.py+++ b/hyperextract/templates/zh/biology/species_interaction_web.py@@ -49,7 +49,8 @@ _PROMPT = """## 角色与任务- 竞争关系:竞争同一资源的物种之间- 互利共生:双方都受益的关系-### 源文本:+## 生态学文献:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -69,7 +70,8 @@ _NODE_PROMPT = """## 角色与任务- 生态学术语保持原文,如物种名称(鲢鱼、绿藻)、生态关系(捕食、竞争)- 注意区分不同营养级的物种-### 源文本:+## 生态学文献:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -91,10 +93,11 @@ _EDGE_PROMPT = """## 角色与任务- 竞争关系:竞争同一资源的物种之间- 互利共生:双方都受益的关系-### 已知物种列表:-{node_context}+## 已知物种列表:+{known_nodes}-### 源文本:+## 生态学文献:+{source_text}"""diff --git a/hyperextract/templates/zh/biology/taxonomic_tree.py b/hyperextract/templates/zh/biology/taxonomic_tree.pyindex 5b205d4..5b15467 100644--- a/hyperextract/templates/zh/biology/taxonomic_tree.py+++ b/hyperextract/templates/zh/biology/taxonomic_tree.py@@ -26,7 +26,7 @@ class TaxonomicRelation(BaseModel):_PROMPT = """## 角色与任务-你是一位专业的生物分类学专家,请从文本中提取分类单元及其层级包含关系。+你是一位专业的生物分类学专家,请从“生物学文献”中提取分类单元及其层级包含关系。## 核心概念定义- **节点 (Node)**:从文档中提取的分类单元实体@@ -46,7 +46,8 @@ _PROMPT = """## 角色与任务- 拉丁学名保持原文格式- 关系类型统一为"包含于"-### 源文本:+## 生物学文献:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -66,7 +67,8 @@ _NODE_PROMPT = """## 角色与任务- 拉丁学名保持原文格式(属名首字母大写,种名小写斜体)- 常见的分类等级英文缩写:Kingdom, Phylum, Class, Order, Family, Genus, Species-### 源文本:+### 生物学文献:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -86,6 +88,11 @@ _EDGE_PROMPT = """## 角色与任务- 关系类型统一为"包含于"- 提取完整的分类路径信息+## 已知分类单元列表:+{known_nodes}++## 生物学文献:+{source_text}"""diff --git a/hyperextract/templates/zh/finance/call_sentiment_hypergraph.py b/hyperextract/templates/zh/finance/call_sentiment_hypergraph.pyindex b1cea71..2c0516f 100644--- a/hyperextract/templates/zh/finance/call_sentiment_hypergraph.py+++ b/hyperextract/templates/zh/finance/call_sentiment_hypergraph.py@@ -72,7 +72,8 @@ _PROMPT = """## 角色与任务- 超边连接 主题 + 发言人 + 情绪 + 驱动因素- 记录与前一季度基调的变化-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -91,7 +92,8 @@ _NODE_PROMPT = """## 角色与任务- 识别发言人(分析师、管理层)- 识别情绪标签和驱动因素-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -112,6 +114,11 @@ _EDGE_PROMPT = """## 角色与任务- 捕捉支撑证据- 记录与前几个季度的基调变化+## 已知实体列表:+{known_nodes}++## 源文本:+{source_text}"""# ==============================================================================diff --git a/hyperextract/templates/zh/finance/company_history_timeline.py b/hyperextract/templates/zh/finance/company_history_timeline.pyindex 0f9ed2e..3269363 100644--- a/hyperextract/templates/zh/finance/company_history_timeline.py+++ b/hyperextract/templates/zh/finance/company_history_timeline.py@@ -88,7 +88,8 @@ _PROMPT = """## 角色与任务3. 缺失时间:留空-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -107,13 +108,15 @@ _NODE_PROMPT = """## 角色与任务- 创始人:公司的创始团队成员- 投资机构:VC、PE等投资方-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务请从已知实体列表中提取公司里程碑事件。## 核心概念定义+- **节点 (Node)**:与公司历史相关的实体- **边 (Edge)**:公司里程碑事件- **时间**:事件发生的时间@@ -139,6 +142,12 @@ _EDGE_PROMPT = """## 角色与任务5. 如果多个主体参与同一事件,应为每个主体创建独立的边- 例如:"A和B共同创立了C" → 创建两条边:(A, 创立, C) 和 (B, 创立, C)- 例如:"红杉资本、IDG投资了该公司" → 创建两条边:(红杉资本, 投资, 该公司) 和 (IDG, 投资, 该公司)++## 已知实体列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/finance/discussion_graph.py b/hyperextract/templates/zh/finance/discussion_graph.pyindex 42bbf70..d66674e 100644--- a/hyperextract/templates/zh/finance/discussion_graph.py+++ b/hyperextract/templates/zh/finance/discussion_graph.py@@ -53,7 +53,8 @@ _PROMPT = """## 角色与任务- 参会人员 ↔ 其他实体:提问关于、回答关于、看好、看衰、担忧、质疑、主导、负责等- 其他实体之间:竞争、合作、增长、下降等-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -71,7 +72,8 @@ _NODE_PROMPT = """## 角色与任务- 参会人员:分析师、管理层(CEO、CFO等)- 公司、产品、指标、行业-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -96,7 +98,11 @@ _EDGE_PROMPT = """## 角色与任务- (CFO, 澄清, 毛利率)- (实体A, 竞争, 实体B)+## 已知实体列表:+{known_nodes}+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/finance/earnings_call_summary.py b/hyperextract/templates/zh/finance/earnings_call_summary.pyindex 345b5fc..083c43b 100644--- a/hyperextract/templates/zh/finance/earnings_call_summary.py+++ b/hyperextract/templates/zh/finance/earnings_call_summary.py@@ -89,7 +89,8 @@ _PROMPT = """## 角色与任务- 列出准备发言中的核心亮点和问答环节中的主要关切- 识别管理层强调的战略重点-### 源文本:+## 源文本:+{source_text}"""# ==============================================================================diff --git a/hyperextract/templates/zh/finance/factor_influence_hypergraph.py b/hyperextract/templates/zh/finance/factor_influence_hypergraph.pyindex c423a72..c4c284e 100644--- a/hyperextract/templates/zh/finance/factor_influence_hypergraph.py+++ b/hyperextract/templates/zh/finance/factor_influence_hypergraph.py@@ -55,7 +55,8 @@ _PROMPT = """## 角色与任务- 价格类:价格上涨、股价下跌、成本上升等- 需求类:需求旺盛、需求疲软、订单增加等-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -75,7 +76,8 @@ _NODE_PROMPT = """## 角色与任务- 公司:营收、ROE、PE等- 市场情绪:资金流向、风险偏好等-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -98,10 +100,11 @@ _EDGE_PROMPT = """## 角色与任务- 价格类:价格上涨、股价下跌、成本上升- 需求类:需求旺盛、需求疲软-### 已知因子列表:-{node_context}+### 已知实体列表:+{known_nodes}-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/finance/filing_financial_snapshot.py b/hyperextract/templates/zh/finance/filing_financial_snapshot.pyindex eafee4b..14f02f8 100644--- a/hyperextract/templates/zh/finance/filing_financial_snapshot.py+++ b/hyperextract/templates/zh/finance/filing_financial_snapshot.py@@ -72,7 +72,8 @@ _PROMPT = """## 角色与任务- 捕获申报文件中明确列出的关键财务比率- 使用表格中的精确数据;除非文件明确给出,否则不要计算衍生数值-### 源文本:+## 源文本:+{source_text}"""# ==============================================================================diff --git a/hyperextract/templates/zh/finance/filing_risk_factor_set.py b/hyperextract/templates/zh/finance/filing_risk_factor_set.pyindex 2ec068e..d678d92 100644--- a/hyperextract/templates/zh/finance/filing_risk_factor_set.py+++ b/hyperextract/templates/zh/finance/filing_risk_factor_set.py@@ -65,7 +65,8 @@ _PROMPT = """## 角色与任务- **完整性**: 提取每一个不同的风险因素,即使只是简要提及- **累积合并**: 如果同一风险在不同章节中出现了更多细节,则合并相关信息-### 源文本:+## 源文本:+{source_text}"""# ==============================================================================diff --git a/hyperextract/templates/zh/finance/financial_data_temporal_graph.py b/hyperextract/templates/zh/finance/financial_data_temporal_graph.pyindex d144472..d249ce4 100644--- a/hyperextract/templates/zh/finance/financial_data_temporal_graph.py+++ b/hyperextract/templates/zh/finance/financial_data_temporal_graph.py@@ -95,7 +95,8 @@ _PROMPT = """## 角色与任务2. 精确时间 → 保持原样3. 时间缺失 → 留空,不要猜测-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色@@ -124,6 +125,7 @@ _NODE_PROMPT = """## 角色- 避免提取过于通用或抽象的概念## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色@@ -141,15 +143,11 @@ _EDGE_PROMPT = """## 角色- "贡献":某分部贡献了某指标的多少(如 "华东区贡献收入20%")- "影响":外部因素影响了某指标(如 "汇率影响收入-5%")-## 输出格式-每条边必须包含:-- source: 主体(节点名称)-- target: 目标(节点名称)-- relationship: 关系类型-- value: 数值(必须)-- fiscal_period: 财务期间+## 已知实体列表:+{known_nodes}## 源文本:+{source_text}"""# ==============================================================================diff --git a/hyperextract/templates/zh/finance/financial_event_causal_graph.py b/hyperextract/templates/zh/finance/financial_event_causal_graph.pyindex 5e4dba8..26aae84 100644--- a/hyperextract/templates/zh/finance/financial_event_causal_graph.py+++ b/hyperextract/templates/zh/finance/financial_event_causal_graph.py@@ -62,7 +62,8 @@ _PROMPT = """## 角色与任务- 抑制类:抑制、拖累、冲击- 影响类:利好、利空-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -80,13 +81,15 @@ _NODE_PROMPT = """## 角色与任务- 市场实体:银行、房地产、科技、消费- 经济指标:GDP、CPI、利率-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务请从已知实体列表中提取实体之间的关系。## 核心概念定义+- **节点 (Node)**:政策事件、市场实体、经济指标- **边 (Edge)**:实体之间的因果关系## 提取规则@@ -100,6 +103,11 @@ _EDGE_PROMPT = """## 角色与任务- 抑制类:抑制、拖累、冲击- 影响类:利好、利空+## 已知实体列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/finance/financial_forecast.py b/hyperextract/templates/zh/finance/financial_forecast.pyindex 708ae16..d65a988 100644--- a/hyperextract/templates/zh/finance/financial_forecast.py+++ b/hyperextract/templates/zh/finance/financial_forecast.py@@ -66,7 +66,8 @@ _PROMPT = """## 角色与任务- 在进行对比时提取一致性预期- 捕获增长率和关键假设-### 源文本:+## 源文本:+{source_text}"""# ==============================================================================diff --git a/hyperextract/templates/zh/finance/management_guidance_list.py b/hyperextract/templates/zh/finance/management_guidance_list.pyindex a8aa0c4..84368d5 100644--- a/hyperextract/templates/zh/finance/management_guidance_list.py+++ b/hyperextract/templates/zh/finance/management_guidance_list.py@@ -74,7 +74,8 @@ _PROMPT = """## 角色与任务- 保留管理层的确信程度措辞- 识别每项指引的发布者-### 源文本:+## 源文本:+{source_text}"""# ==============================================================================diff --git a/hyperextract/templates/zh/finance/market_narrative_timeline.py b/hyperextract/templates/zh/finance/market_narrative_timeline.pyindex 11b6e45..b42a8b7 100644--- a/hyperextract/templates/zh/finance/market_narrative_timeline.py+++ b/hyperextract/templates/zh/finance/market_narrative_timeline.py@@ -72,7 +72,8 @@ _PROMPT = """## 角色与任务2. 精确时间 → 保持原样3. 时间缺失 → 留空-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -97,7 +98,8 @@ _NODE_PROMPT = """## 角色与任务- 政策预期:对政策走向的判断- 经济判断:对经济形势的看法-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -129,6 +131,11 @@ _EDGE_PROMPT = """## 角色与任务2. 精确时间 → 保持原样3. 时间缺失 → 留空+## 已知叙事列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/finance/market_sentiment_model.py b/hyperextract/templates/zh/finance/market_sentiment_model.pyindex 40e624d..614baa5 100644--- a/hyperextract/templates/zh/finance/market_sentiment_model.py+++ b/hyperextract/templates/zh/finance/market_sentiment_model.py@@ -82,7 +82,8 @@ _PROMPT = """## 角色与任务- 评估预期市场影响和时间范围- 记录任何逆向或不同意见的观点-### 源文本:+## 源文本:+{source_text}"""# ==============================================================================diff --git a/hyperextract/templates/zh/finance/material_event_timeline.py b/hyperextract/templates/zh/finance/material_event_timeline.pyindex edffe3e..7d52f64 100644--- a/hyperextract/templates/zh/finance/material_event_timeline.py+++ b/hyperextract/templates/zh/finance/material_event_timeline.py@@ -90,7 +90,8 @@ _PROMPT = """## 角色与任务2. 精确时间 → 保持原样3. 时间缺失 → 留空,不要猜测-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -109,7 +110,8 @@ _NODE_PROMPT = """## 角色与任务- 按类型对每个实体进行分类- 捕获角色描述-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -141,7 +143,11 @@ _EDGE_PROMPT = """## 角色与任务2. 精确时间 → 保持原样3. 时间缺失 → 留空,不要猜测-### 源文本:+## 已知事件主体列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/finance/mda_narrative_graph.py b/hyperextract/templates/zh/finance/mda_narrative_graph.pyindex e1a0383..dd0c7e9 100644--- a/hyperextract/templates/zh/finance/mda_narrative_graph.py+++ b/hyperextract/templates/zh/finance/mda_narrative_graph.py@@ -68,7 +68,8 @@ _PROMPT = """## 角色与任务- 在有说明时捕获量化影响- 保留管理层的归因表述语言-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -87,7 +88,8 @@ _NODE_PROMPT = """## 角色与任务- 识别财务结果(营收变化、利润率变动、现金流影响)- 按类型对每个因素进行分类-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -108,7 +110,11 @@ _EDGE_PROMPT = """## 角色与任务- 在可获取时提取量化幅度- 捕获管理层自身的因果解释-### 源文本:+## 已知实体列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/finance/multi_source_sentiment_hypergraph.py b/hyperextract/templates/zh/finance/multi_source_sentiment_hypergraph.pyindex a9d6f62..2c032c3 100644--- a/hyperextract/templates/zh/finance/multi_source_sentiment_hypergraph.py+++ b/hyperextract/templates/zh/finance/multi_source_sentiment_hypergraph.py@@ -83,7 +83,8 @@ _PROMPT = """## 角色与任务- 评估各来源之间的一致性- 记录冲突观点和信号强度-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -102,7 +103,8 @@ _NODE_PROMPT = """## 角色与任务- 识别受影响实体(股票代码、板块、指数)- 捕捉每个来源的个别情绪-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -123,6 +125,11 @@ _EDGE_PROMPT = """## 角色与任务- 评估交易用途的信号强度- 记录任何冲突观点+## 已知实体列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/finance/proceeds_usage.py b/hyperextract/templates/zh/finance/proceeds_usage.pyindex 0b13d5e..310fb3b 100644--- a/hyperextract/templates/zh/finance/proceeds_usage.py+++ b/hyperextract/templates/zh/finance/proceeds_usage.py@@ -59,7 +59,8 @@ _PROMPT = """## 角色与任务- 提取资金使用时间表(如有说明)- 保留资金使用方式的详细描述-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/finance/research_note_summary.py b/hyperextract/templates/zh/finance/research_note_summary.pyindex dcc9713..d2685f1 100644--- a/hyperextract/templates/zh/finance/research_note_summary.py+++ b/hyperextract/templates/zh/finance/research_note_summary.py@@ -79,7 +79,8 @@ _PROMPT = """## 角色与任务- 列出分析师识别的关键催化剂和风险- 在提及时提取财务预测(收入、每股收益)-### 源文本:+## 源文本:+{source_text}"""# ==============================================================================diff --git a/hyperextract/templates/zh/finance/risk_assessment.py b/hyperextract/templates/zh/finance/risk_assessment.pyindex 6e984fd..ffa46d6 100644--- a/hyperextract/templates/zh/finance/risk_assessment.py+++ b/hyperextract/templates/zh/finance/risk_assessment.py@@ -70,7 +70,8 @@ _PROMPT = """## 角色与任务- 提取发生可能性和影响严重程度- 捕获管理层提及的缓解措施-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -90,7 +91,8 @@ _NODE_PROMPT = """## 角色与任务- 识别运营结果:产能利用率、交付延迟、客户流失等- 为每个实体标注正确的类别-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -113,6 +115,11 @@ _EDGE_PROMPT = """## 角色与任务- 提取影响严重程度或量化影响- 捕获提及的缓解措施或应对策略+## 已知实体列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/finance/risk_factor_list.py b/hyperextract/templates/zh/finance/risk_factor_list.pyindex 254e641..60d62a6 100644--- a/hyperextract/templates/zh/finance/risk_factor_list.py+++ b/hyperextract/templates/zh/finance/risk_factor_list.py@@ -52,7 +52,8 @@ _PROMPT = """## 角色与任务- 在提供量化影响估算时予以捕获- 记录概率评估和时间范围-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/finance/segment_performance_list.py b/hyperextract/templates/zh/finance/segment_performance_list.pyindex c49dbe3..d6d49be 100644--- a/hyperextract/templates/zh/finance/segment_performance_list.py+++ b/hyperextract/templates/zh/finance/segment_performance_list.py@@ -56,7 +56,8 @@ _PROMPT = """## 角色与任务- 提取板块特定的关键绩效指标和度量- 保留管理层的板块评论-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/finance/shareholder_structure.py b/hyperextract/templates/zh/finance/shareholder_structure.pyindex 64a309b..7bc4f63 100644--- a/hyperextract/templates/zh/finance/shareholder_structure.py+++ b/hyperextract/templates/zh/finance/shareholder_structure.py@@ -78,7 +78,8 @@ _PROMPT = """## 角色与任务- 注意双重股权结构和投票权差异- 捕捉锁定期和 IPO 后限制条款-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -97,7 +98,8 @@ _NODE_PROMPT = """## 角色与任务- 识别发行公司本身- 按类型对每个实体进行分类-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -117,6 +119,12 @@ _EDGE_PROMPT = """## 角色与任务- 提取持股比例和股份类别- 注意投票权差异- 捕捉锁定期++## 已知股权实体列表+{known_nodes}++## 源文本:+{source_text}"""class ShareholderStructure(AutoGraph[OwnershipEntity, OwnershipEdge]):diff --git a/hyperextract/templates/zh/finance/supply_chain.py b/hyperextract/templates/zh/finance/supply_chain.pyindex 120dfc2..5affa99 100644--- a/hyperextract/templates/zh/finance/supply_chain.py+++ b/hyperextract/templates/zh/finance/supply_chain.py@@ -60,7 +60,8 @@ _PROMPT = """## 角色与任务- 提取交易类型及产品- 将依赖度、交易量及地缘政治风险汇总至 risk_assessment-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -79,7 +80,8 @@ _NODE_PROMPT = """## 角色与任务- 分类角色(客户、供应商、战略伙伴、分销商)- 记录地区及认证至 details-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -98,6 +100,11 @@ _EDGE_PROMPT = """## 角色与任务- 通过产品/服务连接实体- 综合评估依赖度、交易量及风险(关税、单一来源)+## 已知实体列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/finance/valuation_logic_map.py b/hyperextract/templates/zh/finance/valuation_logic_map.pyindex 812901d..594e5f5 100644--- a/hyperextract/templates/zh/finance/valuation_logic_map.py+++ b/hyperextract/templates/zh/finance/valuation_logic_map.py@@ -73,7 +73,8 @@ _PROMPT = """## 角色与任务- 捕获分析师在每个链接处的具体推理- 记录关系类型:驱动/支撑/确认(正面)、抑制/限制(负面)、假设/关联(中性)-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -92,7 +93,8 @@ _NODE_PROMPT = """## 角色与任务- 识别估值指标(P/E、EV/EBITDA、DCF、可比倍数)- 在提及时捕获量化值-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -112,6 +114,11 @@ _EDGE_PROMPT = """## 角色与任务- 捕获每个链接处的具体推理- 记录关系类型:驱动/支撑/确认(正面)、抑制/限制(负面)、假设/关联(中性)+## 已知估值因素列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/food/dish_review_summary.py b/hyperextract/templates/zh/food/dish_review_summary.pyindex 4244835..2d0cab3 100644--- a/hyperextract/templates/zh/food/dish_review_summary.py+++ b/hyperextract/templates/zh/food/dish_review_summary.py@@ -43,7 +43,8 @@ _PROMPT = """## 角色与任务- 推荐指数常用表达:⭐⭐⭐⭐⭐、4.5/5、强烈推荐- 价格感知常用表达:性价比极高、实惠、略贵但值-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/food/ingredient_composition_hypergraph.py b/hyperextract/templates/zh/food/ingredient_composition_hypergraph.pyindex b97cad7..e0eccaf 100644--- a/hyperextract/templates/zh/food/ingredient_composition_hypergraph.py+++ b/hyperextract/templates/zh/food/ingredient_composition_hypergraph.py@@ -63,7 +63,8 @@ _PROMPT = """## 角色与任务- 提取每个食材的用量信息- 提取配伍描述-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -80,7 +81,8 @@ _NODE_PROMPT = """## 角色与任务### 领域特定规则- 食材类别:主料、辅料、调味品-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -97,6 +99,11 @@ _EDGE_PROMPT = """## 角色与任务### 领域特定规则- 食材角色:主料、辅料、调味品+## 食材列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/food/recipe_collection.py b/hyperextract/templates/zh/food/recipe_collection.pyindex 1cf9d4a..7b7b459 100644--- a/hyperextract/templates/zh/food/recipe_collection.py+++ b/hyperextract/templates/zh/food/recipe_collection.py@@ -41,7 +41,8 @@ _PROMPT = """## 角色与任务- 菜单中常见的分类:凉菜、热菜、主食、甜品、小吃、饮品- 同一菜品在不同分类下出现时,保留所有出现过的分类-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/food/sensory_evaluation_graph.py b/hyperextract/templates/zh/food/sensory_evaluation_graph.pyindex e43f64a..322ea57 100644--- a/hyperextract/templates/zh/food/sensory_evaluation_graph.py+++ b/hyperextract/templates/zh/food/sensory_evaluation_graph.py@@ -45,7 +45,8 @@ _PROMPT = """## 角色与任务- 关系类型:具有特征(描述菜品具有某种口感/味道)、归因于(解释某种口感/味道的来源)- 节点类型:菜品、口感、味道、食材、技法-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -65,7 +66,8 @@ _NODE_PROMPT = """## 角色与任务- 味道描述词:鲜香、麻辣、酸甜、醇厚、清爽等- 技法描述词:腌制、烹煮、火候、刀工等-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -84,6 +86,11 @@ _EDGE_PROMPT = """## 角色与任务### 领域特定规则- 关系类型:具有特征(描述菜品具有某种口感/味道)、归因于(解释某种口感/味道的来源)+## 已知实体列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/food/standard_recipe_card.py b/hyperextract/templates/zh/food/standard_recipe_card.pyindex 0a8b857..df4e45f 100644--- a/hyperextract/templates/zh/food/standard_recipe_card.py+++ b/hyperextract/templates/zh/food/standard_recipe_card.py@@ -46,7 +46,8 @@ _PROMPT = """## 角色与任务- 烹饪步骤:按顺序提取,每步一个条目- TIPS:提取烹饪中的关键技巧和注意事项-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/general/clause_list.py b/hyperextract/templates/zh/general/clause_list.pyindex 4cf585e..7c854f2 100644--- a/hyperextract/templates/zh/general/clause_list.py+++ b/hyperextract/templates/zh/general/clause_list.py@@ -33,7 +33,8 @@ _PROMPT = """## 角色与任务- 不要遗漏任何条文- 保持条文的完整性-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/general/compliance_logic.py b/hyperextract/templates/zh/general/compliance_logic.pyindex 43463d6..aa9d583 100644--- a/hyperextract/templates/zh/general/compliance_logic.py+++ b/hyperextract/templates/zh/general/compliance_logic.py@@ -58,7 +58,8 @@ _PROMPT = """## 角色与任务2. 规则必须包含 ruleType、participants、action3. participants 必须严格使用已提取节点的名称-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -81,11 +82,12 @@ _NODE_PROMPT = """## 角色与任务2. 为每个要素指定类型3. 为每个要素添加简要描述(1-2句话)-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务-请从已知节点列表中提取合规规则超边。+请从已知要素列表中提取合规规则超边。## 核心概念定义- **节点 (Node)**:构成规则的基本要素,作为超边的参与者@@ -93,7 +95,7 @@ _EDGE_PROMPT = """## 角色与任务## 提取规则### 核心约束-1. participants 必须严格使用已知节点列表中的名称,不要创建新名称+1. participants 必须严格使用已知要素列表中的名称,不要创建新名称2. 规则必须包含 ruleType、participants、action3. participants 应包含涉及的主体、执行的操作、以及相关的其他要素@@ -103,6 +105,11 @@ _EDGE_PROMPT = """## 角色与任务- **允许**:允许执行的动作- **其他**:不属于上述类别的规则+## 已知要素列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/general/concept_hierarchy.py b/hyperextract/templates/zh/general/concept_hierarchy.pyindex e995abf..e1394a0 100644--- a/hyperextract/templates/zh/general/concept_hierarchy.py+++ b/hyperextract/templates/zh/general/concept_hierarchy.py@@ -50,7 +50,8 @@ _PROMPT = """## 角色与任务2. 每条边必须连接已提取的节点3. 关系描述应与原文保持一致-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -68,7 +69,8 @@ _NODE_PROMPT = """## 角色与任务1. 提取所有概念2. 为每个概念指定类型-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -83,6 +85,11 @@ _EDGE_PROMPT = """## 角色与任务1. 仅从已知概念列表中提取边,不要创建未列出的概念2. 关系描述应与原文保持一致+## 已知概念列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/general/cross_reference_net.py b/hyperextract/templates/zh/general/cross_reference_net.pyindex 632c603..5d11852 100644--- a/hyperextract/templates/zh/general/cross_reference_net.py+++ b/hyperextract/templates/zh/general/cross_reference_net.py@@ -50,7 +50,8 @@ _PROMPT = """## 角色与任务2. 每条边必须连接已提取的节点3. 关系描述应与原文保持一致-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -68,7 +69,8 @@ _NODE_PROMPT = """## 角色与任务1. 提取所有被提及的概念或条目2. 为每个节点指定类型-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -90,6 +92,11 @@ _EDGE_PROMPT = """## 角色与任务- Related:相关关系- Other:其他关系+## 已知节点列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/general/encyclopedia_item.py b/hyperextract/templates/zh/general/encyclopedia_item.pyindex 32d980b..f4faa79 100644--- a/hyperextract/templates/zh/general/encyclopedia_item.py+++ b/hyperextract/templates/zh/general/encyclopedia_item.py@@ -40,7 +40,8 @@ _PROMPT = """## 角色与任务- 属性名尽量简洁明了- 保持客观准确,符合百科全书风格-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/general/entity_registry.py b/hyperextract/templates/zh/general/entity_registry.pyindex 362b708..5c5eaa1 100644--- a/hyperextract/templates/zh/general/entity_registry.py+++ b/hyperextract/templates/zh/general/entity_registry.py@@ -31,7 +31,8 @@ _PROMPT = """## 角色与任务- 保持客观准确,不添加文本中没有的信息- 实体名称大小写需与原文保持一致-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/general/keyword_list.py b/hyperextract/templates/zh/general/keyword_list.pyindex 8eac339..09113d9 100644--- a/hyperextract/templates/zh/general/keyword_list.py+++ b/hyperextract/templates/zh/general/keyword_list.py@@ -29,7 +29,8 @@ _PROMPT = """## 角色与任务- 确保关键词准确,不添加文本中没有的信息- 保持关键词大小写与原文一致-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/general/knowledge_graph.py b/hyperextract/templates/zh/general/knowledge_graph.pyindex b6cc433..2330283 100644--- a/hyperextract/templates/zh/general/knowledge_graph.py+++ b/hyperextract/templates/zh/general/knowledge_graph.py@@ -50,7 +50,8 @@ _PROMPT = """## 角色与任务2. 每条边必须连接已提取的节点3. 关系描述应与原文保持一致-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -68,7 +69,8 @@ _NODE_PROMPT = """## 角色与任务1. 提取所有实体2. 为每个实体指定类型-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -83,6 +85,11 @@ _EDGE_PROMPT = """## 角色与任务1. 仅从已知实体列表中提取边,不要创建未列出的实体2. 关系描述应与原文保持一致+## 已知实体列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/general/life_event_timeline.py b/hyperextract/templates/zh/general/life_event_timeline.pyindex 2f794e2..dcd287f 100644--- a/hyperextract/templates/zh/general/life_event_timeline.py+++ b/hyperextract/templates/zh/general/life_event_timeline.py@@ -64,7 +64,8 @@ _PROMPT = """## 角色与任务3. 缺失时间:留空-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -77,7 +78,8 @@ _NODE_PROMPT = """## 角色与任务1. 提取所有相关实体2. 为每个实体指定类型-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -106,6 +108,12 @@ _EDGE_PROMPT = """## 角色与任务1. 仅从已知实体列表中提取事件2. 不要创建未列出的实体3. 时间信息为可选,仅在文本中明确提及时才提取++## 已知实体列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/general/operational_procedure.py b/hyperextract/templates/zh/general/operational_procedure.pyindex 0e639d2..8a6d5b5 100644--- a/hyperextract/templates/zh/general/operational_procedure.py+++ b/hyperextract/templates/zh/general/operational_procedure.py@@ -55,7 +55,8 @@ _PROMPT = """## 角色与任务2. 记录步骤之间的先后关系3. 记录转换条件(如有)-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -77,7 +78,8 @@ _NODE_PROMPT = """## 角色与任务5. 记录所需输入或材料(如有)6. 记录输出或结果(如有)-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -91,6 +93,11 @@ _EDGE_PROMPT = """## 角色与任务### 核心约束1. 仅从已知步骤列表中提取边,不要创建未列出的步骤+## 已知步骤列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/general/penalty_mapping.py b/hyperextract/templates/zh/general/penalty_mapping.pyindex 2f2c3a7..8d5994b 100644--- a/hyperextract/templates/zh/general/penalty_mapping.py+++ b/hyperextract/templates/zh/general/penalty_mapping.py@@ -48,7 +48,8 @@ _PROMPT = """## 角色与任务2. 记录节点之间的因果关系3. 关系描述应与原文保持一致-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -66,7 +67,8 @@ _NODE_PROMPT = """## 角色与任务1. 提取所有关键节点2. 为每个节点指定类型-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -88,6 +90,11 @@ _EDGE_PROMPT = """## 角色与任务- Produces:产生- Other:其他+## 已知节点列表:+{known_nodes}++## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/general/penalty_registry.py b/hyperextract/templates/zh/general/penalty_registry.pyindex cbf3b81..1dc7775 100644--- a/hyperextract/templates/zh/general/penalty_registry.py+++ b/hyperextract/templates/zh/general/penalty_registry.py@@ -33,7 +33,8 @@ _PROMPT = """## 角色与任务- 去重:相同的违规行为和处罚措施组合只保留一条- 保持客观准确,不添加文本中没有的信息-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/general/personal_profile.py b/hyperextract/templates/zh/general/personal_profile.pyindex 2cb8371..b922ae1 100644--- a/hyperextract/templates/zh/general/personal_profile.py+++ b/hyperextract/templates/zh/general/personal_profile.py@@ -46,7 +46,8 @@ _PROMPT = """## 角色与任务- 保持客观准确- 若信息缺失时留空,不要编造-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/general/regulation_profile.py b/hyperextract/templates/zh/general/regulation_profile.pyindex d74b1b8..1983be7 100644--- a/hyperextract/templates/zh/general/regulation_profile.py+++ b/hyperextract/templates/zh/general/regulation_profile.py@@ -44,7 +44,8 @@ _PROMPT = """## 角色与任务- 保持客观准确- 信息缺失时留空,不要编造-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/general/social_network.py b/hyperextract/templates/zh/general/social_network.pyindex a7b5d22..6dcad1e 100644--- a/hyperextract/templates/zh/general/social_network.py+++ b/hyperextract/templates/zh/general/social_network.py@@ -52,7 +52,8 @@ _PROMPT = """## 角色与任务2. 每条边必须连接已提取的节点3. 关系描述应与原文保持一致-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -70,7 +71,8 @@ _NODE_PROMPT = """## 角色与任务1. 提取所有人物、组织、机构等2. 为每个节点指定类型和角色-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -85,7 +87,11 @@ _EDGE_PROMPT = """## 角色与任务1. 仅从已知节点列表中提取边,不要创建未列出的节点2. 关系描述应与原文保持一致+## 已知节点+{known_nodes}+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/history/chronological_event_chain.py b/hyperextract/templates/zh/history/chronological_event_chain.pyindex 2a85d1c..cd1d712 100644--- a/hyperextract/templates/zh/history/chronological_event_chain.py+++ b/hyperextract/templates/zh/history/chronological_event_chain.py@@ -43,7 +43,8 @@ _NODE_PROMPT = """## 角色与任务- 事件类型:战争、政治、外交、军事等- 事件要包含简要描述-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -69,6 +70,11 @@ _EDGE_PROMPT = """## 角色与任务2. 精确时间 → 保持原样3. 时间缺失 → 留空,不要猜测+### 已知事件列表:+{known_nodes}++## 源文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -100,7 +106,8 @@ _PROMPT = """## 角色与任务2. 精确时间 → 保持原样3. 时间缺失 → 留空,不要猜测-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/history/epistolary_knowledge_graph.py b/hyperextract/templates/zh/history/epistolary_knowledge_graph.pyindex 9b34993..019b63a 100644--- a/hyperextract/templates/zh/history/epistolary_knowledge_graph.py+++ b/hyperextract/templates/zh/history/epistolary_knowledge_graph.py@@ -44,7 +44,8 @@ _NODE_PROMPT = """## 角色与任务### 领域特定规则- 人物要包含身份描述-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -78,6 +79,12 @@ _EDGE_PROMPT = """## 角色与任务2. 精确时间 → 保持原样3. 时间缺失 → 留空,不要猜测++## 已知人物列表:+{known_nodes}++## 源文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -115,7 +122,8 @@ _PROMPT = """## 角色与任务2. 精确时间 → 保持原样3. 时间缺失 → 留空,不要猜测-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/history/historical_context_graph.py b/hyperextract/templates/zh/history/historical_context_graph.pyindex c624e67..5cb2a6e 100644--- a/hyperextract/templates/zh/history/historical_context_graph.py+++ b/hyperextract/templates/zh/history/historical_context_graph.py@@ -41,7 +41,8 @@ _NODE_PROMPT = """## 角色与任务- 实体类型:地理、政治、经济、军事、文化- 实体要包含描述信息-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -59,6 +60,11 @@ _EDGE_PROMPT = """## 角色与任务### 领域特定规则- 关系类型:包含、影响、对抗、支撑+## 已知实体列表:+{known_nodes}++## 源文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -79,7 +85,8 @@ _PROMPT = """## 角色与任务- 实体类型:地理、政治、经济、军事、文化- 关系类型:包含、影响、对抗、支撑-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/history/historical_knowledge_graph.py b/hyperextract/templates/zh/history/historical_knowledge_graph.pyindex a3d615d..678b413 100644--- a/hyperextract/templates/zh/history/historical_knowledge_graph.py+++ b/hyperextract/templates/zh/history/historical_knowledge_graph.py@@ -42,7 +42,8 @@ _NODE_PROMPT = """## 角色与任务- 同一人物在不同势力有不同官职时,以原文描述的主要官职为准- 历史人物要包含所属阵营信息-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -61,6 +62,11 @@ _EDGE_PROMPT = """## 角色与任务- 关系类型:亲属、君臣、敌友、联盟、对手- 详细描述两人之间的具体互动+## 已知人物列表:+{known_nodes}++## 源文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -81,7 +87,8 @@ _PROMPT = """## 角色与任务- 关系类型:亲属、君臣、敌友、联盟、对手- 历史人物要包含所属阵营信息-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/history/memory_flashback_list.py b/hyperextract/templates/zh/history/memory_flashback_list.pyindex e434d1a..45cfa35 100644--- a/hyperextract/templates/zh/history/memory_flashback_list.py+++ b/hyperextract/templates/zh/history/memory_flashback_list.py@@ -33,7 +33,8 @@ _PROMPT = """## 角色与任务- 情感色彩:感慨、怀念、愤慨、欣慰- 尽量提取原文中的具体描述-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/history/multi_participant_event_map.py b/hyperextract/templates/zh/history/multi_participant_event_map.pyindex 73ac64f..40952fe 100644--- a/hyperextract/templates/zh/history/multi_participant_event_map.py+++ b/hyperextract/templates/zh/history/multi_participant_event_map.py@@ -43,7 +43,8 @@ _NODE_PROMPT = """## 角色与任务- 参与者要标注角色定位(主将、谋士、使者等)- 参与者要标注所属阵营-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -63,6 +64,11 @@ _EDGE_PROMPT = """## 角色与任务- 一个超边代表一个完整的历史事件- 需要包含事件的时间、地点、背景和结果+## 已知参与者列表:+{known_nodes}++## 源文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -86,7 +92,8 @@ _PROMPT = """## 角色与任务- 一个超边代表一个完整的历史事件- 需要包含事件的时间、地点、背景和结果-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/history/narrative_relation_graph.py b/hyperextract/templates/zh/history/narrative_relation_graph.pyindex bb10f9e..74e3f3e 100644--- a/hyperextract/templates/zh/history/narrative_relation_graph.py+++ b/hyperextract/templates/zh/history/narrative_relation_graph.py@@ -41,7 +41,8 @@ _NODE_PROMPT = """## 角色与任务- 人物要包含描述信息- 视角人物的评价或印象要记录-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -60,6 +61,11 @@ _EDGE_PROMPT = """## 角色与任务- 互动类型:评价、往来、合作、书信- 内容要具体描述互动或评价+## 已知人物列表:+{known_nodes}++## 源文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -82,7 +88,8 @@ _PROMPT = """## 角色与任务- 互动类型:评价、往来、合作、书信- 内容要具体描述互动或评价-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/history/personal_trajectory_hypergraph.py b/hyperextract/templates/zh/history/personal_trajectory_hypergraph.pyindex 0f0b591..7068ca5 100644--- a/hyperextract/templates/zh/history/personal_trajectory_hypergraph.py+++ b/hyperextract/templates/zh/history/personal_trajectory_hypergraph.py@@ -42,7 +42,8 @@ _NODE_PROMPT = """## 角色与任务- 主要人物:传记主角及其重要交往对象- 人物要包含描述信息-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -63,6 +64,11 @@ _EDGE_PROMPT = """## 角色与任务- 同行人物:该阶段与主角有交往的人- 核心经历:该阶段的重要事件+## 已知人物列表:+{known_nodes}++## 源文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -86,7 +92,8 @@ _PROMPT = """## 角色与任务- 同行人物:该阶段与主角有交往的人- 核心经历:该阶段的重要事件-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/history/political_struggle_hypergraph.py b/hyperextract/templates/zh/history/political_struggle_hypergraph.pyindex c2d6aeb..1ddc6a3 100644--- a/hyperextract/templates/zh/history/political_struggle_hypergraph.py+++ b/hyperextract/templates/zh/history/political_struggle_hypergraph.py@@ -46,7 +46,8 @@ _NODE_PROMPT = """## 角色与任务- 角色定位:攻方、守方、策划者、变节者、调解者- 参与者要标注所属阵营-### 源文本:+## 源文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -68,6 +69,11 @@ _EDGE_PROMPT = """## 角色与任务- 策划者:幕后策划或出谋划策的人- 变节者:中途倒戈或背叛的人+## 已知人物列表:+{known_nodes}++## 源文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -93,7 +99,8 @@ _PROMPT = """## 角色与任务- 策划者:幕后策划或出谋划策的人- 变节者:中途倒戈或背叛的人-### 源文本:+## 源文本:+{source_text}"""diff --git a/hyperextract/templates/zh/industry/emergency_response_graph.py b/hyperextract/templates/zh/industry/emergency_response_graph.pyindex 407732b..aa9d41d 100644--- a/hyperextract/templates/zh/industry/emergency_response_graph.py+++ b/hyperextract/templates/zh/industry/emergency_response_graph.py@@ -46,7 +46,8 @@ _NODE_PROMPT = """## 角色与任务- 识别负责部门名称(如安保部、设备部、急救部)- 为每个实体指定类别(事故场景/响应动作/部门)-### 源文本:+## 事故应急预案:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -67,6 +68,11 @@ _EDGE_PROMPT = """## 角色与任务- 记录响应时间要求- 记录成功标准+## 已知实体列表:+{known_nodes}++## 事故应急预案:+{source_text}"""_PROMPT = """## 角色与任务@@ -90,7 +96,8 @@ _PROMPT = """## 角色与任务- 建立从事故场景到响应动作的流程关系- 记录时间要求和成功标准-### 源文本:+## 事故应急预案:+{source_text}"""diff --git a/hyperextract/templates/zh/industry/equipment_topology_graph.py b/hyperextract/templates/zh/industry/equipment_topology_graph.pyindex 573ef32..6cf5e90 100644--- a/hyperextract/templates/zh/industry/equipment_topology_graph.py+++ b/hyperextract/templates/zh/industry/equipment_topology_graph.py@@ -47,7 +47,8 @@ _NODE_PROMPT = """## 角色与任务- 分类设备类别(主机、辅机、部件、仪表、阀门、管路、系统、电机、泵、风机、容器等)- 记录安装位置和运行状态-### 源文本:+## 设备系统文档:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -69,6 +70,11 @@ _EDGE_PROMPT = """## 角色与任务- 识别工艺流程关系(前一工序→后一工序)- 识别电气连接和仪表监测关系+## 已知设备列表:+{known_nodes}++## 设备系统文档:+{source_text}"""_PROMPT = """## 角色与任务@@ -91,7 +97,8 @@ _PROMPT = """## 角色与任务- 提取设备之间的连接关系,包括物料输送、能量传递、控制信号等- 记录安装位置和运行状态-### 源文本:+## 设备系统文档:+{source_text}"""diff --git a/hyperextract/templates/zh/industry/failure_case_graph.py b/hyperextract/templates/zh/industry/failure_case_graph.pyindex af78521..c6be549 100644--- a/hyperextract/templates/zh/industry/failure_case_graph.py+++ b/hyperextract/templates/zh/industry/failure_case_graph.py@@ -47,7 +47,8 @@ _NODE_PROMPT = """## 角色与任务- 识别经验教训和改进建议- 记录涉及的设备名称-### 源文本:+## 故障案例文档:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -67,6 +68,11 @@ _EDGE_PROMPT = """## 角色与任务- 识别从原因到措施的关联- 识别从措施到教训的关联+## 已知实体列表:+{known_nodes}++## 故障案例文档:+{source_text}"""_PROMPT = """## 角色与任务@@ -90,7 +96,8 @@ _PROMPT = """## 角色与任务- 总结经验教训和改进建议- 建立从发现到处理的完整链条-### 源文本:+## 故障案例文档:+{source_text}"""diff --git a/hyperextract/templates/zh/industry/failure_knowledge_hypergraph.py b/hyperextract/templates/zh/industry/failure_knowledge_hypergraph.pyindex 72ccc73..af0eb68 100644--- a/hyperextract/templates/zh/industry/failure_knowledge_hypergraph.py+++ b/hyperextract/templates/zh/industry/failure_knowledge_hypergraph.py@@ -52,7 +52,8 @@ _NODE_PROMPT = """## 角色与任务- 识别故障部件(轴承、密封、电机、泵体、阀门)- 识别解决方案(更换备件、调整参数、清洁、紧固)-### 源文本:+## 故障诊断文档:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -73,6 +74,11 @@ _EDGE_PROMPT = """## 角色与任务- 识别从根因到解决方案的推理- 边的 nodes 字段应包含所有参与该故障推理的实体+## 已知实体列表:+{known_nodes}++## 故障诊断文档:+{source_text}"""_PROMPT = """## 角色与任务@@ -95,7 +101,8 @@ _PROMPT = """## 角色与任务- 识别解决方案(更换备件、调整参数、清洁、紧固)- 建立从现象→根因→解决方案的完整推理链条-### 源文本:+## 故障诊断文档:+{source_text}"""diff --git a/hyperextract/templates/zh/industry/incident_causality_map.py b/hyperextract/templates/zh/industry/incident_causality_map.pyindex 101dc30..473f3a2 100644--- a/hyperextract/templates/zh/industry/incident_causality_map.py+++ b/hyperextract/templates/zh/industry/incident_causality_map.py@@ -61,7 +61,8 @@ _NODE_PROMPT = """## 角色与任务- 识别事故后果(人员伤亡、设备损坏、环境污染、停产损失)- 为实体指定严重程度-### 源文本:+## 事故调查报告:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -84,6 +85,11 @@ _EDGE_PROMPT = """## 角色与任务- 建立完整的因果链条:隐患 → 触发条件 → 违章行为 → 事故后果- 边的 nodes 字段应包含所有参与该因果链条的实体+# 已知的实体列表:+{known_nodes}++## 事故调查报告:+{source_text}"""_PROMPT = """## 角色与任务@@ -106,7 +112,8 @@ _PROMPT = """## 角色与任务- 识别事故后果(人员伤亡、设备损坏、环境污染、停产损失)- 建立完整的因果链条:隐患 → 触发条件 → 违章行为 → 事故后果-### 源文本:+## 事故调查报告:+{source_text}"""diff --git a/hyperextract/templates/zh/industry/inspection_record_graph.py b/hyperextract/templates/zh/industry/inspection_record_graph.pyindex 6d550e2..741a406 100644--- a/hyperextract/templates/zh/industry/inspection_record_graph.py+++ b/hyperextract/templates/zh/industry/inspection_record_graph.py@@ -44,7 +44,8 @@ _NODE_PROMPT = """## 角色与任务- 识别巡检项名称(具体检查点)- 为每个实体指定类别(设备/巡检项)-### 源文本:+## 巡检记录文档:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -63,6 +64,11 @@ _EDGE_PROMPT = """## 角色与任务- 识别巡检项与设备之间的从属关系- 例如:电机运行状态 属于 数控加工中心+## 已知实体列表:+{known_nodes}++## 巡检记录文档:+{source_text}"""_PROMPT = """## 角色与任务@@ -84,7 +90,8 @@ _PROMPT = """## 角色与任务- 识别每个设备下的巡检项(如电机运行状态、轴承温度、冷却液位等)- 建立巡检项与设备之间的从属关系-### 源文本:+## 巡检记录文档:+{source_text}"""diff --git a/hyperextract/templates/zh/industry/maintenace_operation_map.py b/hyperextract/templates/zh/industry/maintenace_operation_map.pyindex 5116a05..94fc455 100644--- a/hyperextract/templates/zh/industry/maintenace_operation_map.py+++ b/hyperextract/templates/zh/industry/maintenace_operation_map.py@@ -66,7 +66,8 @@ _NODE_PROMPT = """## 角色与任务- 识别材料(润滑油、密封胶、清洁剂)- 识别备件(轴承、密封圈、滤芯)-### 源文本:+## 维修作业指导书:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -89,6 +90,11 @@ _EDGE_PROMPT = """## 角色与任务- 记录前置条件和质量标准- 边的 nodes 字段应包含所有参与该作业的实体+## 已知实体列表:+{known_nodes}++## 维修作业指导书:+{source_text}"""_PROMPT = """## 角色与任务@@ -116,7 +122,8 @@ _PROMPT = """## 角色与任务- 提取作业耗时- 记录前置条件和质量标准-### 源文本:+## 维修作业指导书:+{source_text}"""diff --git a/hyperextract/templates/zh/industry/operating_mode_graph.py b/hyperextract/templates/zh/industry/operating_mode_graph.pyindex 4dc8472..c139ff6 100644--- a/hyperextract/templates/zh/industry/operating_mode_graph.py+++ b/hyperextract/templates/zh/industry/operating_mode_graph.py@@ -47,7 +47,8 @@ _NODE_PROMPT = """## 角色与任务- 为每个实体指定类别(工况/条件)- 记录每种工况的负荷范围-### 源文本:+## 运行规程文档:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -67,6 +68,11 @@ _EDGE_PROMPT = """## 角色与任务- 识别条件对工况的触发关系(条件 触发 目标工况)- 关系类型使用 切换到 或 触发+## 已知实体列表:+{known_nodes}++## 运行规程文档:+{source_text}"""_PROMPT = """## 角色与任务@@ -90,7 +96,8 @@ _PROMPT = """## 角色与任务- 提取工况之间的切换关系(切换到)- 提取条件触发工况的关系(触发)-### 源文本:+## 运行规程文档:+{source_text}"""diff --git a/hyperextract/templates/zh/industry/operation_flow_graph.py b/hyperextract/templates/zh/industry/operation_flow_graph.pyindex 8476b21..8f6c8c0 100644--- a/hyperextract/templates/zh/industry/operation_flow_graph.py+++ b/hyperextract/templates/zh/industry/operation_flow_graph.py@@ -48,7 +48,8 @@ _NODE_PROMPT = """## 角色与任务- 为每个实体指定类别(动作/设备状态)- 记录每一步骤的预期结果和涉及设备-### 源文本:+## 操作流程文档:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -69,7 +70,11 @@ _EDGE_PROMPT = """## 角色与任务- 记录设备状态的变化- 关系类型使用:下一步、触发、导致-### 已知实体列表:+## 已知实体列表:+{known_nodes}++## 操作流程文档:+{source_text}"""_PROMPT = """## 角色与任务@@ -92,7 +97,8 @@ _PROMPT = """## 角色与任务- 记录每一步骤的详细操作内容、预期结果和涉及设备- 建立步骤之间的流转关系-### 源文本:+## 操作流程文档:+{source_text}"""diff --git a/hyperextract/templates/zh/industry/part_replacement_list.py b/hyperextract/templates/zh/industry/part_replacement_list.pyindex f10aa5b..e280a13 100644--- a/hyperextract/templates/zh/industry/part_replacement_list.py+++ b/hyperextract/templates/zh/industry/part_replacement_list.py@@ -53,7 +53,8 @@ _PROMPT = """## 角色与任务- 提取所属设备名称- 识别维护类型(例行保养、故障维修、计划检修、抢修)-### 源文本:+## 备件更换记录:+{source_text}"""diff --git a/hyperextract/templates/zh/industry/safety_control_graph.py b/hyperextract/templates/zh/industry/safety_control_graph.pyindex 3d52301..833c1fd 100644--- a/hyperextract/templates/zh/industry/safety_control_graph.py+++ b/hyperextract/templates/zh/industry/safety_control_graph.py@@ -49,7 +49,8 @@ _NODE_PROMPT = """## 角色与任务- 为每个实体指定类别(危险源/风险点/管控措施/责任人)- 为风险点指定风险等级(重大风险、较大风险、一般风险)-### 源文本:+## 安全规程文档:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -71,7 +72,11 @@ _EDGE_PROMPT = """## 角色与任务- 记录危险因素和可能导致后果- 关系类型使用:导致、需要、管控、负责-### 已知实体列表:+## 已知实体列表:+{known_nodes}++## 安全规程文档:+{source_text}"""_PROMPT = """## 角色与任务@@ -96,7 +101,8 @@ _PROMPT = """## 角色与任务- 为风险点指定风险等级(重大风险、较大风险、一般风险)- 建立从危险源→风险点→管控措施→责任人的完整管控链条-### 源文本:+## 安全规程文档:+{source_text}"""diff --git a/hyperextract/templates/zh/industry/safety_timeline.py b/hyperextract/templates/zh/industry/safety_timeline.pyindex d020c43..375fb80 100644--- a/hyperextract/templates/zh/industry/safety_timeline.py+++ b/hyperextract/templates/zh/industry/safety_timeline.py@@ -61,7 +61,8 @@ _PROMPT = """## 角色与任务2. 精确时间 → 保持原样3. 时间缺失 → 留空,不要猜测-### 源文本:+## 事故调查报告:+{source_text}"""_NODE_PROMPT = """## 角色@@ -75,7 +76,8 @@ _NODE_PROMPT = """## 角色### 提取范围- 人员、设备、设施、岗位、位置等-## 源文本:+## 事故调查报告:+{source_text}"""_EDGE_PROMPT = """## 角色@@ -102,6 +104,11 @@ _EDGE_PROMPT = """## 角色- location: 发生位置- status: 状态+# 已知实体列表:+{known_nodes}++## 事故调查报告:+{source_text}"""diff --git a/hyperextract/templates/zh/industry/spec_parameter_table.py b/hyperextract/templates/zh/industry/spec_parameter_table.pyindex ecf212d..9a69e83 100644--- a/hyperextract/templates/zh/industry/spec_parameter_table.py+++ b/hyperextract/templates/zh/industry/spec_parameter_table.py@@ -85,7 +85,8 @@ _PROMPT = """## 角色与任务- 提取性能参数:容量、防护等级、绝缘等级- 保留原始单位,不要换算-### 源文本:+## 技术规格书:+{source_text}"""diff --git a/hyperextract/templates/zh/industry/system_compatibility_graph.py b/hyperextract/templates/zh/industry/system_compatibility_graph.pyindex ab4dba9..bc020f2 100644--- a/hyperextract/templates/zh/industry/system_compatibility_graph.py+++ b/hyperextract/templates/zh/industry/system_compatibility_graph.py@@ -59,7 +59,8 @@ _NODE_PROMPT = """## 角色与任务- 识别环境(高温环境、低温环境、防爆区域、腐蚀性环境)- 识别连接方式(法兰连接、螺纹连接、焊接)-### 源文本:+## 技术规格书:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -81,6 +82,11 @@ _EDGE_PROMPT = """## 角色与任务- 识别连接方式的匹配- 边的 nodes 字段应包含所有参与该兼容性关系的实体+## 已知实体列表:+{known_nodes}++## 技术规格书:+{source_text}"""_PROMPT = """## 角色与任务@@ -104,7 +110,8 @@ _PROMPT = """## 角色与任务- 识别连接方式(法兰连接、螺纹连接、焊接)- 建立设备与材质、介质、环境的兼容性关系-### 源文本:+## 技术规格书:+{source_text}"""diff --git a/hyperextract/templates/zh/industry/system_topology_graph.py b/hyperextract/templates/zh/industry/system_topology_graph.pyindex 1795292..4f5992a 100644--- a/hyperextract/templates/zh/industry/system_topology_graph.py+++ b/hyperextract/templates/zh/industry/system_topology_graph.py@@ -46,7 +46,8 @@ _NODE_PROMPT = """## 角色与任务- 识别具体设备名称(如数控加工中心、机械臂、泵等)- 为每个实体指定类别(厂区/系统/子系统/设备)-### 源文本:+## 系统架构文档:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -66,6 +67,11 @@ _EDGE_PROMPT = """## 角色与任务- 识别系统与子系统之间的包含关系- 识别子系统与设备之间的包含关系+## 已知实体列表:+{known_nodes}++## 系统架构文档:+{source_text}"""_PROMPT = """## 角色与任务@@ -89,7 +95,8 @@ _PROMPT = """## 角色与任务- 识别具体设备(如数控加工中心、机械臂、泵等)- 建立上下级的层级包含关系-### 源文本:+## 系统架构文档:+{source_text}"""diff --git a/hyperextract/templates/zh/legal/adjudication_logic.py b/hyperextract/templates/zh/legal/adjudication_logic.pyindex 8ff813e..7db138a 100644--- a/hyperextract/templates/zh/legal/adjudication_logic.py+++ b/hyperextract/templates/zh/legal/adjudication_logic.py@@ -63,7 +63,8 @@ _PROMPT = """## 角色与任务2. 超边必须包含 logic_type、participants、reasoning、conclusion3. participants 必须严格使用已提取节点的名称-### 源文本:+## 源文本:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -88,11 +89,12 @@ _NODE_PROMPT = """## 角色与任务2. 为每个要素指定类型3. 为每个要素添加简要描述-### 源文本:+## 判决书文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务-请从已知节点列表中提取裁判逻辑超边。+请从已知裁判要素列表中提取裁判逻辑超边。## 核心概念定义- **节点 (Node)**:构成裁判逻辑的基本要素,作为超边的参与者@@ -100,7 +102,7 @@ _EDGE_PROMPT = """## 角色与任务## 提取规则### 核心约束-1. participants 必须严格使用已知节点列表中的名称,不要创建新名称+1. participants 必须严格使用已知裁判要素列表中的名称,不要创建新名称2. 超边必须包含 logic_type、participants、reasoning、conclusion3. participants 应包含事实认定、法律依据、裁判结论等相关要素@@ -112,6 +114,11 @@ _EDGE_PROMPT = """## 角色与任务- **金额计算**:计算具体的赔偿金额- **其他**:不属于上述类型的推理+## 已知裁判要素列表:+{known_nodes}++## 判决书文本:+{source_text}"""diff --git a/hyperextract/templates/zh/legal/beneficial_ownership_graph.py b/hyperextract/templates/zh/legal/beneficial_ownership_graph.pyindex 123256a..2791ebd 100644--- a/hyperextract/templates/zh/legal/beneficial_ownership_graph.py+++ b/hyperextract/templates/zh/legal/beneficial_ownership_graph.py@@ -49,7 +49,8 @@ _NODE_PROMPT = """## 角色与任务- 实体类型:公司、自然人、基金、合伙企业、境外特殊目的公司- 包含股东、合伙人、高管、实际控制人等-### 源文本:+## 股权结构文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -73,6 +74,11 @@ _EDGE_PROMPT = """## 角色与任务- **配偶关系**:夫妻关系- **其他关系**:如父子、兄弟、姐妹等+## 已知实体列表:+{known_nodes}++## 股权结构文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -95,7 +101,8 @@ _PROMPT = """## 角色与任务### 关系类型- 控股、参股、担任董事、执行事务合伙人、实际控制、配偶关系等-### 源文本:+## 股权结构文本:+{source_text}"""diff --git a/hyperextract/templates/zh/legal/case_fact_timeline.py b/hyperextract/templates/zh/legal/case_fact_timeline.pyindex 6a28057..64ce536 100644--- a/hyperextract/templates/zh/legal/case_fact_timeline.py+++ b/hyperextract/templates/zh/legal/case_fact_timeline.py@@ -51,11 +51,12 @@ _NODE_PROMPT = """## 角色与任务- 金钱:投资款、红利、违约金等- 股权:股份、股权等-### 源文本:+## 案件事实文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务-请从已知实体列表中提取法律实体之间的法律行为(事件)。+请从已知法律实体列表中提取法律实体之间的法律行为(事件)。## 核心概念定义- **节点 (Node)**:案件中的法律实体@@ -63,7 +64,7 @@ _EDGE_PROMPT = """## 角色与任务## 提取规则### 核心约束-1. 仅从已知实体列表中提取边,不要创建未列出的实体+1. 仅从已知法律实体列表中提取边,不要创建未列出的实体2. 关系描述应与原文保持一致### 法律行为@@ -77,7 +78,11 @@ _EDGE_PROMPT = """## 角色与任务2. 精确时间 → 转换为标准格式年-月-日3. 时间缺失 → 留空-### 已知实体列表:+## 已知法律实体列表:+{known_nodes}++## 案件事实文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -110,7 +115,8 @@ _PROMPT = """## 角色与任务2. 精确时间 → 转换为标准格式年-月-日3. 时间缺失 → 留空-### 源文本:+## 案件事实文本:+{source_text}"""diff --git a/hyperextract/templates/zh/legal/case_law_citation_net.py b/hyperextract/templates/zh/legal/case_law_citation_net.pyindex a4185a4..5eef77f 100644--- a/hyperextract/templates/zh/legal/case_law_citation_net.py+++ b/hyperextract/templates/zh/legal/case_law_citation_net.py@@ -44,7 +44,8 @@ _NODE_PROMPT = """## 角色与任务- 案件类型:指导案例、公报案例、普通案例、司法解释、法律条文- 常见表达:"根据《民法典》第X条"、"指导案例XX号"、"本案确立了..."-### 源文本:+## 判例文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -67,6 +68,11 @@ _EDGE_PROMPT = """## 角色与任务- 参考:后案参考前案的裁判思路- 类案:后案与前案属于同类案件+## 已知判例列表:+{known_nodes}++## 判例文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -91,7 +97,8 @@ _PROMPT = """## 角色与任务- 参考:后案参考前案的裁判思路- 类案:后案与前案属于同类案件-### 源文本:+## 判例文本:+{source_text}"""diff --git a/hyperextract/templates/zh/legal/compliance_requirement_list.py b/hyperextract/templates/zh/legal/compliance_requirement_list.pyindex 7af9cf1..2573888 100644--- a/hyperextract/templates/zh/legal/compliance_requirement_list.py+++ b/hyperextract/templates/zh/legal/compliance_requirement_list.py@@ -52,7 +52,8 @@ _PROMPT = """## 角色与任务- 每项合规要求作为独立条目提取- 保持内容与原文一致-### 源文本:+## 合规申报文件:+{source_text}"""diff --git a/hyperextract/templates/zh/legal/contract_obligation_hypergraph.py b/hyperextract/templates/zh/legal/contract_obligation_hypergraph.pyindex 0c8c865..145cecb 100644--- a/hyperextract/templates/zh/legal/contract_obligation_hypergraph.py+++ b/hyperextract/templates/zh/legal/contract_obligation_hypergraph.py@@ -71,7 +71,8 @@ _PROMPT = """## 角色与任务2. 超边必须包含 obligation_type、participants3. participants 必须严格使用已提取节点的名称-### 源文本:+## 合同条款:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -96,11 +97,12 @@ _NODE_PROMPT = """## 角色与任务2. 为每个要素指定类型3. 为每个要素添加简要描述(1-2句话)-### 源文本:+## 合同条款:+{source_text}"""_EDGE_PROMPT = """## 角色与任务-请从已知节点列表中提取合同义务超边。+请从已知合同要素列表中提取合同义务超边。## 核心概念定义- **节点 (Node)**:构成合同义务的基本要素,作为超边的参与者@@ -108,7 +110,7 @@ _EDGE_PROMPT = """## 角色与任务## 提取规则### 核心约束-1. participants 必须严格使用已知节点列表中的名称,不要创建新名称+1. participants 必须严格使用已知合同要素列表中的名称,不要创建新名称2. 超边必须包含 obligation_type、participants3. participants 应包含涉及的主体、义务及相关要素@@ -132,6 +134,11 @@ _EDGE_PROMPT = """## 角色与任务- 解除合同- 返还已付款项+## 已知合同要素列表:+{known_nodes}++## 合同条款:+{source_text}"""diff --git a/hyperextract/templates/zh/legal/defined_term_registry.py b/hyperextract/templates/zh/legal/defined_term_registry.pyindex f68b3c5..6e5ac2c 100644--- a/hyperextract/templates/zh/legal/defined_term_registry.py+++ b/hyperextract/templates/zh/legal/defined_term_registry.py@@ -37,7 +37,8 @@ _PROMPT = """## 角色与任务- 风险相关的术语(不可抗力、机密信息)- 程序相关的术语(验收标准、付款条件)-### 源文本:+## 合同文本:+{source_text}"""diff --git a/hyperextract/templates/zh/legal/legal_concept_ontology.py b/hyperextract/templates/zh/legal/legal_concept_ontology.pyindex 31f1f40..8870efa 100644--- a/hyperextract/templates/zh/legal/legal_concept_ontology.py+++ b/hyperextract/templates/zh/legal/legal_concept_ontology.py@@ -43,11 +43,12 @@ _NODE_PROMPT = """## 角色与任务- 法律概念类型包括:原则、规则、学说、术语、法律依据- 常见的法律概念:过错、故意、过失、违法性、因果关系、举证责任等-### 源文本:+## 法律文献文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务-请从已知概念列表中提取概念之间的关系。+请从已知法律概念列表中提取概念之间的关系。## 核心概念定义- **节点 (Node)**:从文档中提取的法律概念@@ -55,17 +56,22 @@ _EDGE_PROMPT = """## 角色与任务## 提取规则### 核心约束-1. 仅从已知概念列表中提取边,不要创建未列出的概念+1. 仅从已知法律概念列表中提取边,不要创建未列出的概念2. 关系描述应与原文保持一致-###-- 上位 关系类型定义概念:概念之间的层级包含关系+### 关系类型+- 上位概念:概念之间的层级包含关系- 下位概念:概念之间的层级包含关系- 相关联:概念之间存在逻辑关联- 对立:概念之间存在对立关系- 包含:一个概念包含另一个概念- 依据:一个概念是另一个概念的依据+## 已知法律概念列表:+{known_nodes}++## 法律文献文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -86,8 +92,8 @@ _PROMPT = """## 角色与任务- 法律概念类型包括:原则、规则、学说、术语、法律依据- 关系类型:上位概念、下位概念、相关联、对立、包含、依据-### 源文本:-"""+## 法律文献文本:+{source_text}"""class LegalConceptOntology(AutoGraph[LegalConceptNode, LegalConceptRelationEdge]):diff --git a/hyperextract/templates/zh/legal/liability_clause_list.py b/hyperextract/templates/zh/legal/liability_clause_list.pyindex 38e9e20..9903a7c 100644--- a/hyperextract/templates/zh/legal/liability_clause_list.py+++ b/hyperextract/templates/zh/legal/liability_clause_list.py@@ -47,7 +47,8 @@ _PROMPT = """## 角色与任务- 保持条款内容与原文一致- 不要遗漏任何责任相关条款-### 源文本:+## 合同条款:+{source_text}"""diff --git a/hyperextract/templates/zh/legal/litigation_participant_map.py b/hyperextract/templates/zh/legal/litigation_participant_map.pyindex 38affc0..1c063c3 100644--- a/hyperextract/templates/zh/legal/litigation_participant_map.py+++ b/hyperextract/templates/zh/legal/litigation_participant_map.py@@ -45,11 +45,12 @@ _NODE_PROMPT = """## 角色与任务- 参与人类型:原告、被告、第三人、委托诉讼代理人、法定代理人、证人、鉴定人、法官、合议庭成员- 常见的参与人:当事人(公司或个人)、律师、法定代表人、证人-### 源文本:+## 法律文书文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务-请从已知参与人列表中提取参与人之间的关系。+请从已知诉讼参与人列表中提取参与人之间的关系。## 核心概念定义- **节点 (Node)**:诉讼参与人@@ -57,7 +58,7 @@ _EDGE_PROMPT = """## 角色与任务## 提取规则### 核心约束-1. 仅从已知参与人列表中提取边,不要创建未列出的参与人+1. 仅从已知诉讼参与人列表中提取边,不要创建未列出的参与人2. 关系描述应与原文保持一致### 关系类型@@ -70,7 +71,11 @@ _EDGE_PROMPT = """## 角色与任务- **同案当事人**:同一案件中的原告或被告- **敌对**:利益对立关系-### 已知参与人列表:+## 已知诉讼参与人列表:+{known_nodes}++## 法律文书文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -84,7 +89,7 @@ _PROMPT = """## 角色与任务### 核心约束1. 每个节点只能对应一个独立的参与人,禁止将多个参与人合并为一个节点2. 参与人名称与原文保持一致-3. 仅从已知参与人列表中提取边,不要创建未列出的参与人+3. 仅从已知诉讼参与人列表中提取边,不要创建未列出的参与人4. 关系描述应与原文保持一致### 参与人类型@@ -93,7 +98,8 @@ _PROMPT = """## 角色与任务### 关系类型- 代理、代表、股东、董事、担保、上下级、同案当事人、敌对-### 源文本:+## 法律文书文本:+{source_text}"""diff --git a/hyperextract/templates/zh/literature/character_arc_timeline.py b/hyperextract/templates/zh/literature/character_arc_timeline.pyindex 8fa0b87..451dd06 100644--- a/hyperextract/templates/zh/literature/character_arc_timeline.py+++ b/hyperextract/templates/zh/literature/character_arc_timeline.py@@ -44,11 +44,12 @@ _NODE_PROMPT = """## 角色与任务- 情绪:角色的情感状态,如"悲伤"、"愤怒"、"坚定"、"迷茫"、"绝望"- 事件:关键情节,如"被陷害"、"果郡王之死"、"回宫复仇"-### 源文本:+## 影视剧本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务-请从已知节点列表中提取节点之间的关系。+请从已知叙事元素列表中提取节点之间的关系。## 核心概念定义- **节点 (Node)**:从文档中提取的叙事元素@@ -56,7 +57,7 @@ _EDGE_PROMPT = """## 角色与任务## 提取规则### 核心约束-1. 仅从已知节点列表中提取边,不要创建未列出的节点+1. 仅从已知叙事元素列表中提取边,不要创建未列出的节点2. 关系描述应与原文保持一致### 领域特定规则@@ -73,6 +74,11 @@ _EDGE_PROMPT = """## 角色与任务3. 幕数格式:如"第一幕"、"第2幕" → 保持原样4. 相对时间:如"随后"、"不久" → 留空,不要猜测+## 已知叙事元素列表:+{known_nodes}++## 影视剧本:+{source_text}"""_PROMPT = """## 角色与任务@@ -86,7 +92,7 @@ _PROMPT = """## 角色与任务### 核心约束1. 每个节点只能对应一个独立的实体,禁止将多个实体合并为一个节点2. 实体名称与原文保持一致-3. 仅从已知节点列表中提取边,不要创建未列出的节点+3. 仅从已知叙事元素列表中提取边,不要创建未列出的节点4. 关系描述应与原文保持一致### 领域特定规则@@ -109,7 +115,8 @@ _PROMPT = """## 角色与任务3. 幕数格式:如"第一幕"、"第2幕" → 保持原样4. 相对时间:如"随后"、"不久" → 留空,不要猜测-### 源文本:+## 影视剧本:+{source_text}"""diff --git a/hyperextract/templates/zh/literature/complex_character_relation.py b/hyperextract/templates/zh/literature/complex_character_relation.pyindex 53c23e5..d0f0eb1 100644--- a/hyperextract/templates/zh/literature/complex_character_relation.py+++ b/hyperextract/templates/zh/literature/complex_character_relation.py@@ -42,7 +42,8 @@ _NODE_PROMPT = """## 角色与任务- 角色定位:主角、配角、反派、酱油- 所属阵营:如"江左盟"、"太子党"、"誉王党"等-### 源文本:+## 小说文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -66,6 +67,11 @@ _EDGE_PROMPT = """## 角色与任务- 竞争:多方争夺同一目标- 家族:同一家族的成员关系+## 已知人物列表:+{known_nodes}++## 小说文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -88,7 +94,8 @@ _PROMPT = """## 角色与任务- 所属阵营:如"江左盟"、"太子党"、"誉王党"等- 关系类型:三角恋、结盟、敌对、背叛、竞争、家族-### 源文本:+## 小说文本:+{source_text}"""diff --git a/hyperextract/templates/zh/literature/critique_argument_hypergraph.py b/hyperextract/templates/zh/literature/critique_argument_hypergraph.pyindex a2b397d..9eae71a 100644--- a/hyperextract/templates/zh/literature/critique_argument_hypergraph.py+++ b/hyperextract/templates/zh/literature/critique_argument_hypergraph.py@@ -43,7 +43,8 @@ _NODE_PROMPT = """## 角色与任务- 引用:原文中的引用文本- 观点:作者的核心论点-### 源文本:+## 文学评论文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -57,7 +58,7 @@ _EDGE_PROMPT = """## 角色与任务### 核心约束1. 超边必须包含至少一个论据或引用2. 超边必须包含核心观点-3. 仅从已知元素列表中提取边,不要创建未列出的元素+3. 仅从已知论证元素列表中提取边,不要创建未列出的元素4. 描述应与原文保持一致### 领域特定规则@@ -65,6 +66,11 @@ _EDGE_PROMPT = """## 角色与任务- 引用:原文中的引用文本- 观点:作者的核心论点+## 已知论证元素列表:+{known_nodes}++## 文学评论文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -80,7 +86,7 @@ _PROMPT = """## 角色与任务2. 元素名称与原文保持一致3. 超边必须包含至少一个论据或引用4. 超边必须包含核心观点-5. 仅从已知元素列表中提取边,不要创建未列出的元素+5. 仅从已知论证元素列表中提取边,不要创建未列出的元素6. 描述应与原文保持一致### 领域特定规则@@ -88,7 +94,8 @@ _PROMPT = """## 角色与任务- 引用:原文中的引用文本- 观点:作者的核心论点-### 源文本:+## 文学评论文本:+{source_text}"""diff --git a/hyperextract/templates/zh/literature/motif_association_net.py b/hyperextract/templates/zh/literature/motif_association_net.pyindex f105c43..8b2c487 100644--- a/hyperextract/templates/zh/literature/motif_association_net.py+++ b/hyperextract/templates/zh/literature/motif_association_net.py@@ -39,7 +39,8 @@ _NODE_PROMPT = """## 角色与任务### 领域特定规则- 意象:反复出现的符号、象征物、自然元素等-### 源文本:+## 文学评论文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -61,6 +62,11 @@ _EDGE_PROMPT = """## 角色与任务- 象征:一个意象代表另一个含义- 配套:多个意象共同构成一个意象群+## 已知意象列表:+{known_nodes}++## 文学评论文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -81,7 +87,8 @@ _PROMPT = """## 角色与任务- 意象:反复出现的符号、象征物、自然元素等- 关联类型:对比、递进、因果、象征、配套-### 源文本:+## 文学评论文本:+{source_text}"""diff --git a/hyperextract/templates/zh/literature/narrative_event_chain.py b/hyperextract/templates/zh/literature/narrative_event_chain.pyindex 2c0d29e..9464606 100644--- a/hyperextract/templates/zh/literature/narrative_event_chain.py+++ b/hyperextract/templates/zh/literature/narrative_event_chain.py@@ -39,7 +39,8 @@ _NODE_PROMPT = """## 角色与任务### 领域特定规则- 情节转折点:改变故事走向的关键事件-### 源文本:+## 小说文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -55,11 +56,17 @@ _EDGE_PROMPT = """## 角色与任务2. 关系描述应与原文保持一致### 时间解析规则+当前观测时间: {observation_time}1. 章节格式:如"第一章"、"第3章" → 保持原样2. 日期格式:如"第一日"、"第X日" → 保持原样3. 年份格式:如"第一年"、"XX年" → 保持原样4. 相对时间:如"随后"、"之后" → 留空,不要猜测+## 已知情节列表:+{known_nodes}++## 小说文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -80,12 +87,14 @@ _PROMPT = """## 角色与任务- 情节转折点:改变故事走向的关键事件### 时间解析规则+当前观测时间: {observation_time}1. 章节格式:如"第一章"、"第3章" → 保持原样2. 日期格式:如"第一日"、"第X日" → 保持原样3. 年份格式:如"第一年"、"XX年" → 保持原样4. 相对时间:如"随后"、"之后" → 留空,不要猜测-### 源文本:+## 小说文本:+{source_text}"""diff --git a/hyperextract/templates/zh/literature/narrative_structure_tree.py b/hyperextract/templates/zh/literature/narrative_structure_tree.pyindex f1a16d3..30bfcaf 100644--- a/hyperextract/templates/zh/literature/narrative_structure_tree.py+++ b/hyperextract/templates/zh/literature/narrative_structure_tree.py@@ -44,7 +44,8 @@ _NODE_PROMPT = """## 角色与任务- 前提:故事发生的背景设定- 结局:故事的最终走向和结果-### 源文本:+## 文学评论文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -65,6 +66,11 @@ _EDGE_PROMPT = """## 角色与任务- 展开:上位结构展开为下位结构- 转折:从一线转到另一线+## 已知结构单元列表:+{known_nodes}++## 文学评论文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -92,7 +98,8 @@ _PROMPT = """## 角色与任务- 展开:上位结构展开为下位结构- 转折:从一线转到另一线-### 源文本:+## 文学评论文本:+{source_text}"""diff --git a/hyperextract/templates/zh/literature/scene_event_hypergraph.py b/hyperextract/templates/zh/literature/scene_event_hypergraph.pyindex 1cc36f3..a64d895 100644--- a/hyperextract/templates/zh/literature/scene_event_hypergraph.py+++ b/hyperextract/templates/zh/literature/scene_event_hypergraph.py@@ -45,7 +45,8 @@ _NODE_PROMPT = """## 角色与任务- 道具:从动作描述中提取的关键物品,如"油纸伞"、"宫灯"- 动作:从动作描述中提取的核心行为,如"起舞"、"吟诵"-### 源文本:+## 影视剧本文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -59,7 +60,7 @@ _EDGE_PROMPT = """## 角色与任务### 核心约束1. 超边必须包含至少一个角色2. 超边必须包含地点-3. 仅从已知元素列表中提取边,不要创建未列出的元素+3. 仅从已知场景元素列表中提取边,不要创建未列出的元素4. 描述应与原文保持一致### 领域特定规则@@ -69,6 +70,11 @@ _EDGE_PROMPT = """## 角色与任务- 核心动作:角色完成的主要行为- 时间段:从场景头中提取,如"日"、"夜"、"晨"、"昏"+## 已知场景元素列表:+{known_nodes}++## 影视剧本文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -83,7 +89,7 @@ _PROMPT = """## 角色与任务1. 每个节点只能对应一个独立的实体,禁止将多个实体合并为一个节点2. 实体名称与原文保持一致3. 超边必须包含至少一个角色和地点-4. 仅从已知元素列表中提取边,不要创建未列出的元素+4. 仅从已知场景元素列表中提取边,不要创建未列出的元素5. 描述应与原文保持一致### 领域特定规则@@ -93,7 +99,8 @@ _PROMPT = """## 角色与任务- 动作:从动作描述中提取的核心行为- 时间段:从场景头中提取,如"日"、"夜"、"晨"、"昏"-### 源文本:+## 影视剧本文本:+{source_text}"""diff --git a/hyperextract/templates/zh/literature/story_entity_graph.py b/hyperextract/templates/zh/literature/story_entity_graph.pyindex f92c882..59b71f5 100644--- a/hyperextract/templates/zh/literature/story_entity_graph.py+++ b/hyperextract/templates/zh/literature/story_entity_graph.py@@ -41,7 +41,8 @@ _NODE_PROMPT = """## 角色与任务- 物品:武器、书信、信物、药材等- 地点:城市、建筑、区域等-### 源文本:+## 小说文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -60,6 +61,11 @@ _EDGE_PROMPT = """## 角色与任务- 归属:物品的所有者或使用者- 位于:物品的位置或地点的所在+## 已知实体列表:+{known_nodes}++## 小说文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -81,7 +87,8 @@ _PROMPT = """## 角色与任务- 地点:城市、建筑、区域等- 关系类型:归属(物品的所有者)、位于(物品的位置)-### 源文本:+## 小说文本:+{source_text}"""diff --git a/hyperextract/templates/zh/medicine/adverse_reaction_stats.py b/hyperextract/templates/zh/medicine/adverse_reaction_stats.pyindex 7ea27fb..4cb82ac 100644--- a/hyperextract/templates/zh/medicine/adverse_reaction_stats.py+++ b/hyperextract/templates/zh/medicine/adverse_reaction_stats.py@@ -37,7 +37,8 @@ _PROMPT = """## 角色与任务- 只提取文本中明确提及的不良反应和发生率- 保持客观准确,不添加文本中没有的信息-### 源文本:+## 药品说明书:+{source_text}"""diff --git a/hyperextract/templates/zh/medicine/anatomy_hierarchy.py b/hyperextract/templates/zh/medicine/anatomy_hierarchy.pyindex e3eb869..6099c05 100644--- a/hyperextract/templates/zh/medicine/anatomy_hierarchy.py+++ b/hyperextract/templates/zh/medicine/anatomy_hierarchy.py@@ -50,7 +50,8 @@ _PROMPT = """## 角色与任务- 解剖学术语保持原文,如解剖结构名称(心脏、肝脏、主动脉)- 医学术语保持原文-### 源文本:+## 病历文档:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -67,7 +68,8 @@ _NODE_PROMPT = """## 角色与任务### 领域特定规则- 解剖学术语保持原文,如解剖结构名称-### 源文本:+## 病历文档:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -85,6 +87,12 @@ _EDGE_PROMPT = """## 角色与任务### 领域特定规则- 医学术语保持原文++## 已知实体:+{known_nodes}++## 病历文档:+{source_text}"""diff --git a/hyperextract/templates/zh/medicine/clinical_pathway.py b/hyperextract/templates/zh/medicine/clinical_pathway.pyindex b9fca3b..ccb2592 100644--- a/hyperextract/templates/zh/medicine/clinical_pathway.py+++ b/hyperextract/templates/zh/medicine/clinical_pathway.py@@ -48,7 +48,8 @@ _PROMPT = """## 角色与任务- 医学专业术语保持原文,如检查项目名称、药物名称- 临床术语保持原文,如心电图、血常规-### 源文本:+## 诊疗记录:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -65,7 +66,8 @@ _NODE_PROMPT = """## 角色与任务### 领域特定规则- 医学专业术语保持原文,如检查项目名称、药物名称、症状名称-### 源文本:+## 诊疗记录:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -83,6 +85,12 @@ _EDGE_PROMPT = """## 角色与任务### 领域特定规则- 医学专业术语保持原文++## 已知节点:+{known_nodes}++## 诊疗记录:+{source_text}"""diff --git a/hyperextract/templates/zh/medicine/complex_interaction_net.py b/hyperextract/templates/zh/medicine/complex_interaction_net.pyindex 674fef9..9293cc7 100644--- a/hyperextract/templates/zh/medicine/complex_interaction_net.py+++ b/hyperextract/templates/zh/medicine/complex_interaction_net.py@@ -48,7 +48,8 @@ _PROMPT = """## 角色与任务- 药物名称保持原文,如二甲双胍、磺酰脲类- 不良反应名称保持原文-### 源文本:+## 药品说明书:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -66,7 +67,8 @@ _NODE_PROMPT = """## 角色与任务- 药物名称保持原文,如二甲双胍、磺酰脲类- 不良反应名称保持原文-### 源文本:+## 药品说明书:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -84,6 +86,12 @@ _EDGE_PROMPT = """## 角色与任务### 领域特定规则- 药物名称保持原文++## 已知实体:+{known_nodes}++## 药品说明书:+{source_text}"""diff --git a/hyperextract/templates/zh/medicine/contraindication_list.py b/hyperextract/templates/zh/medicine/contraindication_list.pyindex 6169902..e6f3dee 100644--- a/hyperextract/templates/zh/medicine/contraindication_list.py+++ b/hyperextract/templates/zh/medicine/contraindication_list.py@@ -37,7 +37,8 @@ _PROMPT = """## 角色与任务- 只提取文本中明确提及的禁忌症- 保持客观准确,不添加文本中没有的信息-### 源文本:+## 药品说明书:+{source_text}"""diff --git a/hyperextract/templates/zh/medicine/discharge_instruction.py b/hyperextract/templates/zh/medicine/discharge_instruction.pyindex f1df954..44c1f8c 100644--- a/hyperextract/templates/zh/medicine/discharge_instruction.py+++ b/hyperextract/templates/zh/medicine/discharge_instruction.py@@ -60,7 +60,8 @@ _PROMPT = """## 角色与任务- 只提取文本中明确提及的信息- 保持客观准确,不添加文本中没有的信息-### 源文本:+## 出院小结:+{source_text}"""diff --git a/hyperextract/templates/zh/medicine/hospital_course_timeline.py b/hyperextract/templates/zh/medicine/hospital_course_timeline.pyindex e4debe3..58957cb 100644--- a/hyperextract/templates/zh/medicine/hospital_course_timeline.py+++ b/hyperextract/templates/zh/medicine/hospital_course_timeline.py@@ -63,7 +63,8 @@ _PROMPT = """## 角色与任务### 领域特定规则- 医学术语保持原文-### 源文本:+## 病历文档:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -80,7 +81,8 @@ _NODE_PROMPT = """## 角色与任务### 领域特定规则- 医学术语保持原文-### 源文本:+## 病历文档:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -111,6 +113,12 @@ _EDGE_PROMPT = """## 角色与任务### 领域特定规则- 医学术语保持原文++## 已知实体:+{known_nodes}++## 病历文档:+{source_text}"""diff --git a/hyperextract/templates/zh/medicine/level_of_evidence.py b/hyperextract/templates/zh/medicine/level_of_evidence.pyindex f26655e..843d50a 100644--- a/hyperextract/templates/zh/medicine/level_of_evidence.py+++ b/hyperextract/templates/zh/medicine/level_of_evidence.py@@ -40,7 +40,8 @@ _PROMPT = """## 角色与任务- 只提取文本中明确提及的推荐意见和证据等级- 保持客观准确,不添加文本中没有的信息-### 源文本:+## 临床指南:+{source_text}"""diff --git a/hyperextract/templates/zh/medicine/medical_concept_net.py b/hyperextract/templates/zh/medicine/medical_concept_net.pyindex 26a0821..4229f0a 100644--- a/hyperextract/templates/zh/medicine/medical_concept_net.py+++ b/hyperextract/templates/zh/medicine/medical_concept_net.py@@ -52,7 +52,8 @@ _PROMPT = """## 角色与任务- 医学术语保持原文,如疾病名称、解剖部位名称- 专业缩写保持原文,如 ECG、CT、MRI-### 源文本:+## 医学文档:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -70,7 +71,8 @@ _NODE_PROMPT = """## 角色与任务- 医学术语保持原文,如疾病名称、解剖部位名称- 专业缩写保持原文-### 源文本:+## 医学文档:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -88,6 +90,12 @@ _EDGE_PROMPT = """## 角色与任务### 领域特定规则- 医学术语保持原文++## 已知概念:+{known_nodes}++## 医学文档:+{source_text}"""diff --git a/hyperextract/templates/zh/medicine/microscopic_feature_set.py b/hyperextract/templates/zh/medicine/microscopic_feature_set.pyindex 15dccdf..2c3fb6a 100644--- a/hyperextract/templates/zh/medicine/microscopic_feature_set.py+++ b/hyperextract/templates/zh/medicine/microscopic_feature_set.py@@ -40,7 +40,8 @@ _PROMPT = """## 角色与任务- 只提取文本中明确提及的特征和值- 保持客观准确,不添加文本中没有的信息-### 源文本:+## 病理报告:+{source_text}"""diff --git a/hyperextract/templates/zh/medicine/pathology_hypergraph.py b/hyperextract/templates/zh/medicine/pathology_hypergraph.pyindex 144d99b..e7b1251 100644--- a/hyperextract/templates/zh/medicine/pathology_hypergraph.py+++ b/hyperextract/templates/zh/medicine/pathology_hypergraph.py@@ -57,7 +57,8 @@ _PROMPT = """## 角色与任务- 医学专业术语保持原文,如基因名称(BRCA1、KRAS、TP53)、蛋白名称- 疾病名称保持原文,如慢性阻塞性肺疾病、肺癌-### 源文本:+## 病理文档:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -75,7 +76,8 @@ _NODE_PROMPT = """## 角色与任务- 医学专业术语保持原文,如基因名称(BRCA1、KRAS、TP53)、蛋白名称- 疾病名称保持原文-### 源文本:+## 病理文档:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -93,6 +95,12 @@ _EDGE_PROMPT = """## 角色与任务### 领域特定规则- 医学专业术语保持原文++## 已知实体:+{known_nodes}++## 病理文档:+{source_text}"""diff --git a/hyperextract/templates/zh/medicine/pharmacology_graph.py b/hyperextract/templates/zh/medicine/pharmacology_graph.pyindex 8a35a78..45d7446 100644--- a/hyperextract/templates/zh/medicine/pharmacology_graph.py+++ b/hyperextract/templates/zh/medicine/pharmacology_graph.py@@ -53,7 +53,8 @@ _PROMPT = """## 角色与任务- 受体名称保持原文,如胰岛素受体、肾上腺素受体- 信号通路名称保持原文,如AMPK通路、PI3K/Akt通路-### 源文本:+## 药理文档:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -72,7 +73,8 @@ _NODE_PROMPT = """## 角色与任务- 受体名称保持原文- 信号通路名称保持原文-### 源文本:+## 药理文档:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -90,6 +92,12 @@ _EDGE_PROMPT = """## 角色与任务### 领域特定规则- 药理学术语保持原文++## 已知实体:+{known_nodes}++## 药理文档:+{source_text}"""diff --git a/hyperextract/templates/zh/medicine/surgical_event_graph.py b/hyperextract/templates/zh/medicine/surgical_event_graph.pyindex 860ca44..eddafeb 100644--- a/hyperextract/templates/zh/medicine/surgical_event_graph.py+++ b/hyperextract/templates/zh/medicine/surgical_event_graph.py@@ -49,7 +49,8 @@ _PROMPT = """## 角色与任务- 手术术式保持原文,如冠状动脉旁路移植术- 医疗器械名称保持原文-### 源文本:+## 手术记录:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -67,7 +68,8 @@ _NODE_PROMPT = """## 角色与任务- 手术术式保持原文- 医疗器械名称保持原文-### 源文本:+## 手术记录:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -85,6 +87,12 @@ _EDGE_PROMPT = """## 角色与任务### 领域特定规则- 医学术语保持原文++## 已知实体:+{known_nodes}++## 手术记录:+{source_text}"""diff --git a/hyperextract/templates/zh/medicine/symptom_differential.py b/hyperextract/templates/zh/medicine/symptom_differential.pyindex 131433e..986a070 100644--- a/hyperextract/templates/zh/medicine/symptom_differential.py+++ b/hyperextract/templates/zh/medicine/symptom_differential.py@@ -37,7 +37,8 @@ _PROMPT = """## 角色与任务- 只提取文本中明确提及的症状和疾病- 保持客观准确,不添加文本中没有的信息-### 源文本:+## 诊断文档:+{source_text}"""diff --git a/hyperextract/templates/zh/medicine/treatment_regimen_map.py b/hyperextract/templates/zh/medicine/treatment_regimen_map.pyindex 22c068c..de11880 100644--- a/hyperextract/templates/zh/medicine/treatment_regimen_map.py+++ b/hyperextract/templates/zh/medicine/treatment_regimen_map.py@@ -48,7 +48,8 @@ _PROMPT = """## 角色与任务- 药物名称保持原文,如二甲双胍、阿司匹林- 治疗方式保持原文,如放疗、化疗、手术-### 源文本:+## 治疗方案文档:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -66,7 +67,8 @@ _NODE_PROMPT = """## 角色与任务- 药物名称保持原文,如二甲双胍、阿司匹林- 治疗方式保持原文-### 源文本:+## 治疗方案文档:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -84,6 +86,12 @@ _EDGE_PROMPT = """## 角色与任务### 领域特定规则- 医学术语保持原文++## 已知实体:+{known_nodes}++## 治疗方案文档:+{source_text}"""diff --git a/hyperextract/templates/zh/medicine/tumor_staging_item.py b/hyperextract/templates/zh/medicine/tumor_staging_item.pyindex 6b6ee6b..6f52bc7 100644--- a/hyperextract/templates/zh/medicine/tumor_staging_item.py+++ b/hyperextract/templates/zh/medicine/tumor_staging_item.py@@ -40,7 +40,8 @@ _PROMPT = """## 角色与任务- 只提取文本中明确提及的信息- 保持客观准确,不添加文本中没有的信息-### 源文本:+## 病理报告:+{source_text}"""diff --git a/hyperextract/templates/zh/news/complex_relation_net.py b/hyperextract/templates/zh/news/complex_relation_net.pyindex a996ca0..4cfc907 100644--- a/hyperextract/templates/zh/news/complex_relation_net.py+++ b/hyperextract/templates/zh/news/complex_relation_net.py@@ -44,7 +44,8 @@ _NODE_PROMPT = """## 角色与任务- 参与者类型:企业、个人、机构- 参与者描述要包含基本背景信息-### 源文本:+## 调查报道文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -64,6 +65,11 @@ _EDGE_PROMPT = """## 角色与任务- 关系类型:商业伙伴、政治盟友、家族成员、投资关系、担保关系- 描述多方之间的具体关联+## 已知参与者+{known_nodes}++## 调查报道文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -85,7 +91,8 @@ _PROMPT = """## 角色与任务- 参与者类型:企业、个人、机构- 关系类型:商业伙伴、政治盟友、家族成员、投资关系、担保关系-### 源文本:+## 调查报道文本:+{source_text}"""diff --git a/hyperextract/templates/zh/news/impact_chain.py b/hyperextract/templates/zh/news/impact_chain.pyindex 3c6d56c..4680e8a 100644--- a/hyperextract/templates/zh/news/impact_chain.py+++ b/hyperextract/templates/zh/news/impact_chain.py@@ -43,7 +43,8 @@ _NODE_PROMPT = """## 角色与任务- 节点类型:政策/事件(政策文件、重大事件)、影响群体(企业、消费者、经销商等)、预期后果(销量变化、价格调整、市场调整等)- 描述要包含简要信息-### 源文本:+## 政策分析文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -62,6 +63,11 @@ _EDGE_PROMPT = """## 角色与任务- 关系类型:影响(政策对群体的影响)、导致(原因导致结果)、预期(对未来趋势的预测)- 描述原因到结果的逻辑链条+## 已知实体+{known_nodes}++## 政策分析文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -82,7 +88,8 @@ _PROMPT = """## 角色与任务- 节点类型:政策/事件、影响群体、预期后果- 关系类型:影响、导致、预期-### 源文本:+## 政策分析文本:+{source_text}"""diff --git a/hyperextract/templates/zh/news/investigative_context_graph.py b/hyperextract/templates/zh/news/investigative_context_graph.pyindex d238999..3ff91dd 100644--- a/hyperextract/templates/zh/news/investigative_context_graph.py+++ b/hyperextract/templates/zh/news/investigative_context_graph.py@@ -45,7 +45,8 @@ _NODE_PROMPT = """## 角色与任务- 实体类型:人物(包含姓名、职务)、机构(公司、政府部门)、地点(地址、区域)- 人物描述要包含职务或身份信息-### 源文本:+## 调查报道文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -64,6 +65,11 @@ _EDGE_PROMPT = """## 角色与任务- 关系类型:任职(人物-机构)、亲属(人物-人物)、所属(机构-机构/个人)、所在地(机构/个人-地点)、投资(机构-机构)、抵押(机构-地点)- 描述两人之间的具体关系+## 已知实体+{known_nodes}++## 调查报道文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -85,7 +91,8 @@ _PROMPT = """## 角色与任务- 人物描述要包含职务或身份信息- 关系类型:任职、亲属、所属、所在地、投资、抵押-### 源文本:+## 调查报道文本:+{source_text}"""diff --git a/hyperextract/templates/zh/news/key_event_sequence.py b/hyperextract/templates/zh/news/key_event_sequence.pyindex fae6ee4..a846fe1 100644--- a/hyperextract/templates/zh/news/key_event_sequence.py+++ b/hyperextract/templates/zh/news/key_event_sequence.py@@ -43,7 +43,8 @@ _NODE_PROMPT = """## 角色与任务- 时间格式:年-月-日(如 2023-09-15),精确到日- 事件描述要包含简要信息-### 源文本:+## 调查报道文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -62,6 +63,11 @@ _EDGE_PROMPT = """## 角色与任务- 关系类型:紧接(紧接着发生)、导致(直接原因)、触发(导火索/间接原因)、升级(事态扩大)、回应(对某事件的回应)、协调(多方协商处理)、裁决(法律/官方判定)、调查(正在调查阶段)- 描述两事件之间的具体逻辑关系+## 已知事件+{known_nodes}++## 调查报道文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -83,7 +89,8 @@ _PROMPT = """## 角色与任务- 时间格式:年-月-日(如 2023-09-15),精确到日- 关系类型:紧接、导致、触发、升级、回应、协调、裁决、调查-### 源文本:+## 调查报道文本:+{source_text}"""diff --git a/hyperextract/templates/zh/news/live_update_timeline.py b/hyperextract/templates/zh/news/live_update_timeline.pyindex 5a2ee32..83192a6 100644--- a/hyperextract/templates/zh/news/live_update_timeline.py+++ b/hyperextract/templates/zh/news/live_update_timeline.py@@ -44,7 +44,8 @@ _NODE_PROMPT = """## 角色与任务- 简短名称要简洁明了- 发言人如无则为空白-### 源文本:+## 实时直播文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -63,6 +64,11 @@ _EDGE_PROMPT = """## 角色与任务- 关系类型:开场(会议开始)、介绍(介绍环节)、发布(正式发布)、发言(领导/发言人讲话)、提问(记者提问)、回答(回应问题)、总结(总结陈词)、结束(会议结束)- 描述两时间点之间的具体关系+## 已知时间点+{known_nodes}++## 实时直播文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -86,7 +92,8 @@ _PROMPT = """## 角色与任务- 关系类型:开场、介绍、发布、发言、提问、回答、总结、结束- 发言人如无则为空白-### 源文本:+## 实时直播文本:+{source_text}"""diff --git a/hyperextract/templates/zh/news/news_entity_graph.py b/hyperextract/templates/zh/news/news_entity_graph.pyindex 8b62cc3..e50f893 100644--- a/hyperextract/templates/zh/news/news_entity_graph.py+++ b/hyperextract/templates/zh/news/news_entity_graph.py@@ -44,7 +44,8 @@ _NODE_PROMPT = """## 角色与任务### 领域特定规则- 实体类型:人物、机构、地点、产品、事件-### 源文本:+## 新闻文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -62,6 +63,11 @@ _EDGE_PROMPT = """## 角色与任务### 领域特定规则- 关系类型:例如:发布、任命、收购等+## 已知实体+{known_nodes}++## 新闻文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -82,7 +88,8 @@ _PROMPT = """## 角色与任务- 实体类型:人物、机构、地点、产品、事件- 关系类型:例如:发布、任命、收购等-### 源文本:+## 新闻文本:+{source_text}"""diff --git a/hyperextract/templates/zh/news/news_summary_model.py b/hyperextract/templates/zh/news/news_summary_model.pyindex 2008e70..12c2c7b 100644--- a/hyperextract/templates/zh/news/news_summary_model.py+++ b/hyperextract/templates/zh/news/news_summary_model.py@@ -42,7 +42,8 @@ _PROMPT = """## 角色与任务- 时间格式统一为年-月-日或具体时间点- 地点要具体到城市或区域-### 源文本:+## 新闻文本:+{source_text}"""diff --git a/hyperextract/templates/zh/news/viewpoint_structure.py b/hyperextract/templates/zh/news/viewpoint_structure.pyindex 7cc2983..a623838 100644--- a/hyperextract/templates/zh/news/viewpoint_structure.py+++ b/hyperextract/templates/zh/news/viewpoint_structure.py@@ -47,7 +47,8 @@ _NODE_PROMPT = """## 角色与任务- **背景引用**:政策文件、统计数据、专家说法等外部引用(如"根据国家统计局2023年数据")- 来源如无则为空白-### 源文本:+## 政策分析文本:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -72,6 +73,11 @@ _EDGE_PROMPT = """## 角色与任务- 一个观点可以参与多个超边(从不同角度论证)- 描述应说明这些元素如何共同支撑观点+## 已知论证元素+{known_nodes}++## 政策分析文本:+{source_text}"""_PROMPT = """## 角色与任务@@ -93,7 +99,8 @@ _PROMPT = """## 角色与任务- **论据**:支撑观点的证据或分析- **背景引用**:政策文件、统计数据、专家说法-### 源文本:+## 政策分析文本:+{source_text}"""diff --git a/hyperextract/templates/zh/tcm/acupoint_location_map.py b/hyperextract/templates/zh/tcm/acupoint_location_map.pyindex 62c5141..cd8b601 100644--- a/hyperextract/templates/zh/tcm/acupoint_location_map.py+++ b/hyperextract/templates/zh/tcm/acupoint_location_map.py@@ -44,7 +44,8 @@ _PROMPT = """## 角色与任务- 穴位:针灸特定位置,如合谷、足三里、三阴交- 解剖标志:人体解剖部位,如腕横纹、第2掌骨-### 源文本:+## 针灸文献:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -62,7 +63,8 @@ _NODE_PROMPT = """## 角色与任务- 穴位:针灸特定位置- 解剖标志:人体解剖部位-### 源文本:+## 针灸文献:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -76,7 +78,11 @@ _EDGE_PROMPT = """## 角色与任务1. 仅从已知穴位列表中提取边,不要创建未列出的穴位2. 关系描述应与原文保持一致-### 已知穴位列表:+## 已知穴位列表:+{known_nodes}++## 针灸文献:+{source_text}"""diff --git a/hyperextract/templates/zh/tcm/compatibility_net.py b/hyperextract/templates/zh/tcm/compatibility_net.pyindex 1ee91dc..271f496 100644--- a/hyperextract/templates/zh/tcm/compatibility_net.py+++ b/hyperextract/templates/zh/tcm/compatibility_net.py@@ -43,7 +43,8 @@ _PROMPT = """## 角色与任务### 领域特定规则- 配伍关系类型:相须、相使、相畏、相杀、相恶、相反、十八反、十九畏-### 源文本:+## 中药配伍文献:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -57,7 +58,8 @@ _NODE_PROMPT = """## 角色与任务1. 每个节点只能对应一个独立的实体,禁止将多个实体合并为一个节点2. 实体名称与原文保持一致-### 源文本:+## 中药配伍文献:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -71,7 +73,11 @@ _EDGE_PROMPT = """## 角色与任务1. 仅从已知药物列表中提取边,不要创建未列出的药物2. 关系描述应与原文保持一致-### 已知药物列表:+## 已知药物列表:+{known_nodes}++## 中药配伍文献:+{source_text}"""diff --git a/hyperextract/templates/zh/tcm/formula_composition.py b/hyperextract/templates/zh/tcm/formula_composition.pyindex 4e6f262..4f0276e 100644--- a/hyperextract/templates/zh/tcm/formula_composition.py+++ b/hyperextract/templates/zh/tcm/formula_composition.py@@ -61,7 +61,8 @@ _PROMPT = """## 角色与任务- 药物固有属性:性味、归经、功效(不随方剂变化)- 药物在方剂中的属性:剂量、炮制方法、角色(君/臣/佐/使)-### 源文本:+## 方剂文献:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -78,7 +79,8 @@ _NODE_PROMPT = """## 角色与任务### 领域特定规则- 药物固有属性:性味、归经、功效-### 源文本:+## 方剂文献:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -95,7 +97,11 @@ _EDGE_PROMPT = """## 角色与任务### 领域特定规则- 药物角色:君药、臣药、佐药、使药-### 已知药物列表:+## 已知药物列表:+{known_nodes}++## 方剂文献:+{source_text}"""diff --git a/hyperextract/templates/zh/tcm/function_indication_map.py b/hyperextract/templates/zh/tcm/function_indication_map.pyindex 857207b..280508e 100644--- a/hyperextract/templates/zh/tcm/function_indication_map.py+++ b/hyperextract/templates/zh/tcm/function_indication_map.py@@ -44,7 +44,8 @@ _PROMPT = """## 角色与任务- 功能:如解肌发表、清热解毒- 主治证候:如太阳中风、外感风寒-### 源文本:+## 方剂文献:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -63,7 +64,8 @@ _NODE_PROMPT = """## 角色与任务- 功能:如解肌发表、清热解毒- 主治证候:如太阳中风、外感风寒-### 源文本:+## 方剂文献:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -77,7 +79,11 @@ _EDGE_PROMPT = """## 角色与任务1. 仅从已知实体列表中提取边,不要创建未列出的实体2. 关系描述应与原文保持一致-### 已知实体列表:+## 已知实体列表:+{known_nodes}++## 方剂文献:+{source_text}"""diff --git a/hyperextract/templates/zh/tcm/herb_property_model.py b/hyperextract/templates/zh/tcm/herb_property_model.pyindex ecce677..4c1b770 100644--- a/hyperextract/templates/zh/tcm/herb_property_model.py+++ b/hyperextract/templates/zh/tcm/herb_property_model.py@@ -44,7 +44,8 @@ _PROMPT = """## 角色与任务- 连写拆分:文言中常连写多个属性(如"味甘微寒"→拆分为"味甘"、"微寒"),需分别归到对应字段- 古代剂量:文言中古代剂量单位(如两、钱、匕)可保留原文-### 源文本:+## 本草文献:+{source_text}"""diff --git a/hyperextract/templates/zh/tcm/meridian_flow_graph.py b/hyperextract/templates/zh/tcm/meridian_flow_graph.pyindex 3ab446f..58f8ef7 100644--- a/hyperextract/templates/zh/tcm/meridian_flow_graph.py+++ b/hyperextract/templates/zh/tcm/meridian_flow_graph.py@@ -45,7 +45,8 @@ _PROMPT = """## 角色与任务- 经脉:十二经脉,如手太阴肺经、手阳明大肠经- 经脉类别:阴经、阳经-### 源文本:+## 经络文献:+{source_text}"""_NODE_PROMPT = """## 角色与任务@@ -63,7 +64,8 @@ _NODE_PROMPT = """## 角色与任务- 经脉:十二经脉- 经脉类别:阴经、阳经-### 源文本:+## 经络文献:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -77,7 +79,11 @@ _EDGE_PROMPT = """## 角色与任务1. 仅从已知经脉列表中提取边,不要创建未列出的经脉2. 关系描述应与原文保持一致-### 已知经脉列表:+## 已知经脉节点列表:+{known_nodes}++## 经络文献:+{source_text}"""diff --git a/hyperextract/templates/zh/tcm/prescription_modification.py b/hyperextract/templates/zh/tcm/prescription_modification.pyindex b12ec77..e64a8ee 100644--- a/hyperextract/templates/zh/tcm/prescription_modification.py+++ b/hyperextract/templates/zh/tcm/prescription_modification.py@@ -48,7 +48,8 @@ _NODE_PROMPT = """## 角色与任务- 药物:中药名称,如葛根、厚朴、杏仁、附子- 证型/症状:临床表现,如项背强几几、喘、腹满痛-### 源文本:+## 处方文献:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -66,7 +67,11 @@ _EDGE_PROMPT = """## 角色与任务### 领域特定规则- 加减类型:加、减、替换(通过 modificationType 字段区分)-### 已知实体列表:+## 已知实体列表:+{known_nodes}++## 处方文献:+{source_text}"""_PROMPT = """## 角色与任务@@ -88,7 +93,8 @@ _PROMPT = """## 角色与任务- 证型/症状:临床表现,如项背强几几、喘、腹满痛- 加减类型:加、减、替换-### 源文本:+## 处方文献:+{source_text}"""diff --git a/hyperextract/templates/zh/tcm/processing_method.py b/hyperextract/templates/zh/tcm/processing_method.pyindex 65ca9ec..ca512d6 100644--- a/hyperextract/templates/zh/tcm/processing_method.py+++ b/hyperextract/templates/zh/tcm/processing_method.py@@ -35,7 +35,8 @@ _PROMPT = """## 角色与任务### 领域特定规则- 常用炮制方法:蜜炙、酒炒、醋制、盐制、炒、煅等-### 源文本:+## 药物炮制文献:+{source_text}"""diff --git a/hyperextract/templates/zh/tcm/pulse_tongue_record.py b/hyperextract/templates/zh/tcm/pulse_tongue_record.pyindex 4e847f2..185ed99 100644--- a/hyperextract/templates/zh/tcm/pulse_tongue_record.py+++ b/hyperextract/templates/zh/tcm/pulse_tongue_record.py@@ -36,7 +36,8 @@ _PROMPT = """## 角色与任务- 脉象术语理解:文言脉象术语需准确识别(如"浮紧脉"→浮脉、紧脉)- 复合特征拆分:文言中常将多个特征合并描述,需分别提取到对应字段-### 源文本:+## 诊断记录:+{source_text}"""# ==============================================================================diff --git a/hyperextract/templates/zh/tcm/syndrome_reasoning_graph.py b/hyperextract/templates/zh/tcm/syndrome_reasoning_graph.pyindex 90780d3..f80501f 100644--- a/hyperextract/templates/zh/tcm/syndrome_reasoning_graph.py+++ b/hyperextract/templates/zh/tcm/syndrome_reasoning_graph.py@@ -47,7 +47,8 @@ _NODE_PROMPT = """## 角色与任务- 治则:治疗原则,如解肌发表、调和营卫- 药物:中药名称,如桂枝、麻黄、杏仁-### 源文本:+## 中医医案:+{source_text}"""_EDGE_PROMPT = """## 角色与任务@@ -66,7 +67,11 @@ _EDGE_PROMPT = """## 角色与任务- 推理类型:辨证论治、随证加减- 推理链条:症状群 → 证型 → 治则 → 处方-### 已知实体列表:+## 已知实体列表:+{known_nodes}++## 中医医案:+{source_text}"""_PROMPT = """## 角色与任务@@ -90,7 +95,8 @@ _PROMPT = """## 角色与任务- 推理类型:辨证论治、随证加减- 推理链条:症状群 → 证型 → 治则 → 处方-### 源文本:+## 中医医案:+{source_text}"""diff --git a/hyperextract/types/base.py b/hyperextract/types/base.pyindex 6ba9ec8..05cb238 100644--- a/hyperextract/types/base.py+++ b/hyperextract/types/base.py@@ -68,6 +68,13 @@ class BaseAutoType(ABC, Generic[T]):self.max_workers = max_workersself.verbose = verbose+ # Initialize template+ self.prompt_template = ChatPromptTemplate.from_template(self.prompt)+ self.data_extractor = (+ self.prompt_template+ | self.llm_client.with_structured_output(self._data_schema)+ )+# Initialize text splitter for chunking long documentsself.text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size,@@ -235,31 +242,15 @@ class BaseAutoType(ABC, Generic[T]):# ==================== Extraction & Merge ====================def _extract_data(self, text: str) -> T:- """- Internal: Unified extraction logic (Chunking -> LLM -> Merge).- Implemented in BaseAutoType for code reuse by List and Set.-- Args:- text: Input text.-- Returns:- The extracted knowledge data.- """-- prompt_template = ChatPromptTemplate.from_template(- f"{self.prompt}{{chunk_text}}"- )- llm_chain = prompt_template | self.llm_client.with_structured_output(- self._data_schema- )+ """Internal: Unified extraction logic (Chunking -> LLM -> Merge)."""if len(text) <= self.chunk_size:- extracted_data = llm_chain.invoke({"chunk_text": text})+ extracted_data = self.data_extractor.invoke({"source_text": text})extracted_data_list = [extracted_data]else:chunks = self.text_splitter.split_text(text)- inputs = [{"chunk_text": chunk} for chunk in chunks]- extracted_data_list = llm_chain.batch(+ inputs = [{"source_text": chunk} for chunk in chunks]+ extracted_data_list = self.data_extractor.batch(inputs, config={"max_concurrency": self.max_workers})@@ -390,7 +381,9 @@ class BaseAutoType(ABC, Generic[T]):if isinstance(item, BaseModel):formatted_context.append(item.model_dump_json(indent=2))elif isinstance(item, dict):- formatted_context.append(json.dumps(item, indent=2, ensure_ascii=False))+ formatted_context.append(+ json.dumps(item, indent=2, ensure_ascii=False)+ )elif isinstance(item, str):formatted_context.append(item)else:diff --git a/hyperextract/types/graph.py b/hyperextract/types/graph.pyindex c3f7119..06183fa 100644--- a/hyperextract/types/graph.py+++ b/hyperextract/types/graph.py@@ -43,6 +43,7 @@ DEFAULT_GRAPH_PROMPT = ("CRITICAL CONSTRAINT: Every edge must connect two nodes that are present in the extracted nodes list. ""Do not create edges between entities that are not explicitly identified as nodes.\n\n""### Source Text:\n"+ "{source_text}")DEFAULT_NODE_PROMPT = (@@ -54,6 +55,7 @@ DEFAULT_NODE_PROMPT = ("- Clarity: provide clear, concise descriptions for each entity\n\n""Do not attempt to extract relationships at this stage, only identify entities.\n\n""### Source Text:\n"+ "{source_text}")DEFAULT_EDGE_PROMPT = (@@ -64,6 +66,10 @@ DEFAULT_EDGE_PROMPT = ("2. DO NOT invent or hallucinate new entities that are not listed\n""3. If an entity in the text is not in the known list, DO NOT create edges involving it\n""4. Focus on explicit relationships mentioned in the text\n\n"+ "# Provided Entities\n"+ "{known_nodes}\n\n"+ "# Source Text:\n"+ "{source_text}")@@ -209,10 +215,7 @@ class AutoGraph(# Persist kwargs for reconstructionself._constructor_kwargs = kwargs- # Initialize prompts (use custom if provided, otherwise use defaults)- self.node_prompt = prompt_for_node_extraction or DEFAULT_NODE_PROMPT- self.edge_prompt = prompt_for_edge_extraction or DEFAULT_EDGE_PROMPT-+ graph_prompt = prompt or self._default_prompt()# Create dynamic GraphSchema containersgraph_schema_name = f"{node_schema.__name__}{edge_schema.__name__}Graph"self.graph_schema = create_model(@@ -287,13 +290,30 @@ class AutoGraph(data_schema=self.graph_schema,llm_client=llm_client,embedder=embedder,- prompt=prompt or self._default_prompt(),+ prompt=graph_prompt,chunk_size=chunk_size,chunk_overlap=chunk_overlap,max_workers=max_workers,verbose=verbose,)+ # Initialize prompts (use custom if provided, otherwise use defaults)+ self.node_prompt = prompt_for_node_extraction or DEFAULT_NODE_PROMPT+ self.edge_prompt = prompt_for_edge_extraction or DEFAULT_EDGE_PROMPT++ # Two-stage mode: initialize extractors+ self.prompt_template = ChatPromptTemplate.from_template(self.node_prompt)+ self.node_extractor = (+ self.prompt_template+ | self.llm_client.with_structured_output(self.node_list_schema)+ )++ self.edge_prompt_template = ChatPromptTemplate.from_template(self.edge_prompt)+ self.edge_extractor = (+ self.edge_prompt_template+ | self.llm_client.with_structured_output(self.edge_list_schema)+ )+def _default_prompt(self) -> str:"""Returns the default prompt for one-stage graph extraction."""return DEFAULT_GRAPH_PROMPT@@ -443,21 +463,14 @@ class AutoGraph(Returns:Raw extracted graph data."""- prompt_template = ChatPromptTemplate.from_template(- f"{self.prompt}{{chunk_text}}"- )- llm_chain = prompt_template | self.llm_client.with_structured_output(- self.graph_schema- )- # Extract from single chunk or multiple chunksif len(text) <= self.chunk_size:- graph = llm_chain.invoke({"chunk_text": text})+ graph = self.data_extractor.invoke({"source_text": text})graph_list = [graph]else:chunks = self.text_splitter.split_text(text)- inputs = [{"chunk_text": chunk} for chunk in chunks]- graph_list = llm_chain.batch(+ inputs = [{"source_text": chunk} for chunk in chunks]+ graph_list = self.data_extractor.batch(inputs, config={"max_concurrency": self.max_workers})@@ -514,16 +527,11 @@ class AutoGraph(Returns:List of NodeListSchema objects with extracted nodes."""- prompt_template = ChatPromptTemplate.from_template(- f"{self.node_prompt}{{chunk_text}}"- )- llm_chain = prompt_template | self.llm_client.with_structured_output(- self.node_list_schema+ inputs = [{"source_text": chunk} for chunk in chunks]+ return self.node_extractor.batch(+ inputs, config={"max_concurrency": self.max_workers})- inputs = [{"chunk_text": chunk} for chunk in chunks]- return llm_chain.batch(inputs, config={"max_concurrency": self.max_workers})-def _extract_edges_batch(self, chunks: List[str], node_lists: List[NodeListSchema[NodeSchema]]) -> List[EdgeListSchema[EdgeSchema]]:@@ -540,22 +548,17 @@ class AutoGraph(for chunk, node_list in zip(chunks, node_lists):nodes = node_list.items if node_list else []if not nodes:- node_context = "No specific entities identified in this chunk."+ known_nodes = "No specific entities identified in this chunk."else:node_keys = [self.node_key_extractor(n) for n in nodes]- node_context = "Known entities: " + "\n- ".join(node_keys)+ known_nodes = "\n- ".join(node_keys)- inputs.append({"chunk_text": chunk, "node_context": node_context})+ inputs.append({"source_text": chunk, "known_nodes": known_nodes})- prompt_template = ChatPromptTemplate.from_template(- f"{self.edge_prompt}{{node_context}}\n\n### Source Text:\n{{chunk_text}}"- )- llm_chain = prompt_template | self.llm_client.with_structured_output(- self.edge_list_schema+ return self.edge_extractor.batch(+ inputs, config={"max_concurrency": self.max_workers})- return llm_chain.batch(inputs, config={"max_concurrency": self.max_workers})-def _prune_dangling_edges(self, graph: AutoGraphSchema[NodeSchema, EdgeSchema]) -> AutoGraphSchema[NodeSchema, EdgeSchema]:@@ -895,10 +898,18 @@ class AutoGraph()def search_callback(query: str) -> None:- return self.search(query, top_k_nodes=top_k_nodes_for_search, top_k_edges=top_k_edges_for_search)+ return self.search(+ query,+ top_k_nodes=top_k_nodes_for_search,+ top_k_edges=top_k_edges_for_search,+ )def chat_callback(question: str) -> None:- response = self.chat(question, top_k_nodes=top_k_nodes_for_chat, top_k_edges=top_k_edges_for_chat)+ response = self.chat(+ question,+ top_k_nodes=top_k_nodes_for_chat,+ top_k_edges=top_k_edges_for_chat,+ )content = response.contentretrieved_nodes = response.additional_kwargs.get("retrieved_nodes", [])retrieved_edges = response.additional_kwargs.get("retrieved_edges", [])diff --git a/hyperextract/types/hypergraph.py b/hyperextract/types/hypergraph.pyindex 0388c67..f8efa5d 100644--- a/hyperextract/types/hypergraph.py+++ b/hyperextract/types/hypergraph.py@@ -48,12 +48,14 @@ CRITICAL RULES:5. A Hyperedge represents a Grouping, Event, or Complex Relation involving the listed participants.### Source Text:+{source_text}"""DEFAULT_NODE_PROMPT = """Extract all distinct entities from the text.Entities will serve as participants in complex events later.### Source Text:+{source_text}"""DEFAULT_EDGE_PROMPT = """You are an expert hypergraph extraction assistant.@@ -65,6 +67,11 @@ CRITICAL RULES:3. ONLY use entities from the provided 'Known Entities' list.4. If an entity is not in the list, exclude it from the hyperedge.+# Provided Entities+{known_nodes}++# Source Text:+{source_text}"""@@ -218,9 +225,7 @@ class AutoHypergraph(self.max_workers = max_workersself.verbose = verbose- # Initialize prompts- self.node_prompt = prompt_for_node_extraction or DEFAULT_NODE_PROMPT- self.edge_prompt = prompt_for_edge_extraction or DEFAULT_EDGE_PROMPT+ graph_prompt = prompt or DEFAULT_HYPERGRAPH_PROMPT# Create dynamic HypergraphSchemagraph_schema_name = f"{node_schema.__name__}{edge_schema.__name__}Hypergraph"@@ -290,13 +295,30 @@ class AutoHypergraph(data_schema=self.graph_schema,llm_client=llm_client,embedder=embedder,- prompt=prompt or DEFAULT_HYPERGRAPH_PROMPT,+ prompt=graph_prompt,chunk_size=chunk_size,chunk_overlap=chunk_overlap,max_workers=max_workers,verbose=verbose,)+ # Initialize prompts+ self.node_prompt = prompt_for_node_extraction or DEFAULT_NODE_PROMPT+ self.edge_prompt = prompt_for_edge_extraction or DEFAULT_EDGE_PROMPT++ # Two-stage mode: validate prompts and initialize extractors+ self.prompt_template = ChatPromptTemplate.from_template(self.node_prompt)+ self.node_extractor = (+ self.prompt_template+ | self.llm_client.with_structured_output(self.node_list_schema)+ )++ self.edge_prompt_template = ChatPromptTemplate.from_template(self.edge_prompt)+ self.edge_extractor = (+ self.edge_prompt_template+ | self.llm_client.with_structured_output(self.edge_list_schema)+ )+# ==================== Prompts ====================def _default_prompt(self) -> str:@@ -415,21 +437,14 @@ class AutoHypergraph(Returns:Raw extracted hypergraph data."""- prompt_template = ChatPromptTemplate.from_template(- f"{self.prompt}{{chunk_text}}"- )- llm_chain = prompt_template | self.llm_client.with_structured_output(- self.graph_schema- )-# Extract from single chunk or multiple chunksif len(text) <= self.chunk_size:- graph = llm_chain.invoke({"chunk_text": text})+ graph = self.data_extractor.invoke({"source_text": text})graph_list = [graph]else:chunks = self.text_splitter.split_text(text)- inputs = [{"chunk_text": chunk} for chunk in chunks]- graph_list = llm_chain.batch(+ inputs = [{"source_text": chunk} for chunk in chunks]+ graph_list = self.data_extractor.batch(inputs, config={"max_concurrency": self.max_workers})@@ -473,16 +488,11 @@ class AutoHypergraph(self, chunks: List[str]) -> List[NodeListSchema[NodeSchema]]:"""Batch extract nodes from multiple text chunks."""- prompt_template = ChatPromptTemplate.from_template(- f"{self.node_prompt}{{chunk_text}}"- )- llm_chain = prompt_template | self.llm_client.with_structured_output(- self.node_list_schema+ inputs = [{"source_text": chunk} for chunk in chunks]+ return self.node_extractor.batch(+ inputs, config={"max_concurrency": self.max_workers})- inputs = [{"chunk_text": chunk} for chunk in chunks]- return llm_chain.batch(inputs, config={"max_concurrency": self.max_workers})-def _extract_edges_batch(self, chunks: List[str], node_lists: List[NodeListSchema[NodeSchema]]) -> List[EdgeListSchema[EdgeSchema]]:@@ -491,22 +501,17 @@ class AutoHypergraph(for chunk, node_list in zip(chunks, node_lists):nodes = node_list.items if node_list else []if not nodes:- node_context = "No entities identified in this chunk."+ known_nodes = "No entities identified in this chunk."else:- node_keys = [f"- {self.node_key_extractor(n)}" for n in nodes]- node_context = "Known entities: " + "\n- ".join(node_keys)+ node_keys = [self.node_key_extractor(n) for n in nodes]+ known_nodes = "\n- ".join(node_keys)- inputs.append({"chunk_text": chunk, "node_context": node_context})+ inputs.append({"source_text": chunk, "known_nodes": known_nodes})- prompt_template = ChatPromptTemplate.from_template(- f"{self.edge_prompt}{{node_context}}\n\n### Source Text:\n{{chunk_text}}"- )- llm_chain = prompt_template | self.llm_client.with_structured_output(- self.edge_list_schema+ return self.edge_extractor.batch(+ inputs, config={"max_concurrency": self.max_workers})- return llm_chain.batch(inputs, config={"max_concurrency": self.max_workers})-def _prune_dangling_edges(self, graph: AutoHypergraphSchema) -> AutoHypergraphSchema:@@ -838,10 +843,18 @@ class AutoHypergraph()def search_callback(query: str) -> None:- return self.search(query, top_k_nodes=top_k_nodes_for_search, top_k_edges=top_k_edges_for_search)+ return self.search(+ query,+ top_k_nodes=top_k_nodes_for_search,+ top_k_edges=top_k_edges_for_search,+ )def chat_callback(question: str) -> None:- response = self.chat(question, top_k_nodes=top_k_nodes_for_chat, top_k_edges=top_k_edges_for_chat)+ response = self.chat(+ question,+ top_k_nodes=top_k_nodes_for_chat,+ top_k_edges=top_k_edges_for_chat,+ )content = response.contentretrieved_nodes = response.additional_kwargs.get("retrieved_nodes", [])retrieved_edges = response.additional_kwargs.get("retrieved_edges", [])diff --git a/hyperextract/types/list.py b/hyperextract/types/list.pyindex 6a70a9e..c54ed2e 100644--- a/hyperextract/types/list.py+++ b/hyperextract/types/list.py@@ -27,6 +27,16 @@ from hyperextract.utils.logging import loggerItemSchema = TypeVar("ItemSchema", bound=BaseModel)+DEFAULT_LIST_PROMPT = (+ "You are an expert knowledge extraction assistant. "+ "Extract all relevant items from the text into a list. "+ "Be comprehensive and ensure no item is missed. "+ "Extract all items without adding information not present in the text.\n\n"+ "### Source Text:\n"+ "{source_text}"+)++class AutoListSchema(BaseModel, Generic[ItemSchema]):"""Generic schema container for list-based knowledge patterns."""@@ -113,13 +123,7 @@ class AutoList(BaseAutoType[AutoListSchema[ItemSchema]], Generic[ItemSchema]):def _default_prompt(self) -> str:"""Returns the default extraction prompt for list-based extraction."""- return (- "You are an expert knowledge extraction assistant. "- "Extract all relevant items from the text into a list. "- "Be comprehensive and ensure no item is missed. "- "Extract all items without adding information not present in the text.\n\n"- "### Source Text:\n"- )+ return DEFAULT_LIST_PROMPT@propertydef items(self) -> List[ItemSchema]:diff --git a/hyperextract/types/model.py b/hyperextract/types/model.pyindex b284479..6f5ca34 100644--- a/hyperextract/types/model.py+++ b/hyperextract/types/model.py@@ -14,6 +14,16 @@ from .base import BaseAutoType, Tfrom hyperextract.utils.logging import logger+DEFAULT_MODEL_PROMPT = (+ "You are an expert knowledge extraction assistant. "+ "Your task is to carefully analyze the following text and extract structured information "+ "according to the specified schema. Be precise, comprehensive, and faithful to the source text. "+ "Extract all relevant details without adding information not present in the text.\n\n"+ "### Source Text:\n"+ "{source_text}"+)++class AutoModel(BaseAutoType[T]):"""AutoModel - extracts a single structured object from text.@@ -118,13 +128,7 @@ class AutoModel(BaseAutoType[T]):def _default_prompt(self) -> str:"""Returns the default extraction prompt for single-object extraction."""- return (- "You are an expert knowledge extraction assistant. "- "Your task is to carefully analyze the following text and extract structured information "- "according to the specified schema. Be precise, comprehensive, and faithful to the source text. "- "Extract all relevant details without adding information not present in the text.\n\n"- "### Source Text:\n"- )+ return DEFAULT_MODEL_PROMPT@propertydef data(self) -> T:diff --git a/hyperextract/types/set.py b/hyperextract/types/set.pyindex c9fcd35..9ac496c 100644--- a/hyperextract/types/set.py+++ b/hyperextract/types/set.py@@ -30,6 +30,16 @@ from hyperextract.utils.logging import loggerItemSchema = TypeVar("ItemSchema", bound=BaseModel)+DEFAULT_SET_PROMPT = (+ "You are an expert knowledge extraction assistant. "+ "Extract all unique items from the text into a set. "+ "Be comprehensive and ensure no item is missed. "+ "Extract all items without adding information not present in the text.\n\n"+ "### Source Text:\n"+ "{source_text}"+)++class AutoSetSchema(BaseModel, Generic[ItemSchema]):"""Generic schema container for set-based knowledge patterns."""@@ -212,13 +222,7 @@ class AutoSet(BaseAutoType[AutoSetSchema[ItemSchema]], Generic[ItemSchema]):def _default_prompt(self) -> str:"""Returns the default extraction prompt for set-based extraction."""- return (- "You are an expert knowledge extraction assistant. "- "Extract all unique items from the text into a set. "- "Be comprehensive and ensure no item is missed. "- "Extract all items without adding information not present in the text.\n\n"- "### Source Text:\n"- )+ return DEFAULT_SET_PROMPT@propertydef data(self) -> AutoSetSchema[ItemSchema]:diff --git a/hyperextract/types/spatial_graph.py b/hyperextract/types/spatial_graph.pyindex d8cce7c..a53ac3f 100644--- a/hyperextract/types/spatial_graph.py+++ b/hyperextract/types/spatial_graph.py@@ -2,7 +2,6 @@from typing import Type, Callable, Tuple, Any, Listfrom langchain_core.language_models import BaseChatModel-from langchain_core.prompts import ChatPromptTemplatefrom langchain_core.embeddings import Embeddingsfrom ontomem.merger import MergeStrategy, BaseMerger@@ -32,6 +31,7 @@ DEFAULT_SPATIAL_NODE_RULES_SUFFIX = """Spatial context belongs to the relationships between entities.### Source Text:+{source_text}"""# Edge Extraction Prompts@@ -58,6 +58,11 @@ Current Observation Location: {observation_location}2. DO NOT create edges involving entities that are not listed.3. Use the defined schema fields for location as specified in the output format.+# Provided Entities+{known_nodes}++# Source Text:+{source_text}"""# One-Stage Graph Extraction Prompts@@ -79,6 +84,7 @@ Current Observation Location: {observation_location}3. **Missing Space**: Leave location fields empty if not present.### Source Text:+{source_text}"""@@ -245,57 +251,46 @@ class AutoSpatialGraph(AutoGraph[NodeSchema, EdgeSchema]):def _extract_edges_batch(self, chunks: List[str], node_lists: List[NodeListSchema[NodeSchema]]) -> List[EdgeListSchema[EdgeSchema]]:- """- Override: Inject observation_location into edge extraction during two-stage extraction.- """+ """Override: Inject observation_location into edge extraction during two-stage extraction."""inputs = []for chunk, node_list in zip(chunks, node_lists):nodes = node_list.items if node_list else []- node_context = "Known entities: " + "\n- ".join([self.node_key_extractor(n) for n in nodes]) if nodes else "No specific entities identified."-- inputs.append({- "chunk_text": chunk,- "node_context": node_context,- "observation_location": self.observation_location,- })+ known_nodes = (+ "\n- ".join([self.node_key_extractor(n) for n in nodes])+ if nodes+ else "No specific entities identified."+ )- # Ensure observation_location is explicitly in the prompt if not already part of self.edge_prompt- prompt_with_location = f"Current location context: {{observation_location}}\n\n{self.edge_prompt}"-- prompt_template = ChatPromptTemplate.from_template(- f"{prompt_with_location}{{node_context}}\n\n### Source Text:\n{{chunk_text}}"- )- llm_chain = prompt_template | self.llm_client.with_structured_output(- self.edge_list_schema- )+ inputs.append(+ {+ "source_text": chunk,+ "known_nodes": known_nodes,+ "observation_location": self.observation_location,+ }+ )- return llm_chain.batch(inputs, config={"max_concurrency": self.max_workers})+ return self.edge_extractor.batch(inputs, config={"max_concurrency": self.max_workers})def _extract_data_by_one_stage(self, text: str) -> Any:- """- Override: Inject observation_location into one-stage extraction.- """- prompt_with_location = f"Current location context: {{observation_location}}\n\n{self.prompt}"- template_str = f"{prompt_with_location}{{chunk_text}}"- prompt_template = ChatPromptTemplate.from_template(template_str)- llm_chain = prompt_template | self.llm_client.with_structured_output(- self.graph_schema- )+ """Override: Inject observation_location into one-stage extraction."""if len(text) <= self.chunk_size:inp = {- "chunk_text": text,+ "source_text": text,"observation_location": self.observation_location,}- graph = llm_chain.invoke(inp)+ graph = self.data_extractor.invoke(inp)graph_list = [graph]else:chunks = self.text_splitter.split_text(text)inputs = [- {"chunk_text": chunk, "observation_location": self.observation_location}+ {+ "source_text": chunk,+ "observation_location": self.observation_location,+ }for chunk in chunks]- graph_list = llm_chain.batch(+ graph_list = self.data_extractor.batch(inputs, config={"max_concurrency": self.max_workers})diff --git a/hyperextract/types/spatio_temporal_graph.py b/hyperextract/types/spatio_temporal_graph.pyindex f102f05..be2a15e 100644--- a/hyperextract/types/spatio_temporal_graph.py+++ b/hyperextract/types/spatio_temporal_graph.py@@ -3,7 +3,6 @@from typing import Type, Callable, Tuple, Any, Listfrom datetime import datetimefrom langchain_core.language_models import BaseChatModel-from langchain_core.prompts import ChatPromptTemplatefrom langchain_core.embeddings import Embeddingsfrom ontomem.merger import MergeStrategy, BaseMerger@@ -34,6 +33,7 @@ DEFAULT_SPATIO_TEMPORAL_NODE_RULES_SUFFIX = """4. **Exclude Pure Numbers**: Do not extract standalone amounts or numeric values as independent nodes.### Source Text:+{source_text}"""# Edge Extraction Prompts@@ -67,6 +67,11 @@ Current Observation Location: {observation_location}2. DO NOT create edges involving entities that are not listed.3. Use the defined schema fields for time and space as specified in the output format.+# Provided Entities+{known_nodes}++# Source Text:+{source_text}"""# One-Stage Graph Extraction Prompts@@ -91,6 +96,7 @@ Current Observation Location: {observation_location}4. **Missing Information**: Leave time/location fields empty if not present.### Source Text:+{source_text}"""@@ -265,57 +271,45 @@ class AutoSpatioTemporalGraph(AutoGraph[NodeSchema, EdgeSchema]):inputs = []for chunk, node_list in zip(chunks, node_lists):nodes = node_list.items if node_list else []- node_context = (- "Known entities: "- + "\n- ".join([self.node_key_extractor(n) for n in nodes])+ known_nodes = (+ "\n- ".join([self.node_key_extractor(n) for n in nodes])if nodeselse "No specific entities identified.")inputs.append({- "chunk_text": chunk,- "node_context": node_context,+ "source_text": chunk,+ "known_nodes": known_nodes,"observation_time": self.observation_time,"observation_location": self.observation_location,})- prompt_template = ChatPromptTemplate.from_template(- f"{self.edge_prompt}{{node_context}}\n\n### Source Text:\n{{chunk_text}}"- )- llm_chain = prompt_template | self.llm_client.with_structured_output(- self.edge_list_schema- )- return llm_chain.batch(inputs, config={"max_concurrency": self.max_workers})+ return self.edge_extractor.batch(inputs, config={"max_concurrency": self.max_workers})def _extract_data_by_one_stage(self, text: str) -> Any:"""Inject observation_time and observation_location into one-stage extraction."""- template_str = f"{self.prompt}{{chunk_text}}"- prompt_template = ChatPromptTemplate.from_template(template_str)- llm_chain = prompt_template | self.llm_client.with_structured_output(- self.graph_schema- )if len(text) <= self.chunk_size:inp = {- "chunk_text": text,+ "source_text": text,"observation_time": self.observation_time,"observation_location": self.observation_location,}- graph = llm_chain.invoke(inp)+ graph = self.data_extractor.invoke(inp)graph_list = [graph]else:chunks = self.text_splitter.split_text(text)inputs = [{- "chunk_text": chunk,+ "source_text": chunk,"observation_time": self.observation_time,"observation_location": self.observation_location,}for chunk in chunks]- graph_list = llm_chain.batch(+ graph_list = self.data_extractor.batch(inputs, config={"max_concurrency": self.max_workers})diff --git a/hyperextract/types/temporal_graph.py b/hyperextract/types/temporal_graph.pyindex 4a7162b..170dea7 100644--- a/hyperextract/types/temporal_graph.py+++ b/hyperextract/types/temporal_graph.py@@ -3,7 +3,6 @@from typing import Type, Callable, Tuple, Any, Listfrom datetime import datetimefrom langchain_core.language_models import BaseChatModel-from langchain_core.prompts import ChatPromptTemplatefrom langchain_core.embeddings import Embeddingsfrom ontomem.merger import MergeStrategy, BaseMerger@@ -34,6 +33,7 @@ DEFAULT_TEMPORAL_NODE_RULES_SUFFIX = """4. **Exclude Pure Numbers**: Do not extract standalone amounts or numeric values as independent nodes.### Source Text:+{source_text}"""# Edge Extraction Prompts@@ -62,6 +62,11 @@ Current Observation Date: {observation_time}2. DO NOT create edges involving entities that are not listed.3. Use the defined schema fields for time as specified in the output format.+# Provided Entities+{known_nodes}++# Source Text:+{source_text}"""# One-Stage Graph Extraction Prompts@@ -91,6 +96,7 @@ Current Observation Date: {observation_time}3. **Missing Time**: If no time information is present, leave time fields empty. DO NOT hallucinate dates.### Source Text:+{source_text}"""@@ -262,56 +268,41 @@ class AutoTemporalGraph(AutoGraph[NodeSchema, EdgeSchema]):def _extract_edges_batch(self, chunks: List[str], node_lists: List[NodeListSchema[NodeSchema]]) -> List[EdgeListSchema[EdgeSchema]]:- """- Override: Inject observation_time into edge extraction during two-stage extraction.+ """Override: Inject observation_time into edge extraction during two-stage extraction."""inputs = []for chunk, node_list in zip(chunks, node_lists):nodes = node_list.items if node_list else []if not nodes:- node_context = "No specific entities identified in this chunk."+ known_nodes = "No specific entities identified in this chunk."else:node_keys = [self.node_key_extractor(n) for n in nodes]- node_context = "Known entities: " + "\n- ".join(node_keys)+ known_nodes = "\n- ".join(node_keys)inputs.append({- "chunk_text": chunk,- "node_context": node_context,+ "source_text": chunk,+ "known_nodes": known_nodes,"observation_time": self.observation_time,})- prompt_template = ChatPromptTemplate.from_template(- f"{self.edge_prompt}{{node_context}}\n\n### Source Text:\n{{chunk_text}}"- )- llm_chain = prompt_template | self.llm_client.with_structured_output(- self.edge_list_schema- )-- return llm_chain.batch(inputs, config={"max_concurrency": self.max_workers})+ return self.edge_extractor.batch(inputs, config={"max_concurrency": self.max_workers})def _extract_data_by_one_stage(self, text: str) -> Any:- """- Override: Inject observation_time into one-stage extraction.- """- template_str = f"{self.prompt}{{chunk_text}}"- prompt_template = ChatPromptTemplate.from_template(template_str)- llm_chain = prompt_template | self.llm_client.with_structured_output(- self.graph_schema- )+ """Override: Inject observation_time into one-stage extraction."""if len(text) <= self.chunk_size:- inp = {"chunk_text": text, "observation_time": self.observation_time}- graph = llm_chain.invoke(inp)+ inp = {"source_text": text, "observation_time": self.observation_time}+ graph = self.data_extractor.invoke(inp)graph_list = [graph]else:chunks = self.text_splitter.split_text(text)inputs = [- {"chunk_text": chunk, "observation_time": self.observation_time}+ {"source_text": chunk, "observation_time": self.observation_time}for chunk in chunks]- graph_list = llm_chain.batch(+ graph_list = self.data_extractor.batch(inputs, config={"max_concurrency": self.max_workers})