Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.
refactor(templates): 移除核心概念定义并优化展示参数处理
yifanfeng972f6569ae3a65
diff --git a/examples/template_tcm_demo.py b/examples/template_tcm_demo.pyindex 4000672..e0338ba 100644--- a/examples/template_tcm_demo.py+++ b/examples/template_tcm_demo.py@@ -76,10 +76,10 @@ TEMPLATE_TO_INPUT = {# 方剂规范# TEMPLATE = FormulaComposition # 君臣佐使结构图-TEMPLATE = FunctionIndicationMap # 主治功效映射+# TEMPLATE = FunctionIndicationMap # 主治功效映射# 经络腧穴专著-# TEMPLATE = MeridianFlowGraph # 经络流注图+TEMPLATE = MeridianFlowGraph # 经络流注图# TEMPLATE = AcupointLocationMap # 腧穴空间定位# 名医医案diff --git a/hyperextract/templates/en/INSTRUCTION.md b/hyperextract/templates/en/INSTRUCTION.mdindex 7d76d1f..45cfd43 100644--- a/hyperextract/templates/en/INSTRUCTION.md+++ b/hyperextract/templates/en/INSTRUCTION.md@@ -179,9 +179,9 @@ Current Observation Location: {observation_location}| `_NODE_PROMPT` | two_stage step 1: extract nodes only || `_EDGE_PROMPT` | two_stage step 2: extract edges based on known nodes |-### 4.3 Prompt Pre-Structure Specifications (Mandatory)+### 4.3 Prompt Pre-Structure Specifications (Mandatory for Graph Types)-**All Prompts MUST follow the following pre-structure, no exceptions**:+**Graph types (AutoGraph/AutoHypergraph etc.) must follow the following pre-structure**:```## Role and Task@@ -200,6 +200,11 @@ You are a professional xxx expert, please extract xxx from the text...- Different AutoTypes have different core concepts that must be clearly defined- Concept definitions must be placed at the beginning of the Prompt+**Non-graph types do not require Core Concept Definitions**:+- **AutoModel**: Directly extract structured objects, object definitions are already clear in Pydantic Schema+- **AutoList**: Directly extract item lists, item definitions are already clear in Pydantic Schema+- **AutoSet**: Directly extract element collections, element definitions are already clear in Pydantic Schema+### 4.4 Core Concept Definition Templates for Each AutoType#### AutoModel@@ -276,15 +281,19 @@ In addition to node and edge definitions, time/location definitions must also bedef show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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_for_search: Number of nodes/edges returned for semantic search, default is 3- top_k_for_chat: Number of nodes/edges used for Q&A, default is 3+ top_k_nodes_for_search: Number of nodes returned for semantic search, default is 3+ top_k_edges_for_search: Number of edges returned for 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: MyNode) -> str:return node.name # Simple label, not unique identifier, friendly for display@@ -295,8 +304,10 @@ def show(super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,+ 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,)```@@ -477,15 +488,19 @@ class FinancialReportGraph(AutoTemporalGraph[FinancialEntity, FinancialRelation]def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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_for_search: Number of nodes/edges returned for semantic search, default is 3- top_k_for_chat: Number of nodes/edges used for Q&A, default is 3+ top_k_nodes_for_search: Number of nodes returned for semantic search, default is 3+ top_k_edges_for_search: Number of edges returned for 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: FinancialEntity) -> str:return node.name@@ -496,8 +511,10 @@ class FinancialReportGraph(AutoTemporalGraph[FinancialEntity, FinancialRelation]super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,+ 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/clause_list.py b/hyperextract/templates/en/general/clause_list.pyindex 832ea4a..d64796b 100644--- a/hyperextract/templates/en/general/clause_list.py+++ b/hyperextract/templates/en/general/clause_list.py@@ -21,9 +21,6 @@ class Clause(BaseModel):_PROMPT = """## Role and TaskYou are a professional regulation clause breakdown expert. Please break down the text into atomic clauses.-## Core Concept Definitions-- **Item**: In this template, "Item" refers to a single regulation clause, an atomic rule unit that includes fields such as clause ID, title, content, and category.-## Extraction Rules1. Break down the regulation into independent clauses according to its natural structure2. Assign an ID to each clause (e.g., Article 1, Section 2.1, etc.)diff --git a/hyperextract/templates/en/general/compliance_logic.py b/hyperextract/templates/en/general/compliance_logic.pyindex 4d034c0..af91965 100644--- a/hyperextract/templates/en/general/compliance_logic.py+++ b/hyperextract/templates/en/general/compliance_logic.py@@ -12,18 +12,28 @@ from hyperextract.types import AutoHypergraphclass 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")+ 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")+ 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="")+ 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="")@@ -119,7 +129,7 @@ class ComplianceLogic(AutoHypergraph[ComplianceElement, ComplianceRule]):):"""Initialize compliance logic hypergraph template.-+Args:llm_client: LLM client for knowledge extractionembedder: Embedding model for semantic search@@ -133,7 +143,9 @@ class ComplianceLogic(AutoHypergraph[ComplianceElement, ComplianceRule]):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}",+ 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,@@ -149,16 +161,21 @@ class ComplianceLogic(AutoHypergraph[ComplianceElement, ComplianceRule]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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_for_search: Number of nodes/edges to return for semantic search, default: 3- top_k_for_chat: Number of nodes/edges to use for chat, default: 3+ 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})"@@ -168,8 +185,8 @@ class ComplianceLogic(AutoHypergraph[ComplianceElement, ComplianceRule]):super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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.pyindex d020118..6d2d671 100644--- a/hyperextract/templates/en/general/concept_hierarchy.py+++ b/hyperextract/templates/en/general/concept_hierarchy.py@@ -12,16 +12,22 @@ from hyperextract.types import AutoGraphclass ConceptNode(BaseModel):"""Concept node"""+name: str = Field(description="Concept name")- category: str = Field(description="Concept type: CoreConcept, Subconcept, Attribute, Instance, Other")+ 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")+ relationType: str = Field(+ description="Relationship type: Subclass-Of (taxonomy), Part-Of (composition), Instance-Of (instance), Other"+ )details: str = Field(description="Detailed relationship explanation", default="")@@ -116,7 +122,7 @@ class ConceptHierarchy(AutoGraph[ConceptNode, HierarchyRelation]):):"""Initialize concept hierarchy graph template.-+Args:llm_client: LLM client for knowledge extractionembedder: Embedding model for semantic search@@ -146,27 +152,32 @@ class ConceptHierarchy(AutoGraph[ConceptNode, HierarchyRelation]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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 concept hierarchy graph.-+Args:- top_k_for_search: Number of nodes/edges to return for semantic search, default: 3- top_k_for_chat: Number of nodes/edges to use for chat, default: 3+ 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: 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_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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.pyindex c491781..8339784 100644--- a/hyperextract/templates/en/general/cross_reference_net.py+++ b/hyperextract/templates/en/general/cross_reference_net.py@@ -12,16 +12,22 @@ from hyperextract.types import AutoGraphclass ReferenceNode(BaseModel):"""Reference node"""+name: str = Field(description="Concept/entry name")- type: str = Field(description="Node type: Entry, Section, Concept, Person, Location, Other")+ 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")+ relationType: str = Field(+ description="Relationship type: Hyperlink, Reference, SeeAlso, Related, Other"+ )context: str = Field(description="Reference context description", default="")@@ -117,7 +123,7 @@ class CrossReferenceNet(AutoGraph[ReferenceNode, ReferenceRelation]):):"""Initialize cross-reference network template.-+Args:llm_client: LLM client for knowledge extractionembedder: Embedding model for semantic search@@ -147,27 +153,32 @@ class CrossReferenceNet(AutoGraph[ReferenceNode, ReferenceRelation]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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_for_search: Number of nodes/edges to return for semantic search, default: 3- top_k_for_chat: Number of nodes/edges to use for chat, default: 3+ 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_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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.pyindex 119cf6c..55ea48a 100644--- a/hyperextract/templates/en/general/encyclopedia_item.py+++ b/hyperextract/templates/en/general/encyclopedia_item.py@@ -25,9 +25,6 @@ class EncyclopediaInfo(BaseModel):_PROMPT = """## Role and TaskYou are a professional encyclopedia editor. Please extract structured attribute information for a single subject from the text to build an encyclopedia item infobox.-## Core Concept Definitions-- **Object**: In this template, "Object" refers to a single encyclopedia entry subject, which is a structured information unit containing multiple fields such as title, entity type, aliases, categories, summary, attributes, important events, related concepts, etc.-## Extraction Rules1. 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, Otherdiff --git a/hyperextract/templates/en/general/entity_registry.py b/hyperextract/templates/en/general/entity_registry.pyindex 581b83d..446217b 100644--- a/hyperextract/templates/en/general/entity_registry.py+++ b/hyperextract/templates/en/general/entity_registry.py@@ -20,9 +20,6 @@ class RegistryEntry(BaseModel):_PROMPT = """## Role and TaskYou are a professional entity recognition expert. Please extract all unique entities from the text to form an entity registry.-## Core Concept Definitions-- **Element**: In this template, "Element" refers to a single entity registry entry, a unique knowledge unit that includes fields such as entity name, type, and description, and is deduplicated by name.-## Extraction Rules1. Extract all entities: Person, Organization, Location, Product, Concept, etc.2. Assign a type to each entity: Person, Organization, Location, Product, Concept, Otherdiff --git a/hyperextract/templates/en/general/keyword_list.py b/hyperextract/templates/en/general/keyword_list.pyindex 182e39b..2ebc59a 100644--- a/hyperextract/templates/en/general/keyword_list.py+++ b/hyperextract/templates/en/general/keyword_list.py@@ -20,9 +20,6 @@ class Keyword(BaseModel):_PROMPT = """## Role and TaskYou are a professional keyword extraction expert. Please extract all keywords from the text with category and description information.-## Core Concept Definitions-- **Item**: In this template, "Item" refers to a single keyword entry, a semantic tag unit that includes fields such as keyword term, category, and description.-## Extraction Rules1. Extract all keywords and core phrases from the text2. Assign a category to each keyword: CoreConcept, Term, PersonName, OrganizationName, Otherdiff --git a/hyperextract/templates/en/general/knowledge_graph.py b/hyperextract/templates/en/general/knowledge_graph.pyindex 8548058..65553fc 100644--- a/hyperextract/templates/en/general/knowledge_graph.py+++ b/hyperextract/templates/en/general/knowledge_graph.py@@ -12,16 +12,24 @@ from hyperextract.types import AutoGraphclass 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")++ 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.")+ relationType: str = Field(+ description="Relationship type: BelongsTo, LocatedIn, CollaboratesWith, CompetesWith, InventedBy, CreatedBy, RelatedTo, etc."+ )details: str = Field(description="Detailed description", default="")@@ -107,7 +115,7 @@ class KnowledgeGraph(AutoGraph[GeneralEntity, GeneralRelation]):):"""Initialize general knowledge graph template.-+Args:llm_client: LLM client for knowledge extractionembedder: Embedding model for semantic search@@ -137,27 +145,32 @@ class KnowledgeGraph(AutoGraph[GeneralEntity, GeneralRelation]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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 knowledge graph.-+Args:- top_k_for_search: Number of nodes/edges to return for semantic search, default: 3- top_k_for_chat: Number of nodes/edges to use for chat, default: 3+ 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: 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_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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.pyindex f6b06e7..b30eabc 100644--- a/hyperextract/templates/en/general/life_event_timeline.py+++ b/hyperextract/templates/en/general/life_event_timeline.py@@ -12,17 +12,25 @@ from hyperextract.types import AutoTemporalGraphclass LifeEntity(BaseModel):"""Life entity node"""+name: str = Field(description="Entity name")- type: str = Field(description="Entity type: Person, Location, Organization, Item, Concept, Other")+ 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)+ 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="")@@ -187,7 +195,7 @@ class LifeEventTimeline(AutoTemporalGraph[LifeEntity, LifeEvent]):):"""Initialize life event timeline template.-+Args:llm_client: LLM client for knowledge extractionembedder: Embedding model for semantic search@@ -220,29 +228,34 @@ class LifeEventTimeline(AutoTemporalGraph[LifeEntity, LifeEvent]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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_for_search: Number of nodes/edges to return for semantic search, default: 3- top_k_for_chat: Number of nodes/edges to use for chat, default: 3+ 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_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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.pyindex a6082a8..4dfca72 100644--- a/hyperextract/templates/en/general/operational_procedure.py+++ b/hyperextract/templates/en/general/operational_procedure.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoGraphclass 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")@@ -22,6 +23,7 @@ class ProcedureStep(BaseModel):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="")@@ -114,7 +116,7 @@ class OperationalProcedure(AutoGraph[ProcedureStep, ProcedureTransition]):):"""Initialize operational procedure template.-+Args:llm_client: LLM client for knowledge extractionembedder: Embedding model for semantic search@@ -144,29 +146,34 @@ class OperationalProcedure(AutoGraph[ProcedureStep, ProcedureTransition]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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_for_search: Number of nodes/edges to return for semantic search, default: 3- top_k_for_chat: Number of nodes/edges to use for chat, default: 3+ 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.conditionreturn "→"-+super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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.pyindex 4f15194..48afe95 100644--- a/hyperextract/templates/en/general/penalty_mapping.py+++ b/hyperextract/templates/en/general/penalty_mapping.py@@ -12,16 +12,22 @@ from hyperextract.types import AutoGraphclass PenaltyNode(BaseModel):"""Penalty causal node"""+name: str = Field(description="Node name")- type: str = Field(description="Node type: Violation, HandlingProcedure, PenaltyResult, Other")+ 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")+ relation: str = Field(+ description="Relationship type: Causes, Triggers, Executes, Produces, Other"+ )details: str = Field(description="Detailed explanation", default="")@@ -105,7 +111,7 @@ class PenaltyMapping(AutoGraph[PenaltyNode, PenaltyPath]):):"""Initialize penalty mapping template.-+Args:llm_client: LLM client for knowledge extractionembedder: Embedding model for semantic search@@ -135,27 +141,32 @@ class PenaltyMapping(AutoGraph[PenaltyNode, PenaltyPath]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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_for_search: Number of nodes/edges to return for semantic search, default: 3- top_k_for_chat: Number of nodes/edges to use for chat, default: 3+ 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_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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.pyindex f0771a7..60532cc 100644--- a/hyperextract/templates/en/general/penalty_registry.py+++ b/hyperextract/templates/en/general/penalty_registry.py@@ -22,9 +22,6 @@ class PenaltyEntry(BaseModel):_PROMPT = """## Role and TaskYou are a professional compliance analysis expert. Please extract all violations and their corresponding penalty measures from the text to form a violation penalty registry.-## Core Concept Definitions-- **Element**: In this template, "Element" refers to a single violation penalty entry, a unique knowledge unit that includes fields such as violation description, severity, penalty measure, applicable clause, and notes, and is deduplicated by the combination of violation and penalty measure.-## Extraction Rules1. Extract all violations and their corresponding penalty measures2. Assign a severity level to each violation: Minor, Moderate, Serious, VerySeriousdiff --git a/hyperextract/templates/en/general/personal_profile.py b/hyperextract/templates/en/general/personal_profile.pyindex 4f66765..555053a 100644--- a/hyperextract/templates/en/general/personal_profile.py+++ b/hyperextract/templates/en/general/personal_profile.py@@ -29,9 +29,6 @@ class PersonalInfo(BaseModel):_PROMPT = """## Role and TaskYou are a professional personal profile editor. Please extract static attribute information of this person from the text to build a personal profile.-## Core Concept Definitions-- **Object**: In this template, "Object" refers to personal profile information, which is a structured person information unit containing multiple fields such as name, gender, birth/death dates, nationality, education background, occupations, core identity, major achievements, affiliations, summary, etc.-## Extraction Rules1. Extract basic information: name, gender, date of birth, date of death, nationality, place of birth, etc.2. Extract education backgrounddiff --git a/hyperextract/templates/en/general/regulation_profile.py b/hyperextract/templates/en/general/regulation_profile.pyindex 978b4ff..abbb922 100644--- a/hyperextract/templates/en/general/regulation_profile.py+++ b/hyperextract/templates/en/general/regulation_profile.py@@ -28,9 +28,6 @@ class RegulationInfo(BaseModel):_PROMPT = """## Role and TaskYou are a professional regulation analysis expert. Please extract metadata information of this regulation from the text to build a regulation profile.-## Core Concept Definitions-- **Object**: In this template, "Object" refers to regulation metadata information, structured institutional information that includes multiple fields: title, version, issuing authority, issue/effective/expiry dates, applicable scope, target audience, core purpose, keywords, and related regulations.-## Extraction Rules1. Extract the full name of the regulation2. Extract version number (if available)diff --git a/hyperextract/templates/en/general/social_network.py b/hyperextract/templates/en/general/social_network.pyindex 8a1e308..a6d5ec3 100644--- a/hyperextract/templates/en/general/social_network.py+++ b/hyperextract/templates/en/general/social_network.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoGraphclass 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="")@@ -20,9 +21,12 @@ class PersonNode(BaseModel):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")+ relationType: str = Field(+ description="Relationship type: Family, Friend, Colleague, TeacherStudent, SupervisorSubordinate, Collaboration, Competition, Affiliation, Other"+ )details: str = Field(description="Detailed relationship explanation", default="")@@ -127,7 +131,7 @@ class SocialNetwork(AutoGraph[PersonNode, SocialRelation]):):"""Initialize social network graph template.-+Args:llm_client: LLM client for knowledge extractionembedder: Embedding model for semantic search@@ -157,29 +161,34 @@ class SocialNetwork(AutoGraph[PersonNode, SocialRelation]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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 social network graph.-+Args:- top_k_for_search: Number of nodes/edges to return for semantic search, default: 3- top_k_for_chat: Number of nodes/edges to use for chat, default: 3+ 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: PersonNode) -> str:if node.role:return f"{node.name} ({node.role})"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_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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/history/diplomatic_event_hypergraph.py b/hyperextract/templates/en/history/diplomatic_event_hypergraph.pyindex e6dbb77..7fc52ce 100644--- a/hyperextract/templates/en/history/diplomatic_event_hypergraph.py+++ b/hyperextract/templates/en/history/diplomatic_event_hypergraph.py@@ -78,7 +78,7 @@ class DiplomaticEventHypergraph(AutoHypergraph[CountrySchema, DiplomaticEventSch**kwargs,)- def show(self, *, top_k_for_search: int = 5, top_k_for_chat: int = 5) -> None:+ 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) -> None:def node_label(node: CountrySchema) -> str:return f"🏛️ {node.country_name}"@@ -88,6 +88,5 @@ class DiplomaticEventHypergraph(AutoHypergraph[CountrySchema, DiplomaticEventSchsuper().show(node_label_extractor=node_label,edge_label_extractor=edge_label,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,+ 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/history/war_timeline_graph.py b/hyperextract/templates/en/history/war_timeline_graph.pyindex 8687259..8c54522 100644--- a/hyperextract/templates/en/history/war_timeline_graph.py+++ b/hyperextract/templates/en/history/war_timeline_graph.py@@ -80,7 +80,7 @@ class WarTimelineGraph(AutoTemporalGraph[HistoricalEntitySchema, TemporalEventSc**kwargs,)- def show(self, *, top_k_for_search: int = 5, top_k_for_chat: int = 5) -> None:+ 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) -> None:def node_label(node: HistoricalEntitySchema) -> str:return f"{node.entity_name} ({node.entity_type})"def edge_label(edge: TemporalEventSchema) -> str:@@ -88,6 +88,5 @@ class WarTimelineGraph(AutoTemporalGraph[HistoricalEntitySchema, TemporalEventScsuper().show(node_label_extractor=node_label,edge_label_extractor=edge_label,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,+ 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/legal/corporate_equity_graph.py b/hyperextract/templates/en/legal/corporate_equity_graph.pyindex f879193..38eb29d 100644--- a/hyperextract/templates/en/legal/corporate_equity_graph.py+++ b/hyperextract/templates/en/legal/corporate_equity_graph.py@@ -65,7 +65,7 @@ class CorporateEquityGraph(AutoGraph[EntitySchema, EquityRelationshipSchema]):**kwargs,)- def show(self, *, top_k_for_search: int = 5, top_k_for_chat: int = 5) -> None:+ 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) -> None:def node_label(node: EntitySchema) -> str:type_icon = {"Company": "🏢", "Individual": "👤", "Fund": "💼"}icon = type_icon.get(node.entity_type, "●")@@ -76,6 +76,5 @@ class CorporateEquityGraph(AutoGraph[EntitySchema, EquityRelationshipSchema]):super().show(node_label_extractor=node_label,edge_label_extractor=edge_label,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,+ 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/literature/character_relationship_graph.py b/hyperextract/templates/en/literature/character_relationship_graph.pyindex 90c92f7..76beb4c 100644--- a/hyperextract/templates/en/literature/character_relationship_graph.py+++ b/hyperextract/templates/en/literature/character_relationship_graph.py@@ -8,20 +8,43 @@ from hyperextract.types import AutoGraph# 1. Schema Definitions# ==============================================================================+class Character(BaseModel):"""A character entity in a literary work."""+name: str = Field(description="The full or most common name of the character.")- aliases: List[str] = Field(default_factory=list, description="Other names, titles, or nicknames used for the character.")- traits: List[str] = Field(default_factory=list, description="Core personality traits, skills, or physical attributes.")- description: Optional[str] = Field(description="A brief description of the character's role and significance in the story.")+ aliases: List[str] = Field(+ default_factory=list,+ description="Other names, titles, or nicknames used for the character.",+ )+ traits: List[str] = Field(+ default_factory=list,+ description="Core personality traits, skills, or physical attributes.",+ )+ description: Optional[str] = Field(+ description="A brief description of the character's role and significance in the story."+ )+class Relationship(BaseModel):"""Social or emotional interaction between characters."""- source: str = Field(description="The name of the character initiating or participating in the relationship.")- target: str = Field(description="The name of the second character in the relationship.")- relation_type: str = Field(description="The nature of the relationship (e.g., Kinship, Romance, Rivalry, Mentorship).")- sentiment: str = Field(description="The emotional tone (e.g., Positive, Negative, Ambivalent, Intense).")- evidence: str = Field(description="Brief textual evidence or plot point supporting this relationship.")++ source: str = Field(+ description="The name of the character initiating or participating in the relationship."+ )+ target: str = Field(+ description="The name of the second character in the relationship."+ )+ relation_type: str = Field(+ description="The nature of the relationship (e.g., Kinship, Romance, Rivalry, Mentorship)."+ )+ sentiment: str = Field(+ description="The emotional tone (e.g., Positive, Negative, Ambivalent, Intense)."+ )+ evidence: str = Field(+ description="Brief textual evidence or plot point supporting this relationship."+ )+# ==============================================================================# 2. Prompts@@ -38,9 +61,7 @@ _PROMPT = ("- Ensure every edge connects two nodes that are explicitly listed in the character nodes.")-_NODE_PROMPT = (- "As a literary expert, extract all key characters. For each character, provide their name, any known aliases, core personality tags, and a brief description of their role/status."-)+_NODE_PROMPT = "As a literary expert, extract all key characters. For each character, provide their name, any known aliases, core personality tags, and a brief description of their role/status."_EDGE_PROMPT = ("Based on the extracted characters, identify the social and emotional relationships between them. "@@ -51,13 +72,14 @@ _EDGE_PROMPT = (# 3. Template Class# ==============================================================================+class CharacterRelationshipGraph(AutoGraph[Character, Relationship]):"""Applicable to: [Novels, Screenplays, Biographies, Dramas]Knowledge pattern for extracting character networks and social structures in literature.- This template captures dynamic interactions, emotional tones, and structured connections,+ This template captures dynamic interactions, emotional tones, and structured connections,supporting two-stage extraction for higher precision in complex narrative webs.Example:@@ -82,7 +104,7 @@ class CharacterRelationshipGraph(AutoGraph[Character, Relationship]):chunk_overlap: int = 256,max_workers: int = 10,verbose: bool = False,- **kwargs: Any+ **kwargs: Any,):"""Initialize CharacterRelationshipGraph template.@@ -113,22 +135,27 @@ class CharacterRelationshipGraph(AutoGraph[Character, Relationship]):chunk_overlap=chunk_overlap,max_workers=max_workers,verbose=verbose,- **kwargs+ **kwargs,)def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,) -> None:"""Visualize the character relationship graph.Args:- top_k_for_search: Number of nodes/edges to retrieve for search context.- top_k_for_chat: Number of nodes/edges to retrieve for chat context.+ top_k_nodes_for_search: Number of nodes to retrieve for search context.+ top_k_edges_for_search: Number of edges to retrieve for search context.+ top_k_nodes_for_chat: Number of nodes to retrieve for chat context.+ top_k_edges_for_chat: Number of edges to retrieve for chat context."""+def node_label_extractor(node: Character) -> str:return node.name@@ -138,8 +165,8 @@ class CharacterRelationshipGraph(AutoGraph[Character, Relationship]):super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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/literature/narrative_timeline.py b/hyperextract/templates/en/literature/narrative_timeline.pyindex ed6470f..56e726f 100644--- a/hyperextract/templates/en/literature/narrative_timeline.py+++ b/hyperextract/templates/en/literature/narrative_timeline.py@@ -8,19 +8,35 @@ from hyperextract.types import AutoTemporalGraph# 1. Schema Definitions# ==============================================================================+class PlotPoint(BaseModel):"""A significant event or moment in the narrative flow."""- name: str = Field(description="A short title for the plot point or event (e.g., 'The Departure', 'Unexpected Reunion').")++ name: str = Field(+ description="A short title for the plot point or event (e.g., 'The Departure', 'Unexpected Reunion')."+ )location: Optional[str] = Field(description="Where the event takes place.")- characters_involved: List[str] = Field(default_factory=list, description="List of characters participating in this event.")- description: str = Field(description="Detailed description of the plot content, including key actions and shifts.")+ characters_involved: List[str] = Field(+ default_factory=list,+ description="List of characters participating in this event.",+ )+ description: str = Field(+ description="Detailed description of the plot content, including key actions and shifts."+ )+class TimeProgression(BaseModel):"""The temporal and logical connection between plot points."""+source: str = Field(description="The name of the preceding plot point.")target: str = Field(description="The name of the subsequent plot point.")- time: str = Field(description="The resolved timestamp or absolute date of the event. You MUST resolve relative time expressions (e.g., 'three days later', 'next morning') into absolute dates (e.g., '2024-05-12') or specific years based on context and observation time.")- logic: str = Field(description="The logical relationship between events (e.g., Causality, Escalation, Sudden Twist).")+ time: str = Field(+ description="The resolved timestamp or absolute date of the event. You MUST resolve relative time expressions (e.g., 'three days later', 'next morning') into absolute dates (e.g., '2024-05-12') or specific years based on context and observation time."+ )+ logic: str = Field(+ description="The logical relationship between events (e.g., Causality, Escalation, Sudden Twist)."+ )+# ==============================================================================# 2. Prompts@@ -35,25 +51,22 @@ _PROMPT = ("Note: Time must be extracted on the edge (Progression), not as a standalone node.")-_NODE_PROMPT = (- "Identify and extract all key plot points. Name each point and provide its location and the characters involved."-)+_NODE_PROMPT = "Identify and extract all key plot points. Name each point and provide its location and the characters involved."-_EDGE_PROMPT = (- "Establish connections between the plot points. Accurately resolve temporal cues mentioned in the text into absolute dates or years, and describe how these events are linked in narrative logic."-)+_EDGE_PROMPT = "Establish connections between the plot points. Accurately resolve temporal cues mentioned in the text into absolute dates or years, and describe how these events are linked in narrative logic."# ==============================================================================# 3. Template Class# ==============================================================================+class NarrativeTimeline(AutoTemporalGraph[PlotPoint, TimeProgression]):"""Applicable to: [Chronicles, Epic Literature, Detective Novels, History Books]Knowledge pattern for reconstructing narrative timelines and plot progressions.- Leveraging AutoTemporalGraph, this template embeds temporal information within relationships+ Leveraging AutoTemporalGraph, this template embeds temporal information within relationshipsto visualize the 'Cause-Process-Effect' dynamic of a story.Example:@@ -79,7 +92,7 @@ class NarrativeTimeline(AutoTemporalGraph[PlotPoint, TimeProgression]):chunk_overlap: int = 256,max_workers: int = 10,verbose: bool = False,- **kwargs: Any+ **kwargs: Any,):"""Initialize NarrativeTimeline template.@@ -113,22 +126,27 @@ class NarrativeTimeline(AutoTemporalGraph[PlotPoint, TimeProgression]):chunk_overlap=chunk_overlap,max_workers=max_workers,verbose=verbose,- **kwargs+ **kwargs,)def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,) -> None:"""Visualize the narrative timeline.Args:- top_k_for_search: Number of nodes/edges to retrieve for search context.- top_k_for_chat: Number of nodes/edges to retrieve for chat context.+ top_k_nodes_for_search: Number of nodes to retrieve for search context.+ top_k_edges_for_search: Number of edges to retrieve for search context.+ top_k_nodes_for_chat: Number of nodes to retrieve for chat context.+ top_k_edges_for_chat: Number of edges to retrieve for chat context."""+def node_label_extractor(node: PlotPoint) -> str:return node.name@@ -138,8 +156,8 @@ class NarrativeTimeline(AutoTemporalGraph[PlotPoint, TimeProgression]):super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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 da802e5..ac58388 100644--- a/hyperextract/templates/zh/INSTRUCTION.md+++ b/hyperextract/templates/zh/INSTRUCTION.md@@ -1,4 +1,4 @@-# Hyper-Extract 知识模板定义手册+# Hyper-Extract 知识模板定义手册本文档定义了在 `Hyper-Extract` 框架中实现特定领域知识抽取模板的标准工作流。@@ -177,9 +177,9 @@ class FinancialRelation(BaseModel):| `_NODE_PROMPT` | two_stage 第一步:仅提取节点 || `_EDGE_PROMPT` | two_stage 第二步:基于已知节点提取边 |-### 4.3 Prompt 前置结构规范(强制要求)+### 4.3 Prompt 前置结构规范(图类型强制要求)-**所有 Prompt 必须遵循以下前置结构,缺一不可**:+**图类型(AutoGraph/AutoHypergraph 等)必须遵循以下前置结构**:```## 角色与任务@@ -198,6 +198,11 @@ class FinancialRelation(BaseModel):- 不同的 AutoType 有不同的核心概念,必须明确定义- 概念定义必须放在 Prompt 的开头部分+**非图类型不需要核心概念定义**:+- **AutoModel**:直接提取结构化对象,对象定义已在 Pydantic Schema 中明确+- **AutoList**:直接提取条目列表,条目定义已在 Pydantic Schema 中明确+- **AutoSet**:直接提取元素集合,元素定义已在 Pydantic Schema 中明确+### 4.4 各 AutoType 的核心概念定义模板#### AutoModel@@ -274,15 +279,19 @@ class FinancialRelation(BaseModel):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示知识图谱。Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""def node_label_extractor(node: MyNode) -> str:return node.name # 简明 label,非唯一标识,展示友好@@ -293,8 +302,10 @@ def show(super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,+ 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,)```@@ -475,15 +486,19 @@ class FinancialReportGraph(AutoTemporalGraph[FinancialEntity, FinancialRelation]def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示知识图谱。Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""def node_label_extractor(node: FinancialEntity) -> str:return node.name@@ -494,8 +509,10 @@ class FinancialReportGraph(AutoTemporalGraph[FinancialEntity, FinancialRelation]super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,+ 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/general/clause_list.py b/hyperextract/templates/zh/general/clause_list.pyindex 2ec8590..4cf585e 100644--- a/hyperextract/templates/zh/general/clause_list.py+++ b/hyperextract/templates/zh/general/clause_list.py@@ -21,9 +21,6 @@ class Clause(BaseModel):_PROMPT = """## 角色与任务你是一位专业的规章制度条文拆解专家,请将文本拆解为逐条的原子化条文。-## 核心概念定义-- **条目 (Item)**:本模板中的"条目"指单条规章制度条文,包含条文编号、标题、内容、分类等字段的原子化规则单元。-## 提取规则1. 将规章制度按其自然结构拆解为独立的条文2. 为每条条文分配编号(如第1条、第2.1款等)diff --git a/hyperextract/templates/zh/general/compliance_logic.py b/hyperextract/templates/zh/general/compliance_logic.pyindex 3349218..dd3e650 100644--- a/hyperextract/templates/zh/general/compliance_logic.py+++ b/hyperextract/templates/zh/general/compliance_logic.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoHypergraphclass ComplianceElement(BaseModel):"""合规要素 - 节点"""+name: str = Field(description="要素名称,文本中出现的精确名称")category: str = Field(description="要素类型:主体、操作、条件、其他")description: str = Field(description="简要描述", default="")@@ -19,8 +20,11 @@ class ComplianceElement(BaseModel):class ComplianceRule(BaseModel):"""合规规则 - 超边"""+ruleType: str = Field(description="规则类型:必须、禁止、允许、其他")- participants: List[str] = Field(description="参与要素名称列表,必须使用已提取节点的 name")+ participants: List[str] = Field(+ description="参与要素名称列表,必须使用已提取节点的 name"+ )action: str = Field(description="要求执行或禁止的操作内容")condition: str = Field(description="适用条件/前置要求", default="")consequence: str = Field(description="违规后果/奖励措施", default="")@@ -143,7 +147,9 @@ class ComplianceLogic(AutoHypergraph[ComplianceElement, ComplianceRule]):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}",+ 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,@@ -159,16 +165,21 @@ class ComplianceLogic(AutoHypergraph[ComplianceElement, ComplianceRule]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示合规行为超图。Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""+def node_label_extractor(node: ComplianceElement) -> str:return f"{node.name} ({node.category})"@@ -178,8 +189,8 @@ class ComplianceLogic(AutoHypergraph[ComplianceElement, ComplianceRule]):super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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/general/concept_hierarchy.py b/hyperextract/templates/zh/general/concept_hierarchy.pyindex fc50605..deda89a 100644--- a/hyperextract/templates/zh/general/concept_hierarchy.py+++ b/hyperextract/templates/zh/general/concept_hierarchy.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoGraphclass ConceptNode(BaseModel):"""概念节点"""+name: str = Field(description="概念名称")category: str = Field(description="概念类型:核心概念、子概念、属性、实例、其他")description: str = Field(description="概念简要描述", default="")@@ -19,9 +20,12 @@ class ConceptNode(BaseModel):class HierarchyRelation(BaseModel):"""层级关系边"""+source: str = Field(description="父概念/整体概念")target: str = Field(description="子概念/部分概念")- relationType: str = Field(description="关系类型:Subclass-Of(上下位)、Part-Of(组成)、Instance-Of(实例)、Other(其他)")+ relationType: str = Field(+ description="关系类型:Subclass-Of(上下位)、Part-Of(组成)、Instance-Of(实例)、Other(其他)"+ )details: str = Field(description="关系详细说明", default="")@@ -116,7 +120,7 @@ class ConceptHierarchy(AutoGraph[ConceptNode, HierarchyRelation]):):"""初始化概念层级图模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -146,27 +150,32 @@ class ConceptHierarchy(AutoGraph[ConceptNode, HierarchyRelation]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示概念层级图。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 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_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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/general/cross_reference_net.py b/hyperextract/templates/zh/general/cross_reference_net.pyindex 960e0aa..1c0a5e5 100644--- a/hyperextract/templates/zh/general/cross_reference_net.py+++ b/hyperextract/templates/zh/general/cross_reference_net.py@@ -3,7 +3,7 @@适用于百科内链、跨词条关联图等。"""-from typing import Any, Optional+from typing import Anyfrom pydantic import BaseModel, Fieldfrom langchain_core.language_models import BaseChatModelfrom langchain_core.embeddings import Embeddings@@ -12,6 +12,7 @@ from hyperextract.types import AutoGraphclass ReferenceNode(BaseModel):"""引用节点"""+name: str = Field(description="概念/条目名称")type: str = Field(description="节点类型:条目、章节、概念、人物、地点、其他")description: str = Field(description="简要描述", default="")@@ -19,9 +20,12 @@ class ReferenceNode(BaseModel):class ReferenceRelation(BaseModel):"""引用关系边"""+source: str = Field(description="源条目/概念")target: str = Field(description="被引用条目/概念")- relationType: str = Field(description="关系类型:Hyperlink(超链接)、Reference(引用)、SeeAlso(参见)、Related(相关)、Other(其他)")+ relationType: str = Field(+ description="关系类型:Hyperlink(超链接)、Reference(引用)、SeeAlso(参见)、Related(相关)、Other(其他)"+ )context: str = Field(description="引用上下文描述", default="")@@ -117,7 +121,7 @@ class CrossReferenceNet(AutoGraph[ReferenceNode, ReferenceRelation]):):"""初始化交叉引用网络模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -147,27 +151,32 @@ class CrossReferenceNet(AutoGraph[ReferenceNode, ReferenceRelation]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示交叉引用网络。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 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_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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/general/encyclopedia_item.py b/hyperextract/templates/zh/general/encyclopedia_item.pyindex 195e39f..32d980b 100644--- a/hyperextract/templates/zh/general/encyclopedia_item.py+++ b/hyperextract/templates/zh/general/encyclopedia_item.py@@ -3,7 +3,7 @@适用于维基百科、专业词典词条等。"""-from typing import Any, Optional, List+from typing import Any, Listfrom pydantic import BaseModel, Fieldfrom langchain_core.language_models import BaseChatModelfrom langchain_core.embeddings import Embeddings@@ -25,9 +25,6 @@ class EncyclopediaInfo(BaseModel):_PROMPT = """## 角色与任务你是一位专业的百科全书编辑,请从文本中提取单一主体的结构化属性信息,构建百科条目信息框。-## 核心概念定义-- **对象 (Object)**:本模板中的"对象"指单一百科条目主体,包含标题、实体类型、别名、分类、摘要、属性、重要事件等多个字段的结构化信息。-## 提取规则1. 识别文本的核心主体(人物、地点、组织、事件、概念等)2. 为主体指定类型:人物、地点、组织、事件、概念、物品、其他diff --git a/hyperextract/templates/zh/general/entity_registry.py b/hyperextract/templates/zh/general/entity_registry.pyindex 6cb013a..362b708 100644--- a/hyperextract/templates/zh/general/entity_registry.py+++ b/hyperextract/templates/zh/general/entity_registry.py@@ -20,9 +20,6 @@ class RegistryEntry(BaseModel):_PROMPT = """## 角色与任务你是一位专业的实体识别专家,请从文本中提取所有唯一实体,形成实体注册表。-## 核心概念定义-- **元素 (Element)**:本模板中的"元素"指单个实体注册表条目,包含实体名称、类型、描述等字段,通过名称进行去重的唯一知识单元。-## 提取规则1. 提取所有实体:人物、机构、地点、产品、概念等2. 为每个实体指定类型:人物、机构、地点、产品、概念、其他diff --git a/hyperextract/templates/zh/general/keyword_list.py b/hyperextract/templates/zh/general/keyword_list.pyindex fe48333..8eac339 100644--- a/hyperextract/templates/zh/general/keyword_list.py+++ b/hyperextract/templates/zh/general/keyword_list.py@@ -20,9 +20,6 @@ class Keyword(BaseModel):_PROMPT = """## 角色与任务你是一位专业的关键词提取专家,请从文本中提取所有关键词并附带分类和描述信息。-## 核心概念定义-- **条目 (Item)**:本模板中的"条目"指单个关键词项,包含关键词、分类、描述等字段的语义标签单元。-## 提取规则1. 提取文本中的所有关键词和核心短语2. 为每个关键词指定分类:核心概念、术语、人名、机构名、其他diff --git a/hyperextract/templates/zh/general/knowledge_graph.py b/hyperextract/templates/zh/general/knowledge_graph.pyindex cc37be9..af7bdd1 100644--- a/hyperextract/templates/zh/general/knowledge_graph.py+++ b/hyperextract/templates/zh/general/knowledge_graph.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoGraphclass GeneralEntity(BaseModel):"""通用实体节点"""+name: str = Field(description="实体名称,如人名、机构名、产品名")category: str = Field(description="实体类型:人物、机构、地点、产品、概念、其他")description: str = Field(description="简要描述", default="")@@ -19,9 +20,12 @@ class GeneralEntity(BaseModel):class GeneralRelation(BaseModel):"""通用关系边"""+source: str = Field(description="源实体")target: str = Field(description="目标实体")- relationType: str = Field(description="关系类型:属于、位于、合作、竞争、发明、创建、相关等")+ relationType: str = Field(+ description="关系类型:属于、位于、合作、竞争、发明、创建、相关等"+ )details: str = Field(description="详细描述", default="")@@ -107,7 +111,7 @@ class KnowledgeGraph(AutoGraph[GeneralEntity, GeneralRelation]):):"""初始化通用知识图谱模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -137,27 +141,32 @@ class KnowledgeGraph(AutoGraph[GeneralEntity, GeneralRelation]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示知识图谱。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 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_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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/general/life_event_timeline.py b/hyperextract/templates/zh/general/life_event_timeline.pyindex 383ac88..78bba00 100644--- a/hyperextract/templates/zh/general/life_event_timeline.py+++ b/hyperextract/templates/zh/general/life_event_timeline.py@@ -1,4 +1,4 @@-from typing import Any+from typing import Any, Optionalfrom datetime import datetimefrom langchain_core.language_models import BaseChatModelfrom langchain_core.embeddings import Embeddings@@ -6,94 +6,159 @@ from pydantic import BaseModel, Fieldfrom hyperextract.types import AutoTemporalGraph-class PersonEntity(BaseModel):- """人物实体"""- name: str = Field(description="人物姓名")+class LifeEntity(BaseModel):+ """生活实体节点"""++ name: str = Field(description="实体名称")+ type: str = Field(description="实体类型:人物、地点、组织、物品、概念、其他")description: str = Field(description="简要描述", default="")class LifeEvent(BaseModel):- """生活事件"""- source: str = Field(description="相关人物")- eventType: str = Field(description="事件类型:出生、教育、工作、婚姻、死亡等")- eventName: str = Field(description="事件名称")- timeInfo: str = Field(description="时间信息,统一格式为年-月-日(如 2023-06-15)")- location: str = Field(description="事件地点", default="")- description: str = Field(description="事件描述", default="")+ """生活事件边(带可选时间戳)"""+ source: str = Field(description="事件主体/相关实体")+ target: str = Field(description="事件对象/相关实体")+ eventType: str = Field(+ description="事件类型:出生、逝世、教育、工作、成就、交往、旅行、其他"+ )+ eventDate: Optional[str] = Field(+ description="事件日期,格式为年-月-日或年份,可选", default=None+ )+ details: str = Field(description="事件详细描述", default="")-_PROMPT = """## 角色与任务-你是一位专业的生活事件提取专家,请从文本中提取人物及其生活事件。-## 核心概念定义-- **节点 (Node)**:本模板中的"节点"指人物,包括人物姓名和简要描述。-- **边 (Edge)**:本模板中的"边"指生活事件,包括事件类型、名称、时间、地点和描述。+_PROMPT = """你是一位专业的传记年表专家。请从文本中提取人物、地点、组织等实体以及生活事件,构建生平时序图。-## 提取规则### 节点提取规则-1. 提取所有人物,包括其姓名和简要描述-2. 保持人物姓名与原文一致+1. 提取所有相关实体:人物、地点、组织、物品、概念等+2. 为每个实体指定类型:人物、地点、组织、物品、概念、其他+3. 为每个实体添加简要描述### 事件提取规则-1. 提取所有生活事件,包括事件类型、名称、时间、地点和描述-2. 每条事件必须连接相关的人物-3. 时间信息必须统一转换为「年-月-日」格式(如 2023-06-15)--### 时间解析规则-当前观察日期: {observation_time}--1. 相对时间解析(基于观察日期):- - "去年" → {observation_time} 的前一年,格式化为 YYYY-01-01- - "上月" → {observation_time} 的前一个月,格式化为 YYYY-MM-01+1. 仅从提取的实体中创建事件边+2. 事件类型包括:+ - 出生:出生事件+ - 逝世:逝世事件+ - 教育:学习、受教育事件+ - 工作:工作、职业事件+ - 成就:取得成就、获得荣誉事件+ - 交往:人际交往、社会活动事件+ - 旅行:旅行、迁居事件+ - 其他:其他事件+3. 事件日期为可选提取项,仅在文本中明确提及时才提取+4. 日期格式:年-月-日(如 429-01-01)或年份(如 429)+5. 每条边必须连接已提取的节点++### 中文时间计算规则+当前观察日期:{observation_time}++1. **相对时间解析**:必须根据观察日期解析相对时间表达+ - "去年" → 计算为 {observation_time} 前一年+ - "今年" → {observation_time} 所属年份+ - "明年" → {observation_time} 后一年+ - "昨天" → {observation_time} 前一天+ - "今天" → {observation_time}+ - "明天" → {observation_time} 后一天+ - "上个月" → {observation_time} 前一个月的第一天+ - "这个月" → {observation_time} 所属月份的第一天+ - "下个月" → {observation_time} 后一个月的第一天+ - "十年前" → {observation_time} 前十年+ - "五年后" → {observation_time} 后五年+ - "年初" → 当年的 1月1日+ - "年末" → 当年的 12月31日+ - "世纪初" → 该世纪的第 1 年(如 2000 年)+ - "世纪末" → 该世纪的最后 1 年(如 2099 年)+ - "朝代" → 保留朝代名称(如"唐朝"、"宋代"),无需转换++2. **明确日期**:保持原文中的明确日期格式不变+ - 年份(如 429 年、2023 年)→ 429、2023+ - 年-月(如 429年3月)→ 429-03+ - 年-月-日(如 429年3月14日)→ 429-03-14+ - 中文数字日期(如"民国三十八年")→ 转换为公元纪年++3. **缺失时间**:如果文本中没有时间信息,将 eventDate 留空(None),不要编造日期++### 约束条件+- 不要创建未在文本中提及的实体或事件+- 保持客观准确,不添加文本中没有的信息### 源文本:"""-_NODE_PROMPT = """## 角色与任务-你是一位专业的人物识别专家,请从文本中提取所有人物作为节点。+_NODE_PROMPT = """你是一位专业的实体识别专家。请从文本中提取所有相关实体作为节点。-## 核心概念定义-- **节点 (Node)**:本模板中的"节点"指人物,包括人物姓名和简要描述。--## 提取规则-1. 提取所有人物,包括其姓名和简要描述-2. 保持人物姓名与原文一致+### 提取规则+1. 提取所有相关实体:人物、地点、组织、物品、概念等+2. 为每个实体指定类型:人物、地点、组织、物品、概念、其他+3. 为每个实体添加简要描述### 源文本:"""-_EDGE_PROMPT = """## 角色与任务-你是一位专业的生活事件提取专家,请从给定人物列表中提取生活事件。--## 核心概念定义-- **节点 (Node)**:本模板中的"节点"指人物,作为生活事件的参与者。-- **边 (Edge)**:本模板中的"边"指生活事件,包括事件类型、名称、时间、地点和描述。--## 提取规则-1. 仅从下方已知人物列表中提取事件-2. 每条事件必须连接相关的人物-3. 时间信息必须统一转换为「年-月-日」格式(如 2023-06-15)--### 时间解析规则-当前观察日期: {observation_time}--1. 相对时间解析(基于观察日期):- - "去年" → {observation_time} 的前一年,格式化为 YYYY-01-01- - "上月" → {observation_time} 的前一个月,格式化为 YYYY-MM-01+_EDGE_PROMPT = """你是一位专业的生活事件提取专家。请从给定实体列表中提取生活事件。++### 事件类型说明+- 出生:出生事件+- 逝世:逝世事件+- 教育:学习、受教育事件+- 工作:工作、职业事件+- 成就:取得成就、获得荣誉事件+- 交往:人际交往、社会活动事件+- 旅行:旅行、迁居事件+- 其他:其他事件++### 中文时间计算规则+当前观察日期:{observation_time}++1. **相对时间解析**:必须根据观察日期解析相对时间表达+ - "去年" → 计算为 {observation_time} 前一年+ - "今年" → {observation_time} 所属年份+ - "明年" → {observation_time} 后一年+ - "昨天" → {observation_time} 前一天+ - "今天" → {observation_time}+ - "明天" → {observation_time} 后一天+ - "上个月" → {observation_time} 前一个月的第一天+ - "这个月" → {observation_time} 所属月份的第一天+ - "下个月" → {observation_time} 后一个月的第一天+ - "十年前" → {observation_time} 前十年+ - "五年后" → {observation_time} 后五年+ - "年初" → 当年的 1月1日+ - "年末" → 当年的 12月31日+ - "世纪初" → 该世纪的第 1 年(如 2000 年)+ - "世纪末" → 该世纪的最后 1 年(如 2099 年)+ - "朝代" → 保留朝代名称(如"唐朝"、"宋代"),无需转换++2. **明确日期**:保持原文中的明确日期格式不变+ - 年份(如 429 年、2023 年)→ 429、2023+ - 年-月(如 429年3月)→ 429-03+ - 年-月-日(如 429年3月14日)→ 429-03-14+ - 中文数字日期(如"民国三十八年")→ 转换为公元纪年++3. **缺失时间**:如果文本中没有时间信息,将 eventDate 留空(None),不要编造日期++### 日期格式要求+- 所有日期信息统一转换为「年-月-日」格式(如 429-01-01)或年份(如 429)+- 时间信息为可选提取项,仅在文本中明确提及时才提取++### 约束条件+1. 仅从下方已知实体列表中提取事件+2. 不要创建未列出的实体+3. 时间信息为可选,仅在文本中明确提及时才提取"""-class LifeEventTimeline(AutoTemporalGraph[PersonEntity, LifeEvent]):+class LifeEventTimeline(AutoTemporalGraph[LifeEntity, LifeEvent]):"""- 适用文档: 人物传记、历史人物资料、个人履历-+ 适用文档: 人物传记、年表、回忆录、自传+功能介绍:- 提取人物的生活事件时间线,如出生、教育、工作、婚姻、死亡等重要事件。-+ 提取带时间戳的事件,并按时间顺序排列。适用于人物传记、年表、回忆录等。+Example:>>> template = LifeEventTimeline(llm_client=llm, embedder=embedder)- >>> template.feed_text("...")+ >>> template.feed_text("祖冲之(429年-500年),字文远,范阳遒县人...")>>> template.show()"""@@ -110,7 +175,7 @@ class LifeEventTimeline(AutoTemporalGraph[PersonEntity, LifeEvent]):):"""初始化生活事件时间线模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -124,14 +189,14 @@ class LifeEventTimeline(AutoTemporalGraph[PersonEntity, LifeEvent]):"""if observation_time is None:observation_time = datetime.now().strftime("%Y-%m-%d")-+super().__init__(- node_schema=PersonEntity,+ node_schema=LifeEntity,edge_schema=LifeEvent,node_key_extractor=lambda x: x.name,- edge_key_extractor=lambda x: f"{x.source}|{x.eventType}|{x.eventName}",- time_in_edge_extractor=lambda x: x.timeInfo or "",- nodes_in_edge_extractor=lambda x: (x.source, x.source),+ edge_key_extractor=lambda x: f"{x.source}|{x.eventType}|{x.details}",+ time_in_edge_extractor=lambda x: x.eventDate or "",+ nodes_in_edge_extractor=lambda x: (x.source, x.target),llm_client=llm_client,embedder=embedder,observation_time=observation_time,@@ -147,25 +212,34 @@ class LifeEventTimeline(AutoTemporalGraph[PersonEntity, LifeEvent]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""- 展示生活事件时间线。-+ 展示生平时序图。+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""- def node_label_extractor(node: PersonEntity) -> str:- return node.name-++ def node_label_extractor(node: LifeEntity) -> str:+ return f"{node.name} ({node.type})"+def edge_label_extractor(edge: LifeEvent) -> str:- return f"{edge.eventType}: {edge.eventName}"-+ if edge.eventDate:+ return f"{edge.eventType} ({edge.eventDate})"+ return f"{edge.eventType}"+super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,- )\ No newline at end of file+ 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/general/operational_procedure.py b/hyperextract/templates/zh/general/operational_procedure.pyindex 8c60aff..fe5bdd4 100644--- a/hyperextract/templates/zh/general/operational_procedure.py+++ b/hyperextract/templates/zh/general/operational_procedure.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoGraphclass ProcedureStep(BaseModel):"""流程步骤节点"""+stepId: str = Field(description="步骤编号,如步骤1、步骤2")name: str = Field(description="步骤名称")description: str = Field(description="步骤详细描述")@@ -22,6 +23,7 @@ class ProcedureStep(BaseModel):class ProcedureTransition(BaseModel):"""流程转换边"""+source: str = Field(description="源步骤编号")target: str = Field(description="目标步骤编号")condition: str = Field(description="转换条件", default="")@@ -114,7 +116,7 @@ class OperationalProcedure(AutoGraph[ProcedureStep, ProcedureTransition]):):"""初始化执行程序流程图模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -144,29 +146,34 @@ class OperationalProcedure(AutoGraph[ProcedureStep, ProcedureTransition]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示执行程序流程图。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 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.conditionreturn "→"-+super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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/general/penalty_mapping.py b/hyperextract/templates/zh/general/penalty_mapping.pyindex deade40..8e7092b 100644--- a/hyperextract/templates/zh/general/penalty_mapping.py+++ b/hyperextract/templates/zh/general/penalty_mapping.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoGraphclass PenaltyNode(BaseModel):"""处罚因果节点"""+name: str = Field(description="节点名称")type: str = Field(description="节点类型:违规行为、处理程序、处罚结果、其他")description: str = Field(description="详细描述")@@ -19,6 +20,7 @@ class PenaltyNode(BaseModel):class PenaltyPath(BaseModel):"""处罚因果路径边"""+source: str = Field(description="源节点名称")target: str = Field(description="目标节点名称")relation: str = Field(description="关系类型:导致、触发、执行、产生、其他")@@ -105,7 +107,7 @@ class PenaltyMapping(AutoGraph[PenaltyNode, PenaltyPath]):):"""初始化违规处罚因果链模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -135,27 +137,32 @@ class PenaltyMapping(AutoGraph[PenaltyNode, PenaltyPath]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示违规处罚因果链。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 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_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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/general/penalty_registry.py b/hyperextract/templates/zh/general/penalty_registry.pyindex 197edf7..cbf3b81 100644--- a/hyperextract/templates/zh/general/penalty_registry.py+++ b/hyperextract/templates/zh/general/penalty_registry.py@@ -22,9 +22,6 @@ class PenaltyEntry(BaseModel):_PROMPT = """## 角色与任务你是一位专业的合规分析专家,请从文本中提取所有违规行为及其对应的处罚措施,形成违规处罚对照表。-## 核心概念定义-- **元素 (Element)**:本模板中的"元素"指单条违规处罚条目,包含违规行为、严重程度、处罚措施、适用条款、备注等字段,通过违规行为+处罚措施组合进行去重的唯一知识单元。-## 提取规则1. 提取所有违规行为及其对应的处罚措施2. 为每条违规行为指定严重程度:轻微、一般、严重、特别严重diff --git a/hyperextract/templates/zh/general/personal_profile.py b/hyperextract/templates/zh/general/personal_profile.pyindex e6c97f8..2cb8371 100644--- a/hyperextract/templates/zh/general/personal_profile.py+++ b/hyperextract/templates/zh/general/personal_profile.py@@ -29,9 +29,6 @@ class PersonalInfo(BaseModel):_PROMPT = """## 角色与任务你是一位专业的人物档案编辑,请从文本中提取该人物的静态属性信息,构建个人档案。-## 核心概念定义-- **对象 (Object)**:本模板中的"对象"指个人档案信息,包含姓名、性别、生卒年、国籍、教育经历、职业、核心身份、主要成就等多个字段的结构化人物信息。-## 提取规则1. 提取姓名、性别、出生日期、逝世日期、国籍、出生地等基本信息2. 提取教育经历diff --git a/hyperextract/templates/zh/general/regulation_profile.py b/hyperextract/templates/zh/general/regulation_profile.pyindex a4c65c7..d74b1b8 100644--- a/hyperextract/templates/zh/general/regulation_profile.py+++ b/hyperextract/templates/zh/general/regulation_profile.py@@ -28,9 +28,6 @@ class RegulationInfo(BaseModel):_PROMPT = """## 角色与任务你是一位专业的规章制度分析专家,请从文本中提取该规章制度的元数据信息,构建规章元数据快照。-## 核心概念定义-- **对象 (Object)**:本模板中的"对象"指规章元数据信息,包含标题、版本、发布机构、发布/生效/失效日期、适用范围、适用对象、核心宗旨、关键词、关联规章等多个字段的结构化制度信息。-## 提取规则1. 提取规章的完整名称2. 提取版本号(如有)diff --git a/hyperextract/templates/zh/general/social_network.py b/hyperextract/templates/zh/general/social_network.pyindex c87a7ec..0bd2ea8 100644--- a/hyperextract/templates/zh/general/social_network.py+++ b/hyperextract/templates/zh/general/social_network.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoGraphclass PersonNode(BaseModel):"""人物/组织节点"""+name: str = Field(description="名称")type: str = Field(description="节点类型:人物、组织、机构、其他")description: str = Field(description="简要描述", default="")@@ -20,9 +21,12 @@ class PersonNode(BaseModel):class SocialRelation(BaseModel):"""社会关系边"""+source: str = Field(description="源节点")target: str = Field(description="目标节点")- relationType: str = Field(description="关系类型:亲属、朋友、同事、师生、上下级、合作、竞争、隶属、其他")+ relationType: str = Field(+ description="关系类型:亲属、朋友、同事、师生、上下级、合作、竞争、隶属、其他"+ )details: str = Field(description="关系详细说明", default="")@@ -127,7 +131,7 @@ class SocialNetwork(AutoGraph[PersonNode, SocialRelation]):):"""初始化社交网络图模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -157,29 +161,34 @@ class SocialNetwork(AutoGraph[PersonNode, SocialRelation]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示社交网络图。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""+def node_label_extractor(node: PersonNode) -> str:if node.role:return f"{node.name} ({node.role})"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_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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/history/diplomatic_event_hypergraph.py b/hyperextract/templates/zh/history/diplomatic_event_hypergraph.pyindex a87b1ff..20b5680 100644--- a/hyperextract/templates/zh/history/diplomatic_event_hypergraph.py+++ b/hyperextract/templates/zh/history/diplomatic_event_hypergraph.py@@ -65,7 +65,7 @@ class DiplomaticEventHypergraph(AutoHypergraph[CountrySchema, DiplomaticEventSch**kwargs,)- def show(self, *, top_k_for_search: int = 5, top_k_for_chat: int = 5) -> None:+ 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) -> None:def node_label(node: CountrySchema) -> str:return f"🏛️ {node.country_name}"def edge_label(edge: DiplomaticEventSchema) -> str:@@ -73,6 +73,5 @@ class DiplomaticEventHypergraph(AutoHypergraph[CountrySchema, DiplomaticEventSchsuper().show(node_label_extractor=node_label,edge_label_extractor=edge_label,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,+ 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/history/war_timeline_graph.py b/hyperextract/templates/zh/history/war_timeline_graph.pyindex d49f504..44d0f12 100644--- a/hyperextract/templates/zh/history/war_timeline_graph.py+++ b/hyperextract/templates/zh/history/war_timeline_graph.py@@ -69,7 +69,7 @@ class WarTimelineGraph(AutoTemporalGraph[HistoricalEntitySchema, TemporalEventSc**kwargs,)- def show(self, *, top_k_for_search: int = 5, top_k_for_chat: int = 5) -> None:+ 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) -> None:def node_label(node: HistoricalEntitySchema) -> str:return f"{node.entity_name} ({node.entity_type})"def edge_label(edge: TemporalEventSchema) -> str:@@ -77,6 +77,5 @@ class WarTimelineGraph(AutoTemporalGraph[HistoricalEntitySchema, TemporalEventScsuper().show(node_label_extractor=node_label,edge_label_extractor=edge_label,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,+ 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/legal/corporate_equity_graph.py b/hyperextract/templates/zh/legal/corporate_equity_graph.pyindex 7c51b69..db43ade 100644--- a/hyperextract/templates/zh/legal/corporate_equity_graph.py+++ b/hyperextract/templates/zh/legal/corporate_equity_graph.py@@ -62,7 +62,7 @@ class CorporateEquityGraph(AutoGraph[EntitySchema, EquityRelationshipSchema]):**kwargs,)- def show(self, *, top_k_for_search: int = 5, top_k_for_chat: int = 5) -> None:+ 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) -> None:def node_label(node: EntitySchema) -> str:type_icon = {"公司": "🏢", "个人": "👤", "基金": "💼"}icon = type_icon.get(node.entity_type, "●")@@ -73,6 +73,5 @@ class CorporateEquityGraph(AutoGraph[EntitySchema, EquityRelationshipSchema]):super().show(node_label_extractor=node_label,edge_label_extractor=edge_label,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,+ 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/literature/character_relationship_graph.py b/hyperextract/templates/zh/literature/character_relationship_graph.pyindex bc286c8..2e67848 100644--- a/hyperextract/templates/zh/literature/character_relationship_graph.py+++ b/hyperextract/templates/zh/literature/character_relationship_graph.py@@ -8,21 +8,34 @@ from hyperextract.types import AutoGraph# 1. Schema 定义 (Schema Definitions)# ==============================================================================+class Character(BaseModel):"""文学作品中的人物实体。"""+name: str = Field(description="人物的正式姓名或最常用称呼。")- aliases: List[str] = Field(default_factory=list, description="人物的其他称呼、头衔或绰号。")- traits: List[str] = Field(default_factory=list, description="人物的核心性格、能力或生理特征。")- description: Optional[str] = Field(description="关于人物在作品中地位及核心情节的简要描述。")+ aliases: List[str] = Field(+ default_factory=list, description="人物的其他称呼、头衔或绰号。"+ )+ traits: List[str] = Field(+ default_factory=list, description="人物的核心性格、能力或生理特征。"+ )+ description: Optional[str] = Field(+ description="关于人物在作品中地位及核心情节的简要描述。"+ )+class Relationship(BaseModel):"""人物之间的互动与联系。"""+source: str = Field(description="发起关系的或关系的第一个人物名称。")target: str = Field(description="关系指向的或关系的第二个人物名称。")- relation_type: str = Field(description="关系的性质(如:亲属、爱慕、仇恨、师徒、盟友)。")+ relation_type: str = Field(+ description="关系的性质(如:亲属、爱慕、仇恨、师徒、盟友)。"+ )sentiment: str = Field(description="关系的情感倾向(如:正面、负面、中立、复杂)。")evidence: str = Field(description="支持该关系的文本证据或关键情节简述。")+# ==============================================================================# 2. 提示词 (Prompts)# ==============================================================================@@ -36,18 +49,15 @@ _PROMPT = ("- 确保边连接的两个人物都已在节点列表中列出。")-_NODE_PROMPT = (- "作为文学分析专家,请从文本中提取所有关键人物。记录其姓名、所有已知的别称、核心性格标签以及简要的生平或地位描述。"-)+_NODE_PROMPT = "作为文学分析专家,请从文本中提取所有关键人物。记录其姓名、所有已知的别称、核心性格标签以及简要的生平或地位描述。"-_EDGE_PROMPT = (- "基于已提取的人物列表,识别他们之间的社交与情感关系。请说明关系的类型(如‘宿敌’)、情感色彩(如‘强烈恨意’)并提供证据。"-)+_EDGE_PROMPT = "基于已提取的人物列表,识别他们之间的社交与情感关系。请说明关系的类型(如‘宿敌’)、情感色彩(如‘强烈恨意’)并提供证据。"# ==============================================================================# 3. 模板类 (Template Class)# ==============================================================================+class CharacterRelationshipGraph(AutoGraph[Character, Relationship]):"""适用于:[小说, 剧本, 传记, 戏剧]@@ -73,12 +83,12 @@ class CharacterRelationshipGraph(AutoGraph[Character, Relationship]):llm_client: BaseChatModel,embedder: Embeddings,*,- extraction_mode: str = "one_stage",+ extraction_mode: str = "two_stage",chunk_size: int = 2048,chunk_overlap: int = 256,max_workers: int = 10,verbose: bool = False,- **kwargs: Any+ **kwargs: Any,):"""初始化 CharacterRelationshipGraph 模板。@@ -109,22 +119,27 @@ class CharacterRelationshipGraph(AutoGraph[Character, Relationship]):chunk_overlap=chunk_overlap,max_workers=max_workers,verbose=verbose,- **kwargs+ **kwargs,)def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,) -> None:"""可视化人物关系图谱。Args:- top_k_for_search: 搜索时找回的相关节点/边数量。- top_k_for_chat: 聊天时找回的相关节点/边数量。+ top_k_nodes_for_search: 搜索时找回的相关节点数量。+ top_k_edges_for_search: 搜索时找回的相关边数量。+ top_k_nodes_for_chat: 聊天时找回的相关节点数量。+ top_k_edges_for_chat: 聊天时找回的相关边数量。"""+def node_label_extractor(node: Character) -> str:return node.name@@ -134,8 +149,8 @@ class CharacterRelationshipGraph(AutoGraph[Character, Relationship]):super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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/literature/narrative_timeline.py b/hyperextract/templates/zh/literature/narrative_timeline.pyindex 9870c09..403671b 100644--- a/hyperextract/templates/zh/literature/narrative_timeline.py+++ b/hyperextract/templates/zh/literature/narrative_timeline.py@@ -8,20 +8,29 @@ from hyperextract.types import AutoTemporalGraph# 1. Schema 定义 (Schema Definitions)# ==============================================================================+class NarrativePoint(BaseModel):"""叙事流中的核心情节节点。"""+name: str = Field(description="情节或事件的短标题(如‘鸿门宴’、‘初遇’)。")location: Optional[str] = Field(description="事件发生的地点。")- characters_involved: List[str] = Field(default_factory=list, description="参与该事件的人物名单。")+ characters_involved: List[str] = Field(+ default_factory=list, description="参与该事件的人物名单。"+ )description: str = Field(description="对情节内容的具体描述,包括核心动作和转折。")+class TimeTransition(BaseModel):"""情节节点之间的时间演变与逻辑关联。"""+source: str = Field(description="起始情节名称。")target: str = Field(description="后续情节名称。")- time: str = Field(description="事实发生的时间。你必须结合上下文和观察日期,将相对时间(如‘三天后’、‘次日’)解析并转换为绝对日期(如‘2024-01-15’)或具体年份。")+ time: str = Field(+ description="事实发生的时间。你必须结合上下文和观察日期,将相对时间(如‘三天后’、‘次日’)解析并转换为绝对日期(如‘2024-01-15’)或具体年份。"+ )logic: str = Field(description="事件间的逻辑关系(如:因果、递进、意外转折)。")+# ==============================================================================# 2. 提示词 (Prompts)# ==============================================================================@@ -35,18 +44,15 @@ _PROMPT = ("注意:时间必须提取在边(Transition)上,不要作为独立的节点。")-_NODE_PROMPT = (- "请识别并提取文本中所有的关键情节节点(Plot Points)。为每个节点命名,并提供地点描述及涉及的人物。"-)+_NODE_PROMPT = "请识别并提取文本中所有的关键情节节点(Plot Points)。为每个节点命名,并提供地点描述及涉及的人物。"-_EDGE_PROMPT = (- "在给定的情节节点之间建立联系。请精确提取文本中提及的时间线索,并描述这些事件是如何在叙事逻辑上相互连接的。"-)+_EDGE_PROMPT = "在给定的情节节点之间建立联系。请精确提取文本中提及的时间线索,并描述这些事件是如何在叙事逻辑上相互连接的。"# ==============================================================================# 3. 模板类 (Template Class)# ==============================================================================+class NarrativeTimeline(AutoTemporalGraph[NarrativePoint, TimeTransition]):"""适用于:[编年史, 史诗文学, 侦探小说, 史书]@@ -78,7 +84,7 @@ class NarrativeTimeline(AutoTemporalGraph[NarrativePoint, TimeTransition]):chunk_overlap: int = 256,max_workers: int = 10,verbose: bool = False,- **kwargs: Any+ **kwargs: Any,):"""初始化 NarrativeTimeline 模板。@@ -112,22 +118,27 @@ class NarrativeTimeline(AutoTemporalGraph[NarrativePoint, TimeTransition]):chunk_overlap=chunk_overlap,max_workers=max_workers,verbose=verbose,- **kwargs+ **kwargs,)def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,) -> None:"""可视化叙事时间线。Args:- top_k_for_search: 搜索时找回的相关节点/边数量。- top_k_for_chat: 聊天时找回的相关节点/边数量。+ top_k_nodes_for_search: 搜索时找回的相关节点数量。+ top_k_edges_for_search: 搜索时找回的相关边数量。+ top_k_nodes_for_chat: 聊天时找回的相关节点数量。+ top_k_edges_for_chat: 聊天时找回的相关边数量。"""+def node_label_extractor(node: NarrativePoint) -> str:return node.name@@ -137,8 +148,8 @@ class NarrativeTimeline(AutoTemporalGraph[NarrativePoint, TimeTransition]):super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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/medicine/anatomy_hierarchy.py b/hyperextract/templates/zh/medicine/anatomy_hierarchy.pyindex 6ff950b..b50a6f1 100644--- a/hyperextract/templates/zh/medicine/anatomy_hierarchy.py+++ b/hyperextract/templates/zh/medicine/anatomy_hierarchy.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoGraphclass AnatomyEntity(BaseModel):"""解剖实体节点"""+name: str = Field(description="解剖结构名称,如器官、组织、血管等")category: str = Field(description="解剖类型:器官、组织、血管、神经、骨骼等")description: str = Field(description="简要描述", default="")@@ -19,9 +20,12 @@ class AnatomyEntity(BaseModel):class AnatomyRelation(BaseModel):"""解剖关系边"""+source: str = Field(description="源解剖结构")target: str = Field(description="目标解剖结构")- relationType: str = Field(description="关系类型:包含(Part-Of)、毗邻(Connected-To)、分支、供应等")+ relationType: str = Field(+ description="关系类型:包含(Part-Of)、毗邻(Connected-To)、分支、供应等"+ )details: str = Field(description="详细描述", default="")@@ -109,7 +113,7 @@ class AnatomyHierarchy(AutoGraph[AnatomyEntity, AnatomyRelation]):):"""初始化解剖层级树模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -139,27 +143,32 @@ class AnatomyHierarchy(AutoGraph[AnatomyEntity, AnatomyRelation]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示解剖层级树。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""+def node_label_extractor(node: AnatomyEntity) -> str:return f"{node.name} ({node.category})"-+def edge_label_extractor(edge: AnatomyRelation) -> 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_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,- )\ No newline at end of file+ 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/medicine/clinical_pathway.py b/hyperextract/templates/zh/medicine/clinical_pathway.pyindex 081b5e7..8bc6c43 100644--- a/hyperextract/templates/zh/medicine/clinical_pathway.py+++ b/hyperextract/templates/zh/medicine/clinical_pathway.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoGraphclass ClinicalNode(BaseModel):"""临床节点"""+name: str = Field(description="节点名称,如症状、检查、治疗等")category: str = Field(description="节点类型:症状、检查、治疗、诊断、决策点等")description: str = Field(description="简要描述", default="")@@ -19,6 +20,7 @@ class ClinicalNode(BaseModel):class ClinicalEdge(BaseModel):"""临床路径边"""+source: str = Field(description="源节点")target: str = Field(description="目标节点")condition: str = Field(description="条件描述,如If 症状A Then")@@ -109,7 +111,7 @@ class ClinicalPathway(AutoGraph[ClinicalNode, ClinicalEdge]):):"""初始化临床路径图模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -139,27 +141,32 @@ class ClinicalPathway(AutoGraph[ClinicalNode, ClinicalEdge]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示临床路径图。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""+def node_label_extractor(node: ClinicalNode) -> str:return f"{node.name} ({node.category})"-+def edge_label_extractor(edge: ClinicalEdge) -> str:return edge.condition-+super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,- )\ No newline at end of file+ 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/medicine/complex_interaction_net.py b/hyperextract/templates/zh/medicine/complex_interaction_net.pyindex 892a849..43d593d 100644--- a/hyperextract/templates/zh/medicine/complex_interaction_net.py+++ b/hyperextract/templates/zh/medicine/complex_interaction_net.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoHypergraphclass InteractionEntity(BaseModel):"""相互作用实体节点"""+name: str = Field(description="实体名称,如药物、体质、不良反应等")category: str = Field(description="实体类型:药物、体质、不良反应、其他等")description: str = Field(description="简要描述", default="")@@ -19,6 +20,7 @@ class InteractionEntity(BaseModel):class InteractionHyperedge(BaseModel):"""相互作用超边"""+name: str = Field(description="超边名称,如药物相互作用")nodes: List[str] = Field(description="参与超边的节点列表")interactionType: str = Field(description="相互作用类型:增强、减弱、不良反应等")@@ -111,7 +113,7 @@ class ComplexInteractionNet(AutoHypergraph[InteractionEntity, InteractionHypered):"""初始化条件性相互作用网模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -141,27 +143,32 @@ class ComplexInteractionNet(AutoHypergraph[InteractionEntity, InteractionHypereddef show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示条件性相互作用网。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""+def node_label_extractor(node: InteractionEntity) -> str:return f"{node.name} ({node.category})"-+def edge_label_extractor(edge: InteractionHyperedge) -> str:return f"{edge.name}: {edge.interactionType}"-+super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,- )\ No newline at end of file+ 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/medicine/discharge_instruction.py b/hyperextract/templates/zh/medicine/discharge_instruction.pyindex 3bedaf1..ab10d58 100644--- a/hyperextract/templates/zh/medicine/discharge_instruction.py+++ b/hyperextract/templates/zh/medicine/discharge_instruction.py@@ -12,8 +12,13 @@ from hyperextract.types import AutoModelclass DischargeInstructionInfo(BaseModel):"""出院医嘱信息"""- medications: List[dict] = Field(description="出院带药列表,每个药物包含名称、剂量、用法、频次等信息")- followUp: List[dict] = Field(description="复诊计划列表,每个复诊包含时间、科室、检查项目等信息")++ medications: List[dict] = Field(+ description="出院带药列表,每个药物包含名称、剂量、用法、频次等信息"+ )+ followUp: List[dict] = Field(+ description="复诊计划列表,每个复诊包含时间、科室、检查项目等信息"+ )rehabilitation: List[str] = Field(description="康复建议列表")diet: List[str] = Field(description="饮食建议列表", default_factory=list)activity: List[str] = Field(description="活动建议列表", default_factory=list)@@ -23,9 +28,6 @@ class DischargeInstructionInfo(BaseModel):_PROMPT = """## 角色与任务你是一位专业的医生,请从文本中提取出院带药、复诊计划及康复建议的结构化信息,构建出院医嘱摘要。-## 核心概念定义-- **对象 (Object)**:本模板中的"对象"指出院医嘱信息,包含出院带药、复诊计划、康复建议、饮食建议、活动建议和其他注意事项的结构化信息。-## 提取规则1. 提取所有出院带药信息,每个药物包含名称、剂量、用法、频次等信息2. 提取所有复诊计划信息,每个复诊包含时间、科室、检查项目等信息@@ -64,7 +66,7 @@ class DischargeInstruction(AutoModel[DischargeInstructionInfo]):):"""初始化出院医嘱摘要模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -89,14 +91,15 @@ class DischargeInstruction(AutoModel[DischargeInstructionInfo]):):"""展示出院医嘱摘要。-+Args:top_k: 问答使用的条目数量,默认为 3"""+def label_extractor(item: DischargeInstructionInfo) -> str:return "出院医嘱摘要"-+super().show(label_extractor=label_extractor,top_k=top_k,- )\ No newline at end of file+ )diff --git a/hyperextract/templates/zh/medicine/hospital_course_timeline.py b/hyperextract/templates/zh/medicine/hospital_course_timeline.pyindex ffc55db..9c3034e 100644--- a/hyperextract/templates/zh/medicine/hospital_course_timeline.py+++ b/hyperextract/templates/zh/medicine/hospital_course_timeline.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoTemporalGraphclass HospitalEntity(BaseModel):"""住院实体节点"""+name: str = Field(description="节点名称,如入院、检查、治疗、转归等")category: str = Field(description="节点类型:入院、检查、治疗、手术、转归、其他等")description: str = Field(description="简要描述", default="")@@ -19,6 +20,7 @@ class HospitalEntity(BaseModel):class HospitalEvent(BaseModel):"""住院事件边"""+source: str = Field(description="源节点")target: str = Field(description="目标节点")eventType: str = Field(description="事件类型:入院、检查、治疗、手术、转归等")@@ -142,7 +144,7 @@ class HospitalCourseTimeline(AutoTemporalGraph[HospitalEntity, HospitalEvent]):):"""初始化住院病程时间轴模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -175,27 +177,32 @@ class HospitalCourseTimeline(AutoTemporalGraph[HospitalEntity, HospitalEvent]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示住院病程时间轴。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""+def node_label_extractor(node: HospitalEntity) -> str:return f"{node.name} ({node.category})"-+def edge_label_extractor(edge: HospitalEvent) -> str:return f"{edge.eventType} ({edge.eventDate})"-+super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,- )\ No newline at end of file+ 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/medicine/level_of_evidence.py b/hyperextract/templates/zh/medicine/level_of_evidence.pyindex 8a953df..04de284 100644--- a/hyperextract/templates/zh/medicine/level_of_evidence.py+++ b/hyperextract/templates/zh/medicine/level_of_evidence.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoListclass EvidenceItem(BaseModel):"""证据条目"""+recommendation: str = Field(description="推荐意见")evidenceLevel: str = Field(description="证据等级,如A、B、C、1a、1b等")recommendationLevel: str = Field(description="推荐级别,如强推荐、弱推荐等")@@ -62,7 +63,7 @@ class LevelOfEvidence(AutoList[EvidenceItem]):):"""初始化证据评级表模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -88,16 +89,17 @@ class LevelOfEvidence(AutoList[EvidenceItem]):):"""展示证据评级表。-+Args:top_k_for_search: 语义检索返回的条目数量,默认为 3top_k_for_chat: 问答使用的条目数量,默认为 3"""+def item_label_extractor(item: EvidenceItem) -> str:return f"{item.recommendationLevel} (证据等级: {item.evidenceLevel})"-+super().show(item_label_extractor=item_label_extractor,top_k_items_for_search=top_k_for_search,top_k_items_for_chat=top_k_for_chat,- )\ No newline at end of file+ )diff --git a/hyperextract/templates/zh/medicine/medical_concept_net.py b/hyperextract/templates/zh/medicine/medical_concept_net.pyindex 1e81896..5876e25 100644--- a/hyperextract/templates/zh/medicine/medical_concept_net.py+++ b/hyperextract/templates/zh/medicine/medical_concept_net.py@@ -12,16 +12,22 @@ from hyperextract.types import AutoGraphclass MedicalConcept(BaseModel):"""医学概念节点"""+name: str = Field(description="概念名称,如医学术语、疾病名称、解剖部位等")- category: str = Field(description="概念类型:疾病、解剖部位、生理过程、药物、症状、体征等")+ category: str = Field(+ description="概念类型:疾病、解剖部位、生理过程、药物、症状、体征等"+ )definition: str = Field(description="概念定义", default="")class MedicalRelation(BaseModel):"""医学概念关系边"""+source: str = Field(description="源概念")target: str = Field(description="目标概念")- relationType: str = Field(description="关系类型:属于、定义为、包含、组成、位于、导致、治疗等")+ relationType: str = Field(+ description="关系类型:属于、定义为、包含、组成、位于、导致、治疗等"+ )details: str = Field(description="详细描述", default="")@@ -109,7 +115,7 @@ class MedicalConceptNet(AutoGraph[MedicalConcept, MedicalRelation]):):"""初始化医学概念网络模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -139,27 +145,32 @@ class MedicalConceptNet(AutoGraph[MedicalConcept, MedicalRelation]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示医学概念网络。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""+def node_label_extractor(node: MedicalConcept) -> str:return f"{node.name} ({node.category})"-+def edge_label_extractor(edge: MedicalRelation) -> 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_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,- )\ No newline at end of file+ 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/medicine/microscopic_feature_set.py b/hyperextract/templates/zh/medicine/microscopic_feature_set.pyindex 0a3fb47..53b8f78 100644--- a/hyperextract/templates/zh/medicine/microscopic_feature_set.py+++ b/hyperextract/templates/zh/medicine/microscopic_feature_set.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoSetclass MicroscopicFeatureItem(BaseModel):"""微观特征条目"""+featureName: str = Field(description="特征名称,如免疫组化指标、基因突变等")featureType: str = Field(description="特征类型:免疫组化、基因突变、其他等")value: str = Field(description="特征值,如阳性、阴性、百分比等")@@ -63,7 +64,7 @@ class MicroscopicFeatureSet(AutoSet[MicroscopicFeatureItem]):):"""初始化微观特征集模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -90,16 +91,17 @@ class MicroscopicFeatureSet(AutoSet[MicroscopicFeatureItem]):):"""展示微观特征集。-+Args:top_k_for_search: 语义检索返回的条目数量,默认为 3top_k_for_chat: 问答使用的条目数量,默认为 3"""+def label_extractor(item: MicroscopicFeatureItem) -> str:return f"{item.featureName} ({item.featureType}): {item.value}"-+super().show(label_extractor=label_extractor,top_k_items_for_search=top_k_for_search,top_k_items_for_chat=top_k_for_chat,- )\ No newline at end of file+ )diff --git a/hyperextract/templates/zh/medicine/pathology_hypergraph.py b/hyperextract/templates/zh/medicine/pathology_hypergraph.pyindex 432e5dc..015bb22 100644--- a/hyperextract/templates/zh/medicine/pathology_hypergraph.py+++ b/hyperextract/templates/zh/medicine/pathology_hypergraph.py@@ -12,13 +12,17 @@ from hyperextract.types import AutoHypergraphclass PathologyEntity(BaseModel):"""病理实体节点"""+name: str = Field(description="实体名称,如基因、环境因素、诱因、疾病等")- category: str = Field(description="实体类型:基因、环境因素、诱因、疾病、病理过程、症状等")+ category: str = Field(+ description="实体类型:基因、环境因素、诱因、疾病、病理过程、症状等"+ )description: str = Field(description="简要描述", default="")class PathologyHyperedge(BaseModel):"""病理机制超边"""+name: str = Field(description="超边名称,如致病机制、发病过程等")nodes: List[str] = Field(description="参与超边的节点列表")relationType: str = Field(description="关系类型:致病、诱发、促进、抑制等")@@ -111,7 +115,7 @@ class PathologyHypergraph(AutoHypergraph[PathologyEntity, PathologyHyperedge]):):"""初始化多因素病理机制图模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -141,27 +145,32 @@ class PathologyHypergraph(AutoHypergraph[PathologyEntity, PathologyHyperedge]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示多因素病理机制图。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""+def node_label_extractor(node: PathologyEntity) -> str:return f"{node.name} ({node.category})"-+def edge_label_extractor(edge: PathologyHyperedge) -> str:return f"{edge.name}: {edge.relationType}"-+super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,- )\ No newline at end of file+ 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/medicine/pharmacology_graph.py b/hyperextract/templates/zh/medicine/pharmacology_graph.pyindex 2b2fac8..a5f4384 100644--- a/hyperextract/templates/zh/medicine/pharmacology_graph.py+++ b/hyperextract/templates/zh/medicine/pharmacology_graph.py@@ -12,16 +12,22 @@ from hyperextract.types import AutoGraphclass PharmacologyEntity(BaseModel):"""药理实体节点"""+name: str = Field(description="实体名称,如药物、受体、靶点、生理反应等")- category: str = Field(description="实体类型:药物、受体、靶点、生理反应、信号通路等")+ category: str = Field(+ description="实体类型:药物、受体、靶点、生理反应、信号通路等"+ )description: str = Field(description="简要描述", default="")class PharmacologyRelation(BaseModel):"""药理机制关系边"""+source: str = Field(description="源实体")target: str = Field(description="目标实体")- relationType: str = Field(description="关系类型:结合、激活、抑制、调节、诱导、抑制等")+ relationType: str = Field(+ description="关系类型:结合、激活、抑制、调节、诱导、抑制等"+ )details: str = Field(description="详细描述,如具体的作用机制")@@ -109,7 +115,7 @@ class PharmacologyGraph(AutoGraph[PharmacologyEntity, PharmacologyRelation]):):"""初始化药理机制图模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -139,27 +145,32 @@ class PharmacologyGraph(AutoGraph[PharmacologyEntity, PharmacologyRelation]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示药理机制图。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""+def node_label_extractor(node: PharmacologyEntity) -> str:return f"{node.name} ({node.category})"-+def edge_label_extractor(edge: PharmacologyRelation) -> 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_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,- )\ No newline at end of file+ 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/medicine/surgical_event_graph.py b/hyperextract/templates/zh/medicine/surgical_event_graph.pyindex 5718a53..6fdc68f 100644--- a/hyperextract/templates/zh/medicine/surgical_event_graph.py+++ b/hyperextract/templates/zh/medicine/surgical_event_graph.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoHypergraphclass SurgicalEntity(BaseModel):"""手术实体节点"""+name: str = Field(description="实体名称,如医生、部位、术式、器械等")category: str = Field(description="实体类型:医生、部位、术式、器械、麻醉方式等")description: str = Field(description="简要描述", default="")@@ -19,6 +20,7 @@ class SurgicalEntity(BaseModel):class SurgicalHyperedge(BaseModel):"""手术事件超边"""+name: str = Field(description="超边名称,如手术名称")nodes: List[str] = Field(description="参与超边的节点列表")date: str = Field(description="手术日期")@@ -114,7 +116,7 @@ class SurgicalEventGraph(AutoHypergraph[SurgicalEntity, SurgicalHyperedge]):):"""初始化手术事件超图模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -144,27 +146,32 @@ class SurgicalEventGraph(AutoHypergraph[SurgicalEntity, SurgicalHyperedge]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示手术事件超图。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""+def node_label_extractor(node: SurgicalEntity) -> str:return f"{node.name} ({node.category})"-+def edge_label_extractor(edge: SurgicalHyperedge) -> str:return f"{edge.name} ({edge.date})"-+super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,- )\ No newline at end of file+ 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/medicine/treatment_regimen_map.py b/hyperextract/templates/zh/medicine/treatment_regimen_map.pyindex df24a0b..891ee40 100644--- a/hyperextract/templates/zh/medicine/treatment_regimen_map.py+++ b/hyperextract/templates/zh/medicine/treatment_regimen_map.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoHypergraphclass TreatmentEntity(BaseModel):"""治疗实体节点"""+name: str = Field(description="实体名称,如药物、理疗方法、生活干预等")category: str = Field(description="实体类型:药物、理疗、生活干预、检查、手术等")description: str = Field(description="简要描述", default="")@@ -19,6 +20,7 @@ class TreatmentEntity(BaseModel):class TreatmentHyperedge(BaseModel):"""治疗方案超边"""+name: str = Field(description="超边名称,如治疗方案、康复计划等")nodes: List[str] = Field(description="参与超边的节点列表")disease: str = Field(description="针对的疾病")@@ -111,7 +113,7 @@ class TreatmentRegimenMap(AutoHypergraph[TreatmentEntity, TreatmentHyperedge]):):"""初始化综合治疗方案图模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -141,27 +143,32 @@ class TreatmentRegimenMap(AutoHypergraph[TreatmentEntity, TreatmentHyperedge]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示综合治疗方案图。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""+def node_label_extractor(node: TreatmentEntity) -> str:return f"{node.name} ({node.category})"-+def edge_label_extractor(edge: TreatmentHyperedge) -> str:return f"{edge.name} - {edge.disease}"-+super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,- )\ No newline at end of file+ 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/medicine/tumor_staging_item.py b/hyperextract/templates/zh/medicine/tumor_staging_item.pyindex 84f89cb..1393fd5 100644--- a/hyperextract/templates/zh/medicine/tumor_staging_item.py+++ b/hyperextract/templates/zh/medicine/tumor_staging_item.py@@ -24,9 +24,6 @@ class TumorStagingInfo(BaseModel):_PROMPT = """## 角色与任务你是一位专业的病理学家,请从文本中提取肿瘤大小(T)、淋巴结(N)、转移(M)及分期结果,构建TNM分期表。-## 核心概念定义-- **对象 (Object)**:本模板中的"对象"指肿瘤分期信息,包含T分期、N分期、M分期、病理分期及详细描述的结构化信息。-## 提取规则1. 提取T分期、N分期、M分期和病理分期2. 为每个分期添加详细描述:diff --git a/hyperextract/templates/zh/tcm/acupoint_location_map.py b/hyperextract/templates/zh/tcm/acupoint_location_map.pyindex e911b0f..ea36b18 100644--- a/hyperextract/templates/zh/tcm/acupoint_location_map.py+++ b/hyperextract/templates/zh/tcm/acupoint_location_map.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoGraphclass AcupointNode(BaseModel):"""穴位节点"""+name: str = Field(description="穴位名称:如合谷、足三里、三阴交等")meridian: str = Field(description="所属经脉", default="")location: str = Field(description="位置描述:如脐旁2寸、腕横纹上3寸等")@@ -20,6 +21,7 @@ class AcupointNode(BaseModel):class LocationRelation(BaseModel):"""位置关系边"""+source: str = Field(description="源穴位或解剖标志名称")target: str = Field(description="目标穴位名称")relationType: str = Field(description="关系类型:位于")@@ -50,6 +52,11 @@ _PROMPT = """## 角色与任务- 不要创建未在文本中提及的实体或关系- 保持客观准确,符合针灸学专业术语规范+### 术语标准化指导+- **穴位名称统一**:确保使用标准穴位名称+- **位置描述保留**:文言中位置描述(如"寸"、"分"、"旁"、"上"、"下"等)保持原文+- **解剖标志识别**:准确识别文言中提到的解剖标志+### 源文本:"""@@ -91,10 +98,10 @@ _EDGE_PROMPT = """## 角色与任务class AcupointLocationMap(AutoGraph[AcupointNode, LocationRelation]):"""适用文档: 针灸学教材、穴位图谱、黄帝内经等-+功能介绍:基于人体解剖标志提取穴位的相对位置关系(如"脐旁2寸"),适用于针灸教学可视化、穴位图谱。-+Example:>>> template = AcupointLocationMap(llm_client=llm, embedder=embedder)>>> template.feed_text("合谷穴:在手背,第1、2掌骨间,当第2掌骨桡侧的中点处...")@@ -105,7 +112,7 @@ class AcupointLocationMap(AutoGraph[AcupointNode, LocationRelation]):self,llm_client: BaseChatModel,embedder: Embeddings,- *,+ *,extraction_mode: str = "two_stage",max_workers: int = 10,verbose: bool = False,@@ -113,7 +120,7 @@ class AcupointLocationMap(AutoGraph[AcupointNode, LocationRelation]):):"""初始化腧穴空间定位模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -142,28 +149,33 @@ class AcupointLocationMap(AutoGraph[AcupointNode, LocationRelation]):def show(self,- *,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ *,+ 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,):"""展示腧穴空间定位图。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""+def node_label_extractor(node: AcupointNode) -> str:return f"{node.name} ({node.meridian})"-+def edge_label_extractor(edge: LocationRelation) -> str:return edge.relativePosition-+super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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/tcm/compatibility_net.py b/hyperextract/templates/zh/tcm/compatibility_net.pyindex 1fe90e1..e50c1b6 100644--- a/hyperextract/templates/zh/tcm/compatibility_net.py+++ b/hyperextract/templates/zh/tcm/compatibility_net.py@@ -12,15 +12,19 @@ from hyperextract.types import AutoGraphclass HerbEntity(BaseModel):"""药物实体节点"""+name: str = Field(description="药物名称")description: str = Field(description="简要描述", default="")class CompatibilityRelation(BaseModel):"""配伍关系边"""+source: str = Field(description="源药物")target: str = Field(description="目标药物")- relationType: str = Field(description="配伍关系类型:相须、相使、相畏、相杀、相恶、相反、十八反、十九畏")+ relationType: str = Field(+ description="配伍关系类型:相须、相使、相畏、相杀、相恶、相反、十八反、十九畏"+ )effect: str = Field(description="配伍效果描述", default="")@@ -46,6 +50,12 @@ _PROMPT = """## 角色与任务- 不要创建未在文本中提及的实体或关系- 保持客观准确,符合中药配伍专业术语规范+### 术语标准化指导+- **药物名称标准化**:同一药物的不同名称需统一使用规范正名+- **配伍关系统一**:确保关系类型使用标准术语:相须、相使、相畏、相杀、相恶、相反、十八反、十九畏+- **禁忌表述识别**:准确识别"反"、"畏"、"恶"等配伍禁忌表述+- **双向关系处理**:配伍关系通常是双向的,但按原文表述顺序提取即可+### 源文本:"""@@ -81,10 +91,10 @@ _EDGE_PROMPT = """## 角色与任务class CompatibilityNet(AutoGraph[HerbEntity, CompatibilityRelation]):"""适用文档: 本草典籍、中药配伍指南、方剂学教材等-+功能介绍:提取药物间的相须、相使、相畏、相杀、十八反十九畏关系,适用于配伍禁忌预警、方剂组网分析。-+Example:>>> template = CompatibilityNet(llm_client=llm, embedder=embedder)>>> template.feed_text("甘草反大戟、芫花、甘遂、海藻...")@@ -103,7 +113,7 @@ class CompatibilityNet(AutoGraph[HerbEntity, CompatibilityRelation]):):"""初始化七情配伍网络模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -132,28 +142,33 @@ class CompatibilityNet(AutoGraph[HerbEntity, CompatibilityRelation]):def show(self,- *,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ *,+ 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,):"""展示七情配伍网络。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""+def node_label_extractor(node: HerbEntity) -> str:return node.name-+def edge_label_extractor(edge: CompatibilityRelation) -> 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_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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/tcm/formula_composition.py b/hyperextract/templates/zh/tcm/formula_composition.pyindex 6df424b..857d313 100644--- a/hyperextract/templates/zh/tcm/formula_composition.py+++ b/hyperextract/templates/zh/tcm/formula_composition.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoHypergraphclass HerbNode(BaseModel):"""药物节点"""+name: str = Field(description="药物名称")role: str = Field(description="药物角色:君药、臣药、佐药、使药")dosage: str = Field(description="药物剂量", default="")@@ -20,6 +21,7 @@ class HerbNode(BaseModel):class FormulaHyperedge(BaseModel):"""方剂超边"""+formulaName: str = Field(description="方剂名称")junHerbs: List[str] = Field(description="君药列表")chenHerbs: List[str] = Field(description="臣药列表")@@ -49,6 +51,12 @@ _PROMPT = """## 角色与任务3. 提取方剂功能和主治证候4. 提取煎服法+### 术语标准化指导+- **药物名称标准化**:同一药物的不同名称需统一使用规范正名(如"国老"→"甘草","仙灵脾"→"淫羊藿")+- **角色术语统一**:君、臣、佐、使的不同表述需统一为"君药"、"臣药"、"佐药"、"使药"+- **剂量单位保留**:古代剂量单位(两、钱、分、匕、枚等)可保留原文,无需转换+- **同义词处理**:同一概念的不同表述(如"主治"与"主疗","功效"与"功用")应统一提取+### 约束条件- 每条边必须包含方剂名称和至少一种角色的药物列表- 不要创建未在文本中提及的实体或关系@@ -95,10 +103,10 @@ _EDGE_PROMPT = """## 角色与任务class FormulaComposition(AutoHypergraph[HerbNode, FormulaHyperedge]):"""适用文档: 方剂规范、伤寒论、金匮要略、方剂学教材等-+功能介绍:将方剂建模为 {君药, 臣药, 佐药, 使药} 的层级化超边结构,适用于方剂结构解析、组方规律研究。-+Example:>>> template = FormulaComposition(llm_client=llm, embedder=embedder)>>> template.feed_text("桂枝汤:桂枝三两,芍药三两,甘草二两,生姜三两,大枣十二枚...")@@ -117,7 +125,7 @@ class FormulaComposition(AutoHypergraph[HerbNode, FormulaHyperedge]):):"""初始化君臣佐使结构图模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -132,7 +140,14 @@ class FormulaComposition(AutoHypergraph[HerbNode, FormulaHyperedge]):edge_schema=FormulaHyperedge,node_key_extractor=lambda x: x.name,edge_key_extractor=lambda x: x.formulaName,- nodes_in_edge_extractor=lambda x: (x.junHerbs, x.chenHerbs, x.zuoHerbs, x.shiHerbs),+ nodes_in_edge_extractor=lambda x: set(+ [+ *x.junHerbs,+ *x.chenHerbs,+ *x.zuoHerbs,+ *x.shiHerbs,+ ]+ ),llm_client=llm_client,embedder=embedder,extraction_mode=extraction_mode,@@ -146,28 +161,33 @@ class FormulaComposition(AutoHypergraph[HerbNode, FormulaHyperedge]):def show(self,- *,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ *,+ 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,):"""展示君臣佐使结构图。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""+def node_label_extractor(node: HerbNode) -> str:return f"{node.name} ({node.role})"-+def edge_label_extractor(edge: FormulaHyperedge) -> str:return edge.formulaName-+super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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/tcm/function_indication_map.py b/hyperextract/templates/zh/tcm/function_indication_map.pyindex 140cd81..e5fe75e 100644--- a/hyperextract/templates/zh/tcm/function_indication_map.py+++ b/hyperextract/templates/zh/tcm/function_indication_map.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoGraphclass GeneralEntity(BaseModel):"""通用实体节点"""+name: str = Field(description="实体名称")category: str = Field(description="实体类型:方剂、功能、主治证候")description: str = Field(description="简要描述", default="")@@ -19,6 +20,7 @@ class GeneralEntity(BaseModel):class GeneralRelation(BaseModel):"""通用关系边"""+source: str = Field(description="源实体")target: str = Field(description="目标实体")relationType: str = Field(description="关系类型:具有功能、主治")@@ -38,6 +40,10 @@ _PROMPT = """## 角色与任务2. 为每个实体指定类型:方剂、功能、主治证候3. 保持实体名称与原文一致4. 为每个实体添加简要描述+5. **关键原子化要求**:如果文本中出现逗号、顿号、及、与、和等分隔的多个实体,必须将每个实体单独提取为一个独立节点,不要合并在一起。例如:+ - 原文"清热解毒、凉血止血"→拆分为"清热解毒"和"凉血止血"两个节点+ - 原文"头痛、发热、咳嗽"→拆分为"头痛"、"发热"、"咳嗽"三个节点+ - 原文"太阳病及阳明病"→拆分为"太阳病"和"阳明病"两个节点### 关系提取规则1. 提取方剂与功能之间的关系(具有功能)@@ -63,6 +69,10 @@ _NODE_PROMPT = """## 角色与任务2. 为每个实体指定类型:方剂、功能、主治证候3. 保持实体名称与原文一致4. 为每个实体添加简要描述+5. **关键原子化要求**:如果文本中出现逗号、顿号、及、与、和等分隔的多个实体,必须将每个实体单独提取为一个独立节点,不要合并在一起。例如:+ - 原文"清热解毒、凉血止血"→拆分为"清热解毒"和"凉血止血"两个节点+ - 原文"头痛、发热、咳嗽"→拆分为"头痛"、"发热"、"咳嗽"三个节点+ - 原文"太阳病及阳明病"→拆分为"太阳病"和"阳明病"两个节点### 源文本:"""@@ -90,10 +100,10 @@ _EDGE_PROMPT = """## 角色与任务class FunctionIndicationMap(AutoGraph[GeneralEntity, GeneralRelation]):"""适用文档: 方剂规范、伤寒论、金匮要略、方剂学教材等-+功能介绍:关联 方剂 -> 功能(如清热解毒) -> 主治证候,适用于方剂推荐系统。-+Example:>>> template = FunctionIndicationMap(llm_client=llm, embedder=embedder)>>> template.feed_text("桂枝汤:解肌发表,调和营卫。主治太阳中风...")@@ -104,7 +114,7 @@ class FunctionIndicationMap(AutoGraph[GeneralEntity, GeneralRelation]):self,llm_client: BaseChatModel,embedder: Embeddings,- *,+ *,extraction_mode: str = "two_stage",max_workers: int = 10,verbose: bool = False,@@ -112,7 +122,7 @@ class FunctionIndicationMap(AutoGraph[GeneralEntity, GeneralRelation]):):"""初始化主治功效映射模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -141,28 +151,33 @@ class FunctionIndicationMap(AutoGraph[GeneralEntity, GeneralRelation]):def show(self,- *,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ *,+ 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,):"""展示主治功效映射。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 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_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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/tcm/herb_property_model.py b/hyperextract/templates/zh/tcm/herb_property_model.pyindex 09a0253..77f5433 100644--- a/hyperextract/templates/zh/tcm/herb_property_model.py+++ b/hyperextract/templates/zh/tcm/herb_property_model.py@@ -28,9 +28,6 @@ class HerbProperty(BaseModel):_PROMPT = """## 角色与任务你是一位专业的中药学家,请从文本中提取单味药的性味归经、毒性及推荐剂量等信息。-## 核心概念定义-- **对象 (Object)**:本模板中的"对象"指单一中药药物,包含正名、别名、四气、五味、归经、毒性、剂量、采集、炮制、功效主治、配伍禁忌等多个字段的结构化信息。-## 提取规则1. 识别文本的核心药物主体2. 提取药物的正名和所有别名、俗称@@ -44,6 +41,13 @@ _PROMPT = """## 角色与任务10. 提取药物的功效主治11. 提取药物的配伍禁忌+### 文言文特殊处理指导+- **句式解析**:文言文常采用省略主语、并列结构、连动句式,需先理解句式结构再提取信息+- **术语对应**:文言术语与现代术语需正确对应(如"主"指"主治","疗"指"治疗","久服"指"长期服用")+- **连写拆分**:文言中常连写多个属性(如"味甘微寒"→拆分为"味甘"、"微寒"),需分别归到对应字段+- **省略补充**:文言常省略主语或属性类别,需根据上下文补充理解(如"无毒"默认指药物毒性)+- **古今剂量转换**:文言中古代剂量单位(如两、钱、匕)可保留原文,也可根据常识标注现代对应剂量+### 约束条件- 只提取文本中明确提及的信息,不添加额外内容- 保持客观准确,符合中药学专业术语规范diff --git a/hyperextract/templates/zh/tcm/meridian_flow_graph.py b/hyperextract/templates/zh/tcm/meridian_flow_graph.pyindex 4d310b5..5c50147 100644--- a/hyperextract/templates/zh/tcm/meridian_flow_graph.py+++ b/hyperextract/templates/zh/tcm/meridian_flow_graph.py@@ -12,6 +12,7 @@ from hyperextract.types import AutoGraphclass MeridianNode(BaseModel):"""经脉节点"""+name: str = Field(description="经脉名称:如手太阴肺经、手阳明大肠经等")category: str = Field(description="经脉类别:阴经、阳经")associatedOrgan: str = Field(description="关联脏腑", default="")@@ -20,6 +21,7 @@ class MeridianNode(BaseModel):class MeridianFlowRelation(BaseModel):"""经络流注关系边"""+source: str = Field(description="源经脉名称")target: str = Field(description="目标经脉名称")relationType: str = Field(description="关系类型:流注")@@ -52,6 +54,11 @@ _PROMPT = """## 角色与任务- 不要创建未在文本中提及的实体或关系- 保持客观准确,符合经络学专业术语规范+### 术语标准化指导+- **经脉名称统一**:确保使用标准经脉名称(如"手太阴肺经"而非简称)+- **流注次序确认**:十二经脉流注有固定次序,可参考标准次序辅助确认+- **循行路线保留**:文言中循行路线描述保持原文,无需改写+### 源文本:"""@@ -94,10 +101,10 @@ _EDGE_PROMPT = """## 角色与任务class MeridianFlowGraph(AutoGraph[MeridianNode, MeridianFlowRelation]):"""适用文档: 黄帝内经、经络学教材、针灸学教材等-+功能介绍:提取十二经脉的循行路线及经气流注次序,适用于经络理论教学。-+Example:>>> template = MeridianFlowGraph(llm_client=llm, embedder=embedder)>>> template.feed_text("手太阴肺经起于中焦,下络大肠...")@@ -108,7 +115,7 @@ class MeridianFlowGraph(AutoGraph[MeridianNode, MeridianFlowRelation]):self,llm_client: BaseChatModel,embedder: Embeddings,- *,+ *,extraction_mode: str = "two_stage",max_workers: int = 10,verbose: bool = False,@@ -116,7 +123,7 @@ class MeridianFlowGraph(AutoGraph[MeridianNode, MeridianFlowRelation]):):"""初始化经络流注图模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -145,28 +152,33 @@ class MeridianFlowGraph(AutoGraph[MeridianNode, MeridianFlowRelation]):def show(self,- *,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ *,+ 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,):"""展示经络流注图。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""+def node_label_extractor(node: MeridianNode) -> str:return f"{node.name} ({node.category})"-+def edge_label_extractor(edge: MeridianFlowRelation) -> str:return f"流注 #{edge.flowOrder}"-+super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,+ 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/tcm/prescription_modification.py b/hyperextract/templates/zh/tcm/prescription_modification.pyindex 3167f7e..55ce08d 100644--- a/hyperextract/templates/zh/tcm/prescription_modification.py+++ b/hyperextract/templates/zh/tcm/prescription_modification.py@@ -83,6 +83,12 @@ _PROMPT = """## 角色与任务6. 提取加减的原因和剂量信息7. 提取基础方剂名称+### 术语标准化指导+- **药物名称标准化**:同一药物的不同名称需统一使用规范正名+- **加减术语统一**:"加"、"添"、"增"统一为"加";"减"、"去"、"除"统一为"减";"易"、"换"统一为"替换"+- **症状表述规范化**:文言症状表述需转换为规范中医术语+- **方剂名称保留**:基础方剂名称保持原文表述+### 源文本:"""@@ -146,15 +152,19 @@ class PrescriptionModification(AutoGraph[PrescriptionEntity, ModificationRelatiodef show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示处方加减逻辑图。Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""def node_label_extractor(node: PrescriptionEntity) -> str:return f"{node.name} ({node.category})"@@ -165,6 +175,8 @@ class PrescriptionModification(AutoGraph[PrescriptionEntity, ModificationRelatiosuper().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,+ 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/tcm/processing_method.py b/hyperextract/templates/zh/tcm/processing_method.pyindex 18edd76..aad3998 100644--- a/hyperextract/templates/zh/tcm/processing_method.py+++ b/hyperextract/templates/zh/tcm/processing_method.py@@ -36,6 +36,12 @@ _PROMPT = """## 角色与任务- 只提取文本中明确提及的信息,不添加额外内容- 保持客观准确,符合中药炮制专业术语规范+### 文言文特殊处理指导+- **炮制术语理解**:文言炮制术语需准确理解(如"炙"、"炒"、"煅"、"蒸"等)+- **工艺流程解析**:文言炮制工艺流程常采用简洁表述,需完整理解其步骤+- **药效变化描述**:文言中对药效变化的描述需准确提取(如"增强"、"缓和"、"改变"等)+- **古代计量单位**:保留古代剂量单位和工艺描述,无需转换+### 源文本:"""diff --git a/hyperextract/templates/zh/tcm/pulse_tongue_record.py b/hyperextract/templates/zh/tcm/pulse_tongue_record.pyindex d23b231..1fccae0 100644--- a/hyperextract/templates/zh/tcm/pulse_tongue_record.py+++ b/hyperextract/templates/zh/tcm/pulse_tongue_record.py@@ -32,6 +32,12 @@ _PROMPT = """## 角色与任务5. 提取特征的临床意义(如果有)6. 提取特征的来源信息(如果有)+### 文言文特殊处理指导+- **舌象描述解析**:文言舌象常采用连写表述(如"舌淡红苔薄白"→拆分为舌质淡红、舌苔薄白)+- **脉象术语理解**:文言脉象术语需准确识别(如"浮紧脉"→浮脉、紧脉)+- **复合特征拆分**:文言中常将多个特征合并描述,需分别提取到对应字段+- **临床意义关联**:文言中舌脉特征与临床意义常关联表述,需准确提取对应关系+### 源文本:"""diff --git a/hyperextract/templates/zh/tcm/syndrome_reasoning_graph.py b/hyperextract/templates/zh/tcm/syndrome_reasoning_graph.pyindex 9f29ccb..ed04e55 100644--- a/hyperextract/templates/zh/tcm/syndrome_reasoning_graph.py+++ b/hyperextract/templates/zh/tcm/syndrome_reasoning_graph.py@@ -9,19 +9,26 @@ from langchain_core.embeddings import Embeddingsfrom pydantic import BaseModel, Fieldfrom hyperextract.types import AutoHypergraph+class TCMEntity(BaseModel):"""中医实体节点"""+name: str = Field(description="实体名称,如症状、证型、治则、药物等")category: str = Field(description="实体类型:症状、证型、治则、药物")description: str = Field(description="简要描述", default="")+class SyndromeReasoningEdge(BaseModel):"""辨证论治逻辑边"""- nodes: List[str] = Field(description="参与推理的节点列表,按推理顺序排列:[症状1, 症状2, ..., 证型, 治则, 药物1, 药物2, ...]")++ nodes: List[str] = Field(+ description="参与推理的节点列表,按推理顺序排列:[症状1, 症状2, ..., 证型, 治则, 药物1, 药物2, ...]"+ )reasoningType: str = Field(description="推理类型:辨证论治、随证加减")reasoningProcess: str = Field(description="推理过程描述", default="")source: str = Field(description="推理来源,如医案名称、章节等", default="")+_NODE_PROMPT = """## 角色与任务你是一位专业的中医辨证论治专家,请从文本中提取所有关键实体作为节点。@@ -78,6 +85,12 @@ _PROMPT = """## 角色与任务4. reasoningType 应为"辨证论治"或"随证加减"5. reasoningProcess 应详细描述推理过程+### 文言文特殊处理指导+- **症状表述解析**:文言症状常采用简洁表述,需完整理解其含义(如"恶寒发热"指怕冷和发热两个症状)+- **证型术语理解**:文言中证型表述需准确识别(如"太阳中风证"、"阳明腑实证")+- **省略句式处理**:文言常省略主语或连接词,需根据上下文补充理解+- **医案结构识别**:医案通常有"症状→辨证→治法→方药"的结构,需按此顺序提取+### 源文本:"""@@ -85,14 +98,15 @@ _PROMPT = """## 角色与任务# 3. 模板类# ==============================================================================+class SyndromeReasoningGraph(AutoHypergraph[TCMEntity, SyndromeReasoningEdge]):"""适用文档: 中医医案、名医临床实录-+功能介绍:从中医医案中提取辨证论治的完整推理链条,建模 {症状群} -> 证型 -> 治则 -> {处方} 的逻辑关系,支持复杂的多实体关联关系。-+Example:>>> template = SyndromeReasoningGraph(llm_client=llm, embedder=embedder)>>> template.feed_text("...")@@ -111,7 +125,7 @@ class SyndromeReasoningGraph(AutoHypergraph[TCMEntity, SyndromeReasoningEdge]):):"""初始化辨证论治逻辑图模板。-+Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索@@ -141,25 +155,32 @@ class SyndromeReasoningGraph(AutoHypergraph[TCMEntity, SyndromeReasoningEdge]):def show(self,*,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,+ 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,):"""展示辨证论治逻辑图。-+Args:- top_k_for_search: 语义检索返回的节点/边数量,默认为 3- top_k_for_chat: 问答使用的节点/边数量,默认为 3+ top_k_nodes_for_search: 语义检索返回的节点数量,默认为 3+ top_k_edges_for_search: 语义检索返回的边数量,默认为 3+ top_k_nodes_for_chat: 问答使用的节点数量,默认为 3+ top_k_edges_for_chat: 问答使用的边数量,默认为 3"""+def node_label_extractor(node: TCMEntity) -> str:return f"{node.name} ({node.category})"-+def edge_label_extractor(edge: SyndromeReasoningEdge) -> str:return edge.reasoningType-+super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,+ 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/tests/fixtures/test_samples/en/tcm/prescription_formulary_sample.md b/tests/fixtures/test_samples/en/tcm/prescription_formulary_sample.mdindex 2c1ae34..c293411 100644--- a/tests/fixtures/test_samples/en/tcm/prescription_formulary_sample.md+++ b/tests/fixtures/test_samples/en/tcm/prescription_formulary_sample.md@@ -1,52 +1,97 @@-# Prescription Formulary Sample+# Standard Formula Samples (Revised: No Overlap in Sovereign-Minister-Assistant-Envoy)-## Guizhi Decoction+## Guizhi Decoction (Cinnamon Twig Decoction)-### Composition-Cinnamon Twig 3 liang (peeled), Peony 3 liang, Licorice 2 liang (prepared), Ginger 3 liang (sliced), Jujube 12 pieces (broken)+### Ingredients+Guizhi (Cinnamon Twig) 3 liang (peeled), Shaoyao (Peony Root) 3 liang, Gancao (Licorice) 2 liang (roasted),+Shengjiang (Fresh Ginger) 3 liang (sliced), Dazao (Jujube) 12 pieces (pitted).-### Decoction Method-Take the five ingredients, cut three of them, add 7 sheng of water, simmer over low heat to obtain 3 sheng, remove the dregs, adjust to suitable temperature, and take 1 sheng. Soon after taking, drink about 1 sheng of hot rice gruel to aid the medicinal effect, cover with a blanket for about one hour, and it is better to have a slight sweat all over the body; do not let the sweat flow profusely, otherwise the disease will not be cured. If symptoms are relieved after one dose, stop taking the remaining medicine; if not sweating, take another dose according to the previous method; if still not sweating, shorten the interval between doses, taking three doses within half a day. For severe cases, take the medicine day and night, observing the condition continuously; if symptoms persist after one dose, prepare another dose; if no sweating occurs, take up to two or three doses.+### Decoction and Administration+Take the five ingredients, coarsely crush three of them.+Add 7 sheng of water, simmer gently over low heat until 3 sheng remains.+Strain out the dregs. Adjust to warm temperature and take 1 sheng.++Shortly after taking, drink about 1 sheng of warm thin congee to assist the medicinal effect.+Cover warmly for about one hour, until slight sweating appears all over the body—this is optimal.+Do not allow profuse sweating, otherwise the illness will not be cured.++If sweating occurs and the illness resolves after one dose, stop the remaining doses;+there is no need to finish the entire preparation.+If no sweating occurs, take another dose following the same method.+If still no sweating, shorten the interval between doses;+finish three doses within about half a day.++For severe cases, administer day and night, observing around the clock.+If symptoms remain after one full preparation, prepare another.+If sweating still does not occur, administer up to two or three preparations.### Functions and Indications-Relieves the muscles to expel exterior pathogens, harmonizes nutritive and defensive qi. Indicated for Taiyang wind stroke, with floating yang and weak yin; floating yang causes spontaneous heat, weak yin causes spontaneous sweating. Symptoms include slight aversion to cold, mild aversion to wind, gentle fever, nasal congestion, and retching.+Relieves the exterior and promotes muscle relaxation, regulates Ying and Wei.+Indicated for Taiyang wind-strike: Yang floating and Yin weak.+Yang floating leads to spontaneous fever; Yin weakness leads to spontaneous sweating.+Chills, aversion to wind, mild fever, nasal congestion, and nausea.-### Monarch-Minister-Assistant-Guide Analysis-- Monarch herb: Cinnamon Twig, acrid and warm, relieves the muscles to expel exterior pathogens, warms and unblocks meridians-- Minister herb: Peony, sour, bitter, and slightly cold, nourishes yin and consolidates nutritive qi-- Assistant herbs: Ginger, acrid and warm, assists Cinnamon Twig in expelling exterior pathogens; Jujube, sweet and warm, supplements qi and nourishes the middle-- Guide herb: Licorice, sweet and warm, harmonizes all herbs+### Sovereign-Minister-Assistant-Envoy Analysis+- Sovereign: Guizhi (Cinnamon Twig), pungent-warm, relieves the exterior, warms and unblocks the channels.+- Minister: Shaoyao (Peony Root), sour-bitter slightly cold, nourishes Yin and astringes Ying.+- Assistant: Shengjiang (Fresh Ginger), pungent-warm, assists Guizhi in releasing the exterior;+ Dazao (Jujube), sweet-warm, tonifies Qi and fortifies the spleen.+- Envoy: Gancao (Licorice), sweet-warm, harmonizes all medicinals.-## Mahuang Decoction+----### Composition-Ephedra 3 liang (de-jointed), Cinnamon Twig 2 liang (peeled), Licorice 1 liang (prepared), Apricot Kernel 70 pieces (peeled and tipped)+## Mahuang Decoction (Ephedra Decoction)-### Decoction Method-Take the four ingredients, add 9 sheng of water, first boil Ephedra to reduce by 2 sheng, remove the froth, add the other ingredients, boil to obtain 2.5 sheng, remove the dregs, warm and take 8 he, cover to induce slight sweating, no need to drink porridge, follow the same aftercare as Guizhi Decoction.+### Ingredients+Mahuang (Ephedra) 3 liang (nodes removed), Guizhi (Cinnamon Twig) 2 liang (peeled),+Gancao (Licorice) 1 liang (roasted), Xingren (Apricot Kernel) 70 pieces (skin and tip removed).++### Decoction and Administration+Take the four ingredients. Add 9 sheng of water.+First decoct Mahuang until 2 sheng evaporates; remove the froth.+Add the other medicinals and decoct until 2.5 sheng remains.+Strain out the dregs. Take 8 he warm, cover to induce slight sweating.+No need for warm congee. For the rest, follow the same instructions as Guizhi Decoction.### Functions and Indications-Induces sweating to expel exterior pathogens, ventilates the lungs to relieve asthma. Indicated for Taiyang disease with headache, fever, body pain, low back pain, joint pain, aversion to wind, and absence of sweating with asthma.+Induces sweating to release the exterior, diffuses the lung and relieves asthma.+Indicated for Taiyang disease: headache, fever, body pain, lumbar pain, joint pain,+aversion to wind, absence of sweating, and wheezing.++### Sovereign-Minister-Assistant-Envoy Analysis+- Sovereign: Mahuang (Ephedra), pungent-warm, induces sweating to release the exterior, diffuses the lung and relieves asthma.+- Minister: Guizhi (Cinnamon Twig), pungent-warm, relieves the exterior, warms and unblocks the channels.+- Assistant: Xingren (Apricot Kernel), bitter-warm, descends lung Qi, relieves asthma and cough.+- Envoy: Gancao (Licorice), sweet-warm, harmonizes all medicinals.-### Monarch-Minister-Assistant-Guide Analysis-- Monarch herb: Ephedra, acrid and warm, induces sweating to expel exterior pathogens, ventilates the lungs to relieve asthma-- Minister herb: Cinnamon Twig, acrid and warm, relieves the muscles to expel exterior pathogens, warms and unblocks meridians-- Assistant herb: Apricot Kernel, bitter and warm, descends and benefits lung qi, relieves asthma and stops cough-- Guide herb: Licorice, sweet and warm, harmonizes all herbs+----## Xiaochaihu Decoction+## Xiaochaihu Decoction (Minor Bupleurum Decoction)-### Composition-Bupleurum 8 liang, Scutellaria 3 liang, Ginseng 3 liang, Licorice 3 liang (prepared), Ginger 3 liang (sliced), Jujube 12 pieces (broken), Pinellia 0.5 sheng (washed)+### Ingredients+Chaihu (Bupleurum) 8 liang, Huangqin (Scutellaria) 3 liang,+Renshen (Ginseng) 3 liang, Gancao (Licorice) 3 liang (roasted),+Shengjiang (Fresh Ginger) 3 liang (sliced), Dazao (Jujube) 12 pieces (pitted),+Banxia (Pinellia) 0.5 sheng (washed).-### Decoction Method-Take the seven ingredients, add 12 sheng of water, boil to obtain 6 sheng, remove the dregs, simmer again to obtain 3 sheng, warm and take 1 sheng, three times a day.+### Decoction and Administration+Take the seven ingredients. Add 12 sheng of water, decoct until 6 sheng remains.+Strain out the dregs, then decoct again until 3 sheng remains.+Take 1 sheng warm, three times a day.### Functions and Indications-Harmonizes Shaoyang. Indicated for cold damage or wind stroke of five to six days, with alternating chills and fever, fullness and discomfort in the chest and hypochondria, reluctance to talk and eat, vexation and propensity to vomit, or chest vexation without vomiting, or thirst, or abdominal pain, or hypochondriac fullness and hardness, or palpitations in the epigastrium and urinary difficulty, or absence of thirst with slight fever, or cough.+Harmonizes Shaoyang.+Indicated for cold damage (Shanghan) for five or six days with wind-strike:+alternating chills and fever, fullness in the chest and hypochondria,+depressed appetite, vexation and frequent vomiting.+Other possible presentations:+chest vexation without vomiting, thirst, abdominal pain,+hardness below the hypochondria, palpitations, dysuria,+absence of thirst with mild fever, or cough.-### Monarch-Minister-Assistant-Guide Analysis-- Monarch herb: Bupleurum, bitter and neutral, harmonizes Shaoyang, soothes the liver and resolves stagnation-- Minister herb: Scutellaria, bitter and cold, clears heat in Shaoyang-- Assistant herbs: Ginseng, Jujube, and Licorice, supplement qi and strengthen the spleen; Pinellia and Ginger, harmonize the stomach and descend rebellious qi-- Guide herb: Licorice, harmonizes all herbs+### Sovereign-Minister-Assistant-Envoy Analysis+- Sovereign: Chaihu (Bupleurum), bitter-neutral, harmonizes Shaoyang, courses the liver and gallbladder.+- Minister: Huangqin (Scutellaria), bitter-cold, clears and drains Shaoyang heat.+- Assistant: Renshen (Ginseng) and Dazao (Jujube), tonify Qi and fortify the spleen;+ Banxia (Pinellia) and Shengjiang (Fresh Ginger), harmonize the stomach and direct rebellious Qi downward.+- Envoy: Gancao (Licorice), harmonizes all medicinals.\ No newline at end of filediff --git a/tests/fixtures/test_samples/zh/tcm/prescription_formulary_sample.md b/tests/fixtures/test_samples/zh/tcm/prescription_formulary_sample.mdindex c67c107..72a9aaf 100644--- a/tests/fixtures/test_samples/zh/tcm/prescription_formulary_sample.md+++ b/tests/fixtures/test_samples/zh/tcm/prescription_formulary_sample.md@@ -26,7 +26,7 @@上四味,以水九升,先煮麻黄,减二升,去上沫,内诸药,煮取二升半,去滓,温服八合,覆取微似汗,不须啜粥,余如桂枝法将息。### 功能主治-发汗解表,宣肺平喘。主治太阳病,头痛、发热、身疼、腰痛、骨节疼痛、恶风、无汗而喘者。+发汗解表,宣肺平喘。主治太阳病,头痛、发热、身疼、腰痛、骨节疼痛,恶风、无汗而喘者。### 君臣佐使分析- 君药:麻黄,辛温,发汗解表,宣肺平喘@@ -48,5 +48,5 @@### 君臣佐使分析- 君药:柴胡,苦平,和解少阳,疏泄肝胆- 臣药:黄芩,苦寒,清泄少阳之热-- 佐药:人参、大枣、甘草,益气健脾;半夏、生姜,和胃降逆-- 使药:甘草,调和诸药+- 佐药:人参、大枣,益气健脾;半夏、生姜,和胃降逆+- 使药:甘草,调和诸药\ No newline at end of file