Skip to content

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

Add environmental and ecological templates for pollutant impacts and species interactions

yifanfeng9731cd725db111
diff --git a/hyperextract/templates/INSTRUCTION.md b/hyperextract/templates/INSTRUCTION.md
index 950b9a4..50efbc2 100644
--- a/hyperextract/templates/INSTRUCTION.md
+++ b/hyperextract/templates/INSTRUCTION.md
@@ -34,11 +34,30 @@ Before designing a Schema, ask yourself:
## 2. Implementation Rules
### A. Prompt Definition
-* **Mandatory Constant**: Define `_TEMPLATE_PROMPT` (a multi-line string) outside the class.
+* **Mandatory Constant**: Define `_PROMPT` (a multi-line string) outside the class.
* **Content**: Clearly define the expert persona and extraction logic. Mention specific formatting rules if necessary.
+* **Graph/Hypergraph Two-Stage Support**: If your template inherits from `AutoGraph`, `AutoHypergraph`, `AutoTemporalGraph`, `AutoSpatialGraph`, or `AutoSpatioTemporalGraph`, you **MUST define three separate prompts** to support both extraction modes:
+ 1. `_PROMPT`: For "one_stage" (extract Nodes & Edges simultaneously, faster).
+ 2. `_NODE_PROMPT`: For "two_stage" step 1 (extract Nodes only, foundations).
+ 3. `_EDGE_PROMPT`: For "two_stage" step 2 (extract Edges/Hyperedges given existing Nodes, more precise).
+
+ Pass these to `super().__init__` as:
+ ```python
+ super().__init__(
+ ...,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ ...
+ )
+ ```
### B. Class Structure
* **Schemas**: All Pydantic fields MUST include a `description` attribute. This is vital for the LLM to understand the target.
+* **Documentation**:
+ * **Class Docstring**: Must include a high-level description and a usage **Example** showing how to instantiate and use the template.
+ * **Method Docstrings**: The `__init__` and `show` methods MUST include standard Google-style docstrings with detailed `Args` descriptions for every parameter.
+* **Parameter Accuracy**: Verify that every argument in your `__init__` exists in the base class. Common mistake: `extraction_mode` exists in `AutoGraph` but NOT in `AutoSet`.
* **Initialization**: Explicitly list parameters (`llm_client`, `embedder`, etc.) and pass the prompt to `super().__init__(..., prompt=_TEMPLATE_PROMPT, ...)`.
* **Visualization (`show`)**: YOU MUST override the `show` method.
* **Parameter Constraint**: **DO NOT** include `label_extractor` parameters (e.g., `node_label_extractor`) in the template's `show` method signature.
@@ -61,7 +80,7 @@ class ItemSchema(BaseModel):
...
# 2. Define Prompt
-_TEMPLATE_PROMPT = """
+_PROMPT = """
You are an expert in [Domain]. Your task is to extract [Structure] from text...
"""
@@ -80,7 +99,7 @@ class MyTemplate(AutoType[ItemSchema]): # Replace with actual base class (AutoLi
item_schema=ItemSchema,
llm_client=llm_client,
embedder=embedder,
- prompt=_TEMPLATE_PROMPT,
+ prompt=_PROMPT,
chunk_size=chunk_size,
**kwargs
)
diff --git a/hyperextract/templates/INSTRUCTION_ZH.md b/hyperextract/templates/INSTRUCTION_ZH.md
index 45c445b..3a810a1 100644
--- a/hyperextract/templates/INSTRUCTION_ZH.md
+++ b/hyperextract/templates/INSTRUCTION_ZH.md
@@ -34,11 +34,30 @@
## 2. 实现规范 (Implementation Rules)
### A. Prompt 定义
-* **强制常数**:必须在类外部定义 `_TEMPLATE_PROMPT`(多行字符串)。
+* **强制常数**:必须在类外部定义 `_PROMPT`(多行字符串)。
* **内容要求**:明确定义专家角色、提取逻辑。如果某些字段有特定的提取格式要求,请在 Prompt 中强调。
+* **图谱/超图双阶段支持**:如果模板继承自 `AutoGraph`、`AutoHypergraph`、`AutoTemporalGraph`、`AutoSpatialGraph` 或 `AutoSpatioTemporalGraph`,你**必须定义三个独立的 Prompt** 以支持所有提取模式:
+ 1. `_PROMPT`: 用于 "one_stage"(同时提取节点和边,速度快)。
+ 2. `_NODE_PROMPT`: 用于 "two_stage" 第一步(仅提取节点,打基础)。
+ 3. `_EDGE_PROMPT`: 用于 "two_stage" 第二步(基于已有节点提取边/超边,更精准)。
+
+ 在 `super().__init__` 中分别传递:
+ ```python
+ super().__init__(
+ ...,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ ...
+ )
+ ```
### B. 类结构
* **Schema**:所有 Pydantic 字段必须包含 `description` 属性,这是 LLM 理解抽取目标的关键。
+* **文档注释 (Documentation)**:
+ * **类文档字符串 (Class Docstring)**:必须包含高层功能描述,以及一个展示如何初始化和使用的 **示例 (Example)**。
+ * **方法文档字符串 (Method Docstring)**:`__init__` 和 `show` 方法必须包含标准的 Google 风格文档字符串,详细说明每个参数 (`Args`)。
+* **参数准确性 (Parameter Accuracy)**:确保 `__init__` 中的每一个参数都在基类中存在。常见错误:`extraction_mode` 仅存在于 `AutoGraph` 系列中,**不存在**于 `AutoSet` 或 `AutoList` 中。
* **初始化 (`__init__`)**:显式列参数(`llm_client`, `embedder` 等),并正确调用 `super().__init__(..., prompt=_TEMPLATE_PROMPT, ...)`。
* **可视化 (`show`)**:必须覆盖 `show` 方法。
* **参数约束**:**禁止**在模板类的 `show` 方法签名中包含 `label_extractor` 参数。
@@ -61,7 +80,7 @@ class ItemSchema(BaseModel):
...
# 2. 定义 Prompt
-_TEMPLATE_PROMPT = """
+_PROMPT = """
你是一位[领域]专家。你的任务是从文本中提取[结构化知识]...
"""
@@ -80,7 +99,7 @@ class MyTemplate(AutoType[ItemSchema]): # 替换为 AutoList, AutoSet 等
item_schema=ItemSchema,
llm_client=llm_client,
embedder=embedder,
- prompt=_TEMPLATE_PROMPT,
+ prompt=_PROMPT,
chunk_size=chunk_size,
**kwargs
)
diff --git a/hyperextract/templates/en/agriculture/crop_cycle.py b/hyperextract/templates/en/agriculture/crop_cycle.py
index 97ab79c..93780bc 100644
--- a/hyperextract/templates/en/agriculture/crop_cycle.py
+++ b/hyperextract/templates/en/agriculture/crop_cycle.py
@@ -38,7 +38,7 @@ class AgriRelation(BaseModel):
# 2. Prompts
# ==============================================================================
-CROP_CYCLE_PROMPT = (
+_PROMPT = (
"You are an expert agronomist. Extract a crop growth and management graph from the text.\n\n"
"Guidelines:\n"
"- Identify the crop and its specific growth stages (e.g., Sowing, Flowering).\n"
@@ -46,7 +46,7 @@ CROP_CYCLE_PROMPT = (
"- Note any threats like pests or diseases and their impact on the crop."
)
-CROP_CYCLE_NODE_PROMPT = (
+_NODE_PROMPT = (
"You are an expert agronomist. Your task is to identify and extract all key agricultural entities (Nodes) from the text.\n\n"
"Extraction Rules:\n"
"- Identify crop types, specific growth stages, environmental factors (e.g., pH, temperature), and farming tasks.\n"
@@ -55,7 +55,7 @@ CROP_CYCLE_NODE_PROMPT = (
"- DO NOT identify sequences or dependencies between these entities at this stage."
)
-CROP_CYCLE_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"You are an expert agronomist. Given the list of agricultural entities, map the logical links and cycles (Edges).\n\n"
"Extraction Rules:\n"
"- Establish sequential links between growth stages.\n"
@@ -126,9 +126,9 @@ class CropCycleGraph(AutoGraph[AgriEntity, AgriRelation]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=CROP_CYCLE_PROMPT,
- prompt_for_node_extraction=CROP_CYCLE_NODE_PROMPT,
- prompt_for_edge_extraction=CROP_CYCLE_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs,
)
diff --git a/hyperextract/templates/en/agriculture/livestock.py b/hyperextract/templates/en/agriculture/livestock.py
index f4285df..5ba0d14 100644
--- a/hyperextract/templates/en/agriculture/livestock.py
+++ b/hyperextract/templates/en/agriculture/livestock.py
@@ -38,7 +38,7 @@ class BreedingRelation(BaseModel):
# 2. Prompts
# ==============================================================================
-LIVESTOCK_GRAPH_PROMPT = (
+_PROMPT = (
"You are a livestock specialist and geneticist. Extract a breeding and health management graph.\n\n"
"Guidelines:\n"
"- Identify individual animals and their breeds.\n"
@@ -46,12 +46,12 @@ LIVESTOCK_GRAPH_PROMPT = (
"- Link animals to their health status, vaccinations, and nutrition records."
)
-LIVESTOCK_NODE_PROMPT = (
+_NODE_PROMPT = (
"Extract livestock entities: identify specific animals (by ID or name), breeds, health conditions, "
"vaccines, and specific feed types. Provide relevant traits or metrics for each."
)
-LIVESTOCK_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"Link livestock entities logically. Map family trees (parental links), breeding history, "
"and medical/nutritional events. Ensure relation types like 'bred with' or 'fed with' are used accurately."
)
@@ -117,9 +117,9 @@ class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=LIVESTOCK_GRAPH_PROMPT,
- prompt_for_node_extraction=LIVESTOCK_NODE_PROMPT,
- prompt_for_edge_extraction=LIVESTOCK_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs,
)
diff --git a/hyperextract/templates/en/agriculture/pest_control.py b/hyperextract/templates/en/agriculture/pest_control.py
index 0aea89b..fbf54b2 100644
--- a/hyperextract/templates/en/agriculture/pest_control.py
+++ b/hyperextract/templates/en/agriculture/pest_control.py
@@ -38,7 +38,7 @@ class AgriPestRelation(BaseModel):
# 2. Prompts
# ==============================================================================
-_TEMPLATE_PROMPT = """
+_PROMPT = """
You are an expert agronomist and pest management specialist.
Your task is to extract a comprehensive knowledge graph of crop pests, diseases, and their control methods.
@@ -87,7 +87,7 @@ class AgriPestControl(AutoGraph[AgriPestEntity, AgriPestRelation]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=_TEMPLATE_PROMPT,
+ prompt=_PROMPT,
**kwargs,
)
diff --git a/hyperextract/templates/en/biology/metabolic.py b/hyperextract/templates/en/biology/metabolic.py
index dff01c2..d3d5fac 100644
--- a/hyperextract/templates/en/biology/metabolic.py
+++ b/hyperextract/templates/en/biology/metabolic.py
@@ -49,7 +49,7 @@ class MetabolicReactionHyperedge(BaseModel):
# 2. Prompts
# ==============================================================================
-METABOLIC_CONSOLIDATED_PROMPT = (
+_PROMPT = (
"You are a biochemist specializing in metabolic engineering. Extract complex N-ary reactions.\n\n"
"Rules:\n"
"- Group all participants (substrates, products, and enzymes) into a single Hyperedge.\n"
@@ -57,7 +57,7 @@ METABOLIC_CONSOLIDATED_PROMPT = (
"- Capture the catalytic enzymes as part of the hyperedge participants."
)
-METABOLIC_NODE_PROMPT = (
+_NODE_PROMPT = (
"You are a biochemist. Your task is to identify all metabolites and catalytic enzymes (Nodes) involved in metabolic processes.\n\n"
"Extraction Rules:\n"
"- Identify chemical components (substrates/products) and the enzymes that facilitate their transformation.\n"
@@ -66,7 +66,7 @@ METABOLIC_NODE_PROMPT = (
"- DO NOT construct reaction equations or complexes at this stage."
)
-METABOLIC_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"You are a biochemist. Given the following list of metabolites and enzymes, extract complex metabolic reactions (Hyperedges).\n\n"
"Extraction Rules:\n"
"- Group all participants (substrates, products, and enzymes) into single reaction events.\n"
@@ -112,9 +112,9 @@ class MetabolicHypergraph(AutoHypergraph[MetaboliteNode, MetabolicReactionHypere
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=METABOLIC_CONSOLIDATED_PROMPT,
- prompt_for_node_extraction=METABOLIC_NODE_PROMPT,
- prompt_for_edge_extraction=METABOLIC_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs,
)
diff --git a/hyperextract/templates/en/biology/network.py b/hyperextract/templates/en/biology/network.py
index 50699c4..2921da9 100644
--- a/hyperextract/templates/en/biology/network.py
+++ b/hyperextract/templates/en/biology/network.py
@@ -31,7 +31,7 @@ class BioInteractionEdge(BaseModel):
# 2. Prompts
# ==============================================================================
-NETWORK_CONSOLIDATED_PROMPT = (
+_PROMPT = (
"You are a bioinformatics expert specializing in molecular signaling and regulatory networks. "
"Extract interactions from the text to build a biological network graph.\n\n"
"Rules:\n"
@@ -40,7 +40,7 @@ NETWORK_CONSOLIDATED_PROMPT = (
"- Capture the specific biochemical mechanism for each edge."
)
-NETWORK_NODE_PROMPT = (
+_NODE_PROMPT = (
"You are a bioinformatics expert. Your task is to identify all molecular entities (Nodes) mentioned in the text.\n\n"
"Extraction Rules:\n"
"- Identify genes, proteins, RNAs, and metabolites. Use standard nomenclature (e.g., HGNC symbols).\n"
@@ -49,7 +49,7 @@ NETWORK_NODE_PROMPT = (
"- DO NOT extract interactions or state changes at this stage."
)
-NETWORK_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"You are a bioinformatics expert. Given the following list of molecular entities, extract their physical and functional interactions (Edges).\n\n"
"Extraction Rules:\n"
"- Identify the type of interaction (Phosphorylation, Inhibition, Activation, Binding, etc.).\n"
@@ -91,9 +91,9 @@ class BiologicalNetwork(AutoGraph[BioEntityNode, BioInteractionEdge]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=NETWORK_CONSOLIDATED_PROMPT,
- prompt_for_node_extraction=NETWORK_NODE_PROMPT,
- prompt_for_edge_extraction=NETWORK_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs
)
def show(
diff --git a/hyperextract/templates/en/biology/taxonomy.py b/hyperextract/templates/en/biology/taxonomy.py
index 94ae1ea..9e9c7ef 100644
--- a/hyperextract/templates/en/biology/taxonomy.py
+++ b/hyperextract/templates/en/biology/taxonomy.py
@@ -50,7 +50,7 @@ class TaxonomyRelation(BaseModel):
# 2. Prompts
# ==============================================================================
-TAXONOMY_CONSOLIDATED_PROMPT = (
+_PROMPT = (
"You are a professional taxonomist and systematic biologist. Extract the biological hierarchy (Taxonomy) from the text.\n\n"
"Rules:\n"
"- Identify all taxons (Kingdom to Species) and their specific ranks.\n"
@@ -58,7 +58,7 @@ TAXONOMY_CONSOLIDATED_PROMPT = (
"- Capture both scientific names and common names where available."
)
-TAXONOMY_NODE_PROMPT = (
+_NODE_PROMPT = (
"You are a professional taxonomist. Your task is to identify and extract all biological taxonomic units (Nodes) from the text.\n\n"
"Extraction Rules:\n"
"- Identify the scientific name and assigned rank (e.g., Domain, Kingdom, Phylum, Class, Order, Family, Genus, Species) for each taxon.\n"
@@ -67,7 +67,7 @@ TAXONOMY_NODE_PROMPT = (
"- DO NOT extract relationships between taxons at this stage."
)
-TAXONOMY_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"You are a professional taxonomist. Given the following list of identified taxons, extract the hierarchical relationships (Edges) described in the text.\n\n"
"Extraction Rules:\n"
"- Establish 'parent_of' links where a higher-rank taxon contains a lower-rank one.\n"
@@ -113,9 +113,9 @@ class TaxonomyGraph(AutoGraph[TaxonNode, TaxonomyRelation]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=TAXONOMY_CONSOLIDATED_PROMPT,
- prompt_for_node_extraction=TAXONOMY_NODE_PROMPT,
- prompt_for_edge_extraction=TAXONOMY_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs,
)
diff --git a/hyperextract/templates/en/chemistry/molecular.py b/hyperextract/templates/en/chemistry/molecular.py
index 37e8457..749e800 100644
--- a/hyperextract/templates/en/chemistry/molecular.py
+++ b/hyperextract/templates/en/chemistry/molecular.py
@@ -48,7 +48,7 @@ class ChemicalBond(BaseModel):
# 2. Prompts
# ==============================================================================
-MOLECULAR_CONSOLIDATED_PROMPT = (
+_PROMPT = (
"You are a computational chemist and crystallographer. Extract the 3D molecular topology.\n\n"
"Rules:\n"
"- Identify every atom as a node.\n"
@@ -56,7 +56,7 @@ MOLECULAR_CONSOLIDATED_PROMPT = (
"- Capture the formal charge and hybridization of each atom."
)
-MOLECULAR_NODE_PROMPT = (
+_NODE_PROMPT = (
"You are a computational chemist. Your task is to identify and extract all individual atoms (Nodes) from the molecular structure.\n\n"
"Extraction Rules:\n"
"- Identify the unique atom identifier (e.g., C1) and its chemical element symbol.\n"
@@ -65,7 +65,7 @@ MOLECULAR_NODE_PROMPT = (
"- DO NOT identify bonds or spatial connectivity at this stage."
)
-MOLECULAR_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"You are a computational chemist. Given the list of atoms, map the chemical bonds and spatial connectivity (Edges).\n\n"
"Extraction Rules:\n"
"- Define the bond type (Single, Double, Aromatic, etc.) between a source and target atom.\n"
@@ -112,9 +112,9 @@ class MolecularStructureGraph(AutoSpatialGraph[AtomNode, ChemicalBond]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=MOLECULAR_CONSOLIDATED_PROMPT,
- prompt_for_node_extraction=MOLECULAR_NODE_PROMPT,
- prompt_for_edge_extraction=MOLECULAR_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs,
)
diff --git a/hyperextract/templates/en/chemistry/protocol.py b/hyperextract/templates/en/chemistry/protocol.py
index eb11ec5..0964fdb 100644
--- a/hyperextract/templates/en/chemistry/protocol.py
+++ b/hyperextract/templates/en/chemistry/protocol.py
@@ -51,7 +51,7 @@ class ProtocolTransition(BaseModel):
# 2. Prompts
# ==============================================================================
-PROTOCOL_CONSOLIDATED_PROMPT = (
+_PROMPT = (
"You are a laboratory technician specializing in protocol documentation. Extract sequential lab steps.\n\n"
"Rules:\n"
"- Represent each operation as a Node.\n"
@@ -60,7 +60,7 @@ PROTOCOL_CONSOLIDATED_PROMPT = (
"- Map the timeline precisely (e.g., 'Step 1' -> 'Step 2')."
)
-PROTOCOL_NODE_PROMPT = (
+_NODE_PROMPT = (
"You are a laboratory technician. Your task is to identify individual protocol operations (Nodes).\n\n"
"Extraction Rules:\n"
"- Identify discrete actions (e.g., Centrifuge, Incubate, Titrate).\n"
@@ -69,7 +69,7 @@ PROTOCOL_NODE_PROMPT = (
"- DO NOT establish the sequence or timing between steps at this stage."
)
-PROTOCOL_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"You are a laboratory technician. Given the list of laboratory operations, extract the sequential flow (Edges).\n\n"
"Extraction Rules:\n"
"- Connect the source step to the target step in chronological order.\n"
@@ -117,9 +117,9 @@ class LabProtocolTemporal(AutoTemporalGraph[LabOperation, ProtocolTransition]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=PROTOCOL_CONSOLIDATED_PROMPT,
- prompt_for_node_extraction=PROTOCOL_NODE_PROMPT,
- prompt_for_edge_extraction=PROTOCOL_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs,
)
diff --git a/hyperextract/templates/en/chemistry/reaction.py b/hyperextract/templates/en/chemistry/reaction.py
index 254f8b6..055aa7d 100644
--- a/hyperextract/templates/en/chemistry/reaction.py
+++ b/hyperextract/templates/en/chemistry/reaction.py
@@ -56,7 +56,7 @@ class ReactionEvent(BaseModel):
# 2. Prompts
# ==============================================================================
-REACTION_CONSOLIDATED_PROMPT = (
+_PROMPT = (
"You are an expert organic and inorganic chemist. Extract multi-component reaction events.\n\n"
"Rules:\n"
"- Represent each reaction as a Hyperedge connecting all reactants, products, and catalysts.\n"
@@ -64,7 +64,7 @@ REACTION_CONSOLIDATED_PROMPT = (
"- Identify the role of each chemical entity correctly in the reaction context."
)
-REACTION_NODE_PROMPT = (
+_NODE_PROMPT = (
"You are an organic chemist. Your task is to identify and extract all chemical entities (Nodes) mentioned in the text.\n\n"
"Extraction Rules:\n"
"- Identify reagents, products, catalysts, and solvents.\n"
@@ -73,7 +73,7 @@ REACTION_NODE_PROMPT = (
"- DO NOT construct reaction sequences or grouping participants at this stage."
)
-REACTION_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"You are an organic chemist. Given the list of chemical entities, extract multi-component reaction events (Hyperedges).\n\n"
"Extraction Rules:\n"
"- Group all participants (reactants, products, catalysts, solvents) into a single reaction hyperedge.\n"
@@ -119,9 +119,9 @@ class ChemicalReactionHyper(AutoHypergraph[ChemicalEntity, ReactionEvent]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=REACTION_CONSOLIDATED_PROMPT,
- prompt_for_node_extraction=REACTION_NODE_PROMPT,
- prompt_for_edge_extraction=REACTION_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs,
)
diff --git a/hyperextract/templates/en/education/academic_lexicon.py b/hyperextract/templates/en/education/academic_lexicon.py
index 32e8b34..684fed4 100644
--- a/hyperextract/templates/en/education/academic_lexicon.py
+++ b/hyperextract/templates/en/education/academic_lexicon.py
@@ -36,7 +36,7 @@ class AcademicTerm(BaseModel):
# 2. Prompts
# ==============================================================================
-ACADEMIC_LEXICON_PROMPT = (
+_PROMPT = (
"You are a Lexicographer and Academic Encyclopedia Editor. Your goal is to extract standardize academic definitions.\n\n"
"Extraction Rules:\n"
"- Identify unique academic terms and their highly precise definitions.\n"
@@ -98,7 +98,7 @@ class AcademicLexiconSet(AutoSet[AcademicTerm]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=ACADEMIC_LEXICON_PROMPT,
+ prompt=_PROMPT,
**kwargs,
)
diff --git a/hyperextract/templates/en/education/interdisciplinary_nexus.py b/hyperextract/templates/en/education/interdisciplinary_nexus.py
index ace46d6..222ac30 100644
--- a/hyperextract/templates/en/education/interdisciplinary_nexus.py
+++ b/hyperextract/templates/en/education/interdisciplinary_nexus.py
@@ -40,7 +40,7 @@ class InterdisciplinaryEdge(BaseModel):
# 2. Prompts
# ==============================================================================
-NEXUS_CONSOLIDATED_PROMPT = (
+_PROMPT = (
"You are a Polymath and Interdisciplinary Researcher. Identify deep connections between concepts across different academic fields.\n\n"
"Extraction Rules:\n"
"- Identify core concepts as Nodes.\n"
@@ -48,14 +48,14 @@ NEXUS_CONSOLIDATED_PROMPT = (
"- Focus on finding surprising but scientifically valid bridges (e.g., connecting Biology and Economics through Game Theory)."
)
-NEXUS_NODE_PROMPT = (
+_NODE_PROMPT = (
"Identify fundamental academic concepts that carry cross-disciplinary potential.\n\n"
"Rules:\n"
"- Extract nouns/concepts that are central to their respective fields.\n"
"- Identify the field of origin."
)
-NEXUS_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"Identify the 'Nexuses' or Hyperedges that unify a group of concepts.\n\n"
"Rules:\n"
"- A hyperedge must involve more than two nodes whenever possible.\n"
@@ -123,9 +123,9 @@ class InterdisciplinaryNexusHypergraph(
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=NEXUS_CONSOLIDATED_PROMPT,
- prompt_for_node_extraction=NEXUS_NODE_PROMPT,
- prompt_for_edge_extraction=NEXUS_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs,
)
diff --git a/hyperextract/templates/en/education/prerequisite_map.py b/hyperextract/templates/en/education/prerequisite_map.py
index c7a7030..8dd2fb3 100644
--- a/hyperextract/templates/en/education/prerequisite_map.py
+++ b/hyperextract/templates/en/education/prerequisite_map.py
@@ -48,7 +48,7 @@ class PrerequisiteRelation(BaseModel):
# 2. Prompts
# ==============================================================================
-EDUCATION_CONSOLIDATED_PROMPT = (
+_PROMPT = (
"You are a Senior Curriculum Architect and Educational Psychologist. Extract the logical structure of knowledge points from the text.\n\n"
"Rules:\n"
"- Identify atomic concepts that constitute the learning path.\n"
@@ -56,7 +56,7 @@ EDUCATION_CONSOLIDATED_PROMPT = (
"- Ensure that the resulting graph reflects a sound pedagogical sequence."
)
-EDUCATION_NODE_PROMPT = (
+_NODE_PROMPT = (
"You are an Educational Psychologist specializing in knowledge decomposition. Your task is to identify all discrete Knowledge Points (Nodes).\n\n"
"Extraction Rules:\n"
"- Focus on nouns or noun phrases that represent specific academic concepts, formulas, or methods.\n"
@@ -64,7 +64,7 @@ EDUCATION_NODE_PROMPT = (
"- DO NOT identify relationships or dependencies at this stage."
)
-EDUCATION_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"You are a Curriculum Designer. Given the identified knowledge points, map the Prerequisite Relations (Edges).\n\n"
"Extraction Rules:\n"
"- Determine if Concept A is a necessary precursor to Concept B.\n"
@@ -136,9 +136,9 @@ class PrerequisiteMapGraph(AutoGraph[KnowledgePointNode, PrerequisiteRelation]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=EDUCATION_CONSOLIDATED_PROMPT,
- prompt_for_node_extraction=EDUCATION_NODE_PROMPT,
- prompt_for_edge_extraction=EDUCATION_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs,
)
diff --git a/hyperextract/templates/en/environment/__init__.py b/hyperextract/templates/en/environment/__init__.py
index e69de29..50df726 100644
--- a/hyperextract/templates/en/environment/__init__.py
+++ b/hyperextract/templates/en/environment/__init__.py
@@ -0,0 +1,11 @@
+"""Environment domain templates for ecological and environmental analysis."""
+
+from .species_interaction import SpeciesInteractionNetwork
+from .pollutant_impact import PollutantImpactMap
+from .endangered_species import EndangeredSpeciesList
+
+__all__ = [
+ "SpeciesInteractionNetwork",
+ "PollutantImpactMap",
+ "EndangeredSpeciesList",
+]
diff --git a/hyperextract/templates/en/environment/endangered_species.py b/hyperextract/templates/en/environment/endangered_species.py
new file mode 100644
index 0000000..aefbbeb
--- /dev/null
+++ b/hyperextract/templates/en/environment/endangered_species.py
@@ -0,0 +1,127 @@
+from typing import Optional, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types.set import AutoSet
+
+# ==============================================================================
+# 1. Schema Definitions
+# ==============================================================================
+
+
+class SpeciesStatus(BaseModel):
+ """Conservation and endangerment status of a species."""
+
+ name: str = Field(description="Scientific or common name of the species.")
+ endangered_level: str = Field(
+ description="Conservation status: 'Extinct', 'Extinct in the Wild', 'Critically Endangered', 'Endangered', 'Vulnerable', 'Near Threatened', 'Least Concern'."
+ )
+ main_threats: Optional[str] = Field(
+ None,
+ description="Primary threats to the species (e.g., 'habitat loss', 'poaching', 'climate change', 'pollution')."
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = """
+You are a conservation biologist and wildlife protection expert.
+Your task is to extract information about endangered and threatened species from conservation reports, IUCN Red List summaries, and biodiversity assessments.
+
+Guidelines:
+1. Identify all species mentioned with their conservation or endangerment status.
+2. For each species, classify it according to standard conservation levels: Extinct, Extinct in the Wild, Critically Endangered, Endangered, Vulnerable, Near Threatened, or Least Concern.
+3. Extract the primary threats that endanger the species (habitat loss, poaching, climate change, disease, pollution, etc.).
+4. Ensure scientific accuracy in species names and classification.
+5. Avoid duplication: if a species appears multiple times with the same status and threats, treat as a single entry.
+
+Output Format:
+- Each species should have a name, endangered_level, and main_threats.
+- Consolidate multiple mentions of the same species into a single comprehensive entry.
+"""
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+
+class EndangeredSpeciesList(AutoSet[SpeciesStatus]):
+ """
+ Unique collection template for endangered and threatened species documentation.
+
+ Transforms conservation assessments and biodiversity reports into a deduplicated
+ registry of species with their endangerment status and key threats, supporting
+ conservation priority-setting and resource allocation.
+
+ Example:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4")
+ >>> embedder = OpenAIEmbeddings()
+ >>>
+ >>> endangered_list = EndangeredSpeciesList(llm_client=llm, embedder=embedder)
+ >>> text = "The Giant Panda (Vulnerable) faces habitat loss. The Javan Rhinoceros (Critically Endangered) is threatened by poaching."
+ >>> endangered_list.feed_text(text)
+ >>> endangered_list.show() # Display deduplicated endangered species
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """Initialize the EndangeredSpeciesList template.
+
+ Args:
+ llm_client (BaseChatModel): Language model client for extracting species and threat information.
+ embedder (Embeddings): Embedding model for deduplicating species entries and indexing threat descriptions.
+ chunk_size (int, optional): Maximum characters per text chunk. Defaults to 2048.
+ chunk_overlap (int, optional): Overlapping characters between chunks for context preservation. Defaults to 256.
+ max_workers (int, optional): Maximum concurrent extraction workers. Defaults to 10.
+ verbose (bool, optional): If True, prints detailed extraction and deduplication progress logs. Defaults to False.
+ **kwargs: Additional arguments passed to the AutoSet base class for deduplication control.
+ """
+ super().__init__(
+ item_schema=SpeciesStatus,
+ key_extractor=lambda x: x.name.strip().lower(),
+ llm_client=llm_client,
+ embedder=embedder,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ prompt=_PROMPT,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 3,
+ top_k_for_chat: int = 3,
+ ) -> None:
+ """Visualize the endangered species list for conservation planning.
+
+ Displays the deduplicated unique collection of species with endangerment levels and threats using OntoSight.
+ Internally defines frontend labels for species (name + endangered_level for conservation priority visualization).
+
+ Args:
+ top_k_for_search (int, optional): Number of species to retrieve from the deduplicated collection for search-triggered context. Defaults to 3.
+ top_k_for_chat (int, optional): Number of species to retrieve from the deduplicated collection for chat-triggered context. Defaults to 3.
+ """
+
+ def item_label_extractor(item: SpeciesStatus) -> str:
+ return f"{item.name} - {item.endangered_level}"
+
+ super().show(
+ item_label_extractor=item_label_extractor,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/en/environment/pollutant_impact.py b/hyperextract/templates/en/environment/pollutant_impact.py
new file mode 100644
index 0000000..1f50d75
--- /dev/null
+++ b/hyperextract/templates/en/environment/pollutant_impact.py
@@ -0,0 +1,191 @@
+from typing import Optional, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types.graph import AutoGraph
+
+# ==============================================================================
+# 1. Schema Definitions
+# ==============================================================================
+
+
+class EnvironmentalEntity(BaseModel):
+ """An entity in the environmental pollution domain."""
+
+ name: str = Field(description="Name of the pollutant, contaminated site, or impacted entity.")
+ entity_type: str = Field(
+ description="Type: 'Pollutant' (chemical, particle, etc.), 'Source' (factory, vehicle), 'Target' (water, air, soil, organism)."
+ )
+ description: Optional[str] = Field(
+ None, description="Additional details such as chemical properties, location, or characteristics."
+ )
+
+
+class PollutantImpact(BaseModel):
+ """The impact relationship between a source/pollutant and a target/receptor."""
+
+ source: str = Field(description="The pollutant or contamination source.")
+ target: str = Field(description="The impacted entity (ecosystem, organism, location).")
+ impact_type: str = Field(
+ description="Type of impact: 'bioaccumulation', 'toxicity', 'contamination', 'ecosystem damage', 'health effect'."
+ )
+ severity: Optional[str] = Field(
+ None, description="Severity level: 'critical', 'high', 'moderate', 'low'. Include any quantitative measures if available."
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = """
+You are an environmental scientist specializing in pollution assessment and ecosystem impact analysis.
+Your task is to extract pollution sources, pollutants, and their environmental impacts from reports, monitoring data, and news articles.
+
+Guidelines:
+1. Identify all pollutants mentioned (e.g., Mercury, PM2.5, Plastic, Carbon dioxide).
+2. Identify pollution sources (factories, vehicles, agricultural runoff, etc.) and impacted targets (rivers, air, soil, human populations, wildlife).
+3. Extract the causal relationships: which pollutant affects which entity and how.
+4. Capture severity or quantitative impact information if mentioned (e.g., "50 mg/L concentration", "critical contamination level").
+5. Be precise about the directionality: pollution flows FROM source TO target.
+
+Output Format:
+- Pollutants and impacted entities should be distinct nodes.
+- Impacts should have a clear source (pollutant/source), target (receptor), impact type, and severity if available.
+"""
+
+_NODE_PROMPT = """
+You are an environmental scientist specializing in pollution assessment.
+Your task is to extract ONLY environmental entities (pollutants, sources, and targets) during the first extraction stage.
+Do not identify pollution impacts yet - focus solely on finding all entities.
+
+Guidelines:
+1. Identify all pollutants mentioned (chemicals, particles, compounds).
+2. Identify all pollution sources (factories, vehicles, sites).
+3. Identify all impacted targets (water bodies, organisms, human populations, ecosystems).
+4. For each entity, capture: name, entity_type, and any relevant characteristics.
+5. Avoid duplicates: consolidate references to the same entity.
+
+Output Format:
+- Each entity should be a distinct node with name, type (Pollutant/Source/Target), and description.
+"""
+
+_EDGE_PROMPT = """
+You are an environmental scientist analyzing pollution impacts.
+Your task is to extract ONLY the causal relationships between given entities during the second extraction stage.
+You will be provided with environmental entities (nodes). Your job is to identify pollution impacts between them.
+
+Guidelines:
+1. Given the list of confirmed entities, find all pollution impact relationships in the text.
+2. For each impact, capture: source (pollutant/source entity), target (impacted entity), impact_type, and severity.
+3. Preserve directionality: pollutant flows FROM source TO target.
+4. Only extract impacts between given entities; ignore stands-alone entity mentions.
+5. Include quantitative measures (concentrations, severity levels) if available.
+
+Output Format:
+- Each impact is an edge: Source → Target with impact_type and severity.
+"""
+
+# ==============================================================================
+# 3. Template Class
+# =============================================================================="
+
+
+class PollutantImpactMap(AutoGraph[EnvironmentalEntity, PollutantImpact]):
+ """
+ Knowledge graph template for environmental pollution tracking and impact assessment.
+
+ Transforms environmental monitoring reports and sustainability analyses into structured
+ pollution source-target relationships, enabling environmental health risk analysis.
+
+ Example:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4")
+ >>> embedder = OpenAIEmbeddings()
+ >>>
+ >>> pollutant_map = PollutantImpactMap(llm_client=llm, embedder=embedder)
+ >>> text = "Mercury discharged from the factory contaminated the river, causing fish toxicity at critical levels."
+ >>> pollutant_map.feed_text(text)
+ >>> pollutant_map.show() # Visualize pollution impacts and severity
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "one_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """Initialize the PollutantImpactMap template.
+
+ Args:
+ llm_client (BaseChatModel): Language model client for extracting pollutants and impacts.
+ embedder (Embeddings): Embedding model for indexing pollutants, sources, and impacted targets.
+ extraction_mode (str, optional): Extraction strategy. Defaults to "one_stage".
+ - "one_stage": Extract pollutants and impacts simultaneously (faster).
+ - "two_stage": Extract pollutants first, then impacts (higher accuracy).
+ chunk_size (int, optional): Maximum characters per text chunk. Defaults to 2048.
+ chunk_overlap (int, optional): Overlapping characters between chunks for context preservation. Defaults to 256.
+ max_workers (int, optional): Maximum concurrent extraction workers for parallel processing. Defaults to 10.
+ verbose (bool, optional): If True, prints detailed extraction progress and pollution tracking logs. Defaults to False.
+ **kwargs: Additional arguments passed to the AutoGraph base class.
+ """
+ super().__init__(
+ node_schema=EnvironmentalEntity,
+ edge_schema=PollutantImpact,
+ node_key_extractor=lambda x: x.name.strip(),
+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.impact_type.lower()})-->{x.target.strip()}",
+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),
+ llm_client=llm_client,
+ embedder=embedder,
+ extraction_mode=extraction_mode,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_nodes_for_search: int = 3,
+ top_k_edges_for_search: int = 3,
+ top_k_nodes_for_chat: int = 3,
+ top_k_edges_for_chat: int = 3,
+ ) -> None:
+ """Visualize the pollutant impact network for environmental assessment.
+
+ Displays pollution sources, pollutants, and impacted targets with severity information using OntoSight.
+ Internally defines frontend labels for entities (name + entity_type) and impacts (impact_type + severity).
+
+ Args:
+ top_k_nodes_for_search (int, optional): Number of environmental entities (pollutants/sources/targets) to retrieve for search context. Defaults to 3.
+ top_k_edges_for_search (int, optional): Number of impact relationships to retrieve for search context. Defaults to 3.
+ top_k_nodes_for_chat (int, optional): Number of environmental entities to retrieve for chat context. Defaults to 3.
+ top_k_edges_for_chat (int, optional): Number of impact relationships to retrieve for chat context. Defaults to 3.
+ """
+
+ def node_label_extractor(node: EnvironmentalEntity) -> str:
+ return f"{node.name} ({node.entity_type})"
+
+ def edge_label_extractor(edge: PollutantImpact) -> str:
+ severity = f" [{edge.severity}]" if edge.severity else ""
+ return f"{edge.impact_type}{severity}"
+
+ super().show(
+ node_label_extractor=node_label_extractor,
+ edge_label_extractor=edge_label_extractor,
+ top_k_nodes_for_search=top_k_nodes_for_search,
+ top_k_edges_for_search=top_k_edges_for_search,
+ top_k_nodes_for_chat=top_k_nodes_for_chat,
+ top_k_edges_for_chat=top_k_edges_for_chat,
+ )
diff --git a/hyperextract/templates/en/environment/species_interaction.py b/hyperextract/templates/en/environment/species_interaction.py
new file mode 100644
index 0000000..57b77c2
--- /dev/null
+++ b/hyperextract/templates/en/environment/species_interaction.py
@@ -0,0 +1,191 @@
+from typing import Optional, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types.graph import AutoGraph
+
+# ==============================================================================
+# 1. Schema Definitions
+# ==============================================================================
+
+
+class Species(BaseModel):
+ """An organism entity in the ecosystem."""
+
+ name: str = Field(description="Scientific or common name of the species.")
+ category: str = Field(
+ description="Taxonomic classification: 'Mammal', 'Bird', 'Insect', 'Plant', 'Microorganism', etc."
+ )
+ protection_level: Optional[str] = Field(
+ None, description="Conservation status: 'Endangered', 'Vulnerable', 'Least Concern', etc."
+ )
+
+
+class Interaction(BaseModel):
+ """The biological interaction between two species."""
+
+ source: str = Field(description="The initiating species (predator, competitor, etc.).")
+ target: str = Field(description="The receiving species (prey, competitor, host, etc.).")
+ interaction_type: str = Field(
+ description="Type of interaction: 'predation', 'parasitism', 'mutualism', 'commensalism', 'competition', 'symbiosis'."
+ )
+ detail: Optional[str] = Field(
+ None, description="Specific details about the interaction (e.g., frequency, seasonal pattern, ecological impact)."
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = """
+You are an expert ecologist and biodiversity specialist.
+Your task is to extract the ecological interaction network from scientific texts, field reports, or nature documentaries.
+
+Guidelines:
+1. Identify all organisms mentioned in the text and classify them by category (species, type).
+2. Extract the biological relationships between organisms (predation, parasitism, competition, mutualism, etc.).
+3. For each interaction, capture the interaction type and any specific ecological details (timing, frequency, conditions).
+4. Preserve the directionality of interactions (e.g., "Lion hunts Zebra" is different from "Zebra avoids Lion").
+5. Include conservation status information if mentioned.
+
+Output Format:
+- Each species should be a distinct entity with name, category, and conservation status if available.
+- Each interaction should clearly state the source (initiating organism), target (receiving organism), and interaction type.
+"""
+
+_NODE_PROMPT = """
+You are an expert ecologist and biodiversity specialist.
+Your task is to extract ONLY species/organisms from the text during the first extraction stage.
+Do not identify interactions yet - focus solely on finding all distinct organisms mentioned.
+
+Guidelines:
+1. List all species, organisms, or populations mentioned in the text.
+2. For each organism, capture: name, category (e.g., predator, prey, plant, decomposer), and conservation status if available.
+3. Ensure no duplicates: if "Lion" and "African Lion" refer to the same species, consolidate to the most specific name.
+4. Ignore vague references; extract only explicitly mentioned organisms.
+
+Output Format:
+- Each organism should be a distinct node with clear name, category, and status.
+"""
+
+_EDGE_PROMPT = """
+You are an expert ecologist analyzing species interactions.
+Your task is to extract ONLY the biological relationships between given species during the second extraction stage.
+You will be provided with a list of already-extracted species (nodes). Your job is to identify interactions between them.
+
+Guidelines:
+1. Given the list of confirmed species, find all pairwise interactions mentioned in the text.
+2. For each interaction, capture: source species, target species, interaction type (predation, mutualism, competition, etc.), and details.
+3. Preserve directionality: "A eats B" is predation (A→B), different from "B avoids A".
+4. Only extract interactions that connect the given species; ignore mentions of species not in the provided list.
+5. Include ecological context (seasonal, frequency, conditions) as details.
+
+Output Format:
+- Each interaction is an edge: Source → Target with relation type and details.
+"""
+
+# ==============================================================================
+# 3. Template Class
+# =============================================================================="
+
+
+class SpeciesInteractionNetwork(AutoGraph[Species, Interaction]):
+ """
+ Knowledge graph template for ecological species interactions.
+
+ Transforms scientific texts and field studies into structured interaction networks,
+ enabling analysis of ecosystem biodiversity and food webs.
+
+ Example:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4")
+ >>> embedder = OpenAIEmbeddings()
+ >>>
+ >>> network = SpeciesInteractionNetwork(llm_client=llm, embedder=embedder)
+ >>> text = "Lions hunt zebras in the African savanna. Parasitic wasps are eaten by birds."
+ >>> network.feed_text(text)
+ >>> network.show() # Visualize the species interaction network
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "one_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """Initialize the SpeciesInteractionNetwork template.
+
+ Args:
+ llm_client (BaseChatModel): Language model client for species and interaction extraction.
+ embedder (Embeddings): Embedding model for vector indexing of species nodes and interaction edges.
+ extraction_mode (str, optional): Extraction strategy. Defaults to "one_stage".
+ - "one_stage": Extract species and interactions simultaneously (faster).
+ - "two_stage": Extract species first, then interactions (higher accuracy).
+ chunk_size (int, optional): Maximum characters per text chunk. Defaults to 2048.
+ chunk_overlap (int, optional): Overlapping characters between chunks for context preservation. Defaults to 256.
+ max_workers (int, optional): Maximum concurrent extraction workers. Defaults to 10.
+ verbose (bool, optional): If True, prints detailed extraction progress logs. Defaults to False.
+ **kwargs: Additional arguments passed to the AutoGraph base class.
+ """
+ super().__init__(
+ node_schema=Species,
+ edge_schema=Interaction,
+ node_key_extractor=lambda x: x.name.strip(),
+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.interaction_type.lower()})-->{x.target.strip()}",
+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),
+ llm_client=llm_client,
+ embedder=embedder,
+ extraction_mode=extraction_mode,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_nodes_for_search: int = 3,
+ top_k_edges_for_search: int = 3,
+ top_k_nodes_for_chat: int = 3,
+ top_k_edges_for_chat: int = 3,
+ ) -> None:
+ """Visualize the species interaction network for ecological analysis.
+
+ Displays the extracted species (nodes) and their interactions (edges) using OntoSight visualization.
+ Internally defines frontend visualization labels for species (name + category + protection status)
+ and interactions (interaction type).
+
+ Args:
+ top_k_nodes_for_search (int, optional): Number of species nodes to retrieve for search-triggered context. Defaults to 3.
+ top_k_edges_for_search (int, optional): Number of interaction edges to retrieve for search-triggered context. Defaults to 3.
+ top_k_nodes_for_chat (int, optional): Number of species nodes to retrieve for chat-triggered context. Defaults to 3.
+ top_k_edges_for_chat (int, optional): Number of interaction edges to retrieve for chat-triggered context. Defaults to 3.
+ """
+
+ def node_label_extractor(node: Species) -> str:
+ status = f" [{node.protection_level}]" if node.protection_level else ""
+ return f"{node.name} ({node.category}){status}"
+
+ def edge_label_extractor(edge: Interaction) -> str:
+ return f"{edge.interaction_type}"
+
+ super().show(
+ node_label_extractor=node_label_extractor,
+ edge_label_extractor=edge_label_extractor,
+ top_k_nodes_for_search=top_k_nodes_for_search,
+ top_k_edges_for_search=top_k_edges_for_search,
+ top_k_nodes_for_chat=top_k_nodes_for_chat,
+ top_k_edges_for_chat=top_k_edges_for_chat,
+ )
diff --git a/hyperextract/templates/en/general/concept_map.py b/hyperextract/templates/en/general/concept_map.py
index bbdeae4..e21215d 100644
--- a/hyperextract/templates/en/general/concept_map.py
+++ b/hyperextract/templates/en/general/concept_map.py
@@ -38,7 +38,7 @@ class ConceptRelation(BaseModel):
# 2. Prompts
# ==============================================================================
-CONCEPT_MAP_PROMPT = (
+_PROMPT = (
"You are an expert in semantic modeling. Extract a concept map from the text, focusing on "
"definitions, terminologies, and their hierarchical or associative relationships.\n\n"
"Guidelines:\n"
@@ -47,13 +47,13 @@ CONCEPT_MAP_PROMPT = (
"- Capture illustrative examples if mentioned."
)
-CONCEPT_MAP_NODE_PROMPT = (
+_NODE_PROMPT = (
"Extract all foundational concepts and technical terms from the text. "
"For each concept, provide its term, a precise definition, a list of key attributes, "
"and any specific examples mentioned in the source."
)
-CONCEPT_MAP_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"Establish semantic relationships between the provided concepts. "
"Focus on hierarchical taxonomies (is-a, part-of) and functional associations (used-for, instance-of). "
"Ensure edges logically connect the defined concepts."
@@ -125,9 +125,9 @@ class ConceptMap(AutoGraph[Concept, ConceptRelation]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=CONCEPT_MAP_PROMPT,
- prompt_for_node_extraction=CONCEPT_MAP_NODE_PROMPT,
- prompt_for_edge_extraction=CONCEPT_MAP_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs,
)
diff --git a/hyperextract/templates/en/general/knowledge_graph.py b/hyperextract/templates/en/general/knowledge_graph.py
index 0cbb637..05eee13 100644
--- a/hyperextract/templates/en/general/knowledge_graph.py
+++ b/hyperextract/templates/en/general/knowledge_graph.py
@@ -38,7 +38,7 @@ class Relation(BaseModel):
# 2. Prompts
# ==============================================================================
-KNOWLEDGE_GRAPH_PROMPT = (
+_PROMPT = (
"You are an expert knowledge extraction system. Your task is to extract a factual knowledge graph "
"from the provided text. Focus on identifying key entities (People, Organizations, Locations, and relevant Objects) "
"and the explicit relationships between them.\n\n"
@@ -48,12 +48,12 @@ KNOWLEDGE_GRAPH_PROMPT = (
"- Use clear, concise language for descriptions and relations."
)
-KNOWLEDGE_GRAPH_NODE_PROMPT = (
+_NODE_PROMPT = (
"Extract all key entities from the text. Focus on identifying People, Organizations, Locations, and important Objects. "
"Provide a name, a category, and a concise description for each entity."
)
-KNOWLEDGE_GRAPH_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"Identify factual relationships between the following listed entities based on the text. "
"Focus on interactions like 'works for', 'located in', 'acquired', or 'partnered with'. "
"Do not hallucinate entities not in the provided list."
@@ -125,9 +125,9 @@ class KnowledgeGraph(AutoGraph[Entity, Relation]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=KNOWLEDGE_GRAPH_PROMPT,
- prompt_for_node_extraction=KNOWLEDGE_GRAPH_NODE_PROMPT,
- prompt_for_edge_extraction=KNOWLEDGE_GRAPH_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs,
)
diff --git a/hyperextract/templates/en/general/logic_graph.py b/hyperextract/templates/en/general/logic_graph.py
index 737c3cf..be1d245 100644
--- a/hyperextract/templates/en/general/logic_graph.py
+++ b/hyperextract/templates/en/general/logic_graph.py
@@ -35,7 +35,7 @@ class LogicRelation(BaseModel):
# 2. Prompts
# ==============================================================================
-LOGIC_GRAPH_PROMPT = (
+_PROMPT = (
"You are a logical analyst. Extract the reasoning structure from the text into a directed graph.\n\n"
"Guidelines:\n"
"- Identify the main claims (conclusions) and the evidence or premises that lead to them.\n"
@@ -43,12 +43,12 @@ LOGIC_GRAPH_PROMPT = (
"- Do not just extract facts; extract the 'argument' and 'reasoning' flow."
)
-LOGIC_GRAPH_NODE_PROMPT = (
+_NODE_PROMPT = (
"Extract the individual building blocks of the argument. Identify core claims, supporting evidence, "
"and underlying premises. For each, determine its type and note any source attribution mentioned."
)
-LOGIC_GRAPH_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"Map the logical flow between the extracted claims and evidence. Focus on how statements "
"Support, Contradict, or Lead to one another. Ensure every edge represents a step in the reasoning chain."
)
@@ -120,9 +120,9 @@ class LogicGraph(AutoGraph[LogicNode, LogicRelation]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=LOGIC_GRAPH_PROMPT,
- prompt_for_node_extraction=LOGIC_GRAPH_NODE_PROMPT,
- prompt_for_edge_extraction=LOGIC_GRAPH_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs,
)
diff --git a/hyperextract/templates/zh/agriculture/crop_cycle.py b/hyperextract/templates/zh/agriculture/crop_cycle.py
index 04ee2d2..2d79d23 100644
--- a/hyperextract/templates/zh/agriculture/crop_cycle.py
+++ b/hyperextract/templates/zh/agriculture/crop_cycle.py
@@ -29,7 +29,7 @@ class AgriRelation(BaseModel):
# 2. 提示词 (Prompts)
# ==============================================================================
-CROP_CYCLE_PROMPT = (
+_PROMPT = (
"你是一位资深农艺师。请从文本中提取作物生长与管理图谱。\n\n"
"提取指南:\n"
"- 识别作物及其具体的生长阶段(如:播种、开花、成熟)。\n"
@@ -37,7 +37,7 @@ CROP_CYCLE_PROMPT = (
"- 记录任何提及的威胁因素(如病虫害)及其对作物的影响。"
)
-CROP_CYCLE_NODE_PROMPT = (
+_NODE_PROMPT = (
"你是一位资深农艺师。你的任务是从文本中识别并提取所有关键农业实体(节点)。\n\n"
"提取规则:\n"
"- 识别作物类型、具体生长阶段、环境因子(如 pH 值、温度)以及农事任务。\n"
@@ -46,7 +46,7 @@ CROP_CYCLE_NODE_PROMPT = (
"- 在此阶段请勿识别这些实体之间的逻辑顺序或依赖关系。"
)
-CROP_CYCLE_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"你是一位资深农艺师。根据农业实体清单,映射其中的逻辑链路和周期关系(边)。\n\n"
"提取规则:\n"
"- 在生长阶段之间建立顺序链接。\n"
@@ -113,9 +113,9 @@ class CropCycleGraph(AutoGraph[AgriEntity, AgriRelation]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=CROP_CYCLE_PROMPT,
- prompt_for_node_extraction=CROP_CYCLE_NODE_PROMPT,
- prompt_for_edge_extraction=CROP_CYCLE_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs
)
def show(
diff --git a/hyperextract/templates/zh/agriculture/livestock.py b/hyperextract/templates/zh/agriculture/livestock.py
index 8a0d8fd..7be5133 100644
--- a/hyperextract/templates/zh/agriculture/livestock.py
+++ b/hyperextract/templates/zh/agriculture/livestock.py
@@ -34,7 +34,7 @@ class BreedingRelation(BaseModel):
# 2. 提示词 (Prompts)
# ==============================================================================
-LIVESTOCK_GRAPH_PROMPT = (
+_PROMPT = (
"你是一位畜牧专家和遗传学家。请从文本中提取育种与健康管理图谱。\n\n"
"提取指南:\n"
"- 识别动物个体及其品种。\n"
@@ -42,9 +42,9 @@ LIVESTOCK_GRAPH_PROMPT = (
"- 将动物与其健康状况、疫苗接种和营养记录关联起来。"
)
-LIVESTOCK_NODE_PROMPT = "请提取畜牧实体:识别特定动物(通过ID或名称)、品种、健康状况、疫苗类型以及特定的饲料。为每一项提供相关的特征或指标。"
+_NODE_PROMPT = "请提取畜牧实体:识别特定动物(通过ID或名称)、品种、健康状况、疫苗类型以及特定的饲料。为每一项提供相关的特征或指标。"
-LIVESTOCK_EDGE_PROMPT = "逻辑化地连接畜牧实体。映射家族树(亲缘链接)、育种历史以及医疗/营养事件。确保准确使用'与...交配'或'饲喂'等关系类型。"
+_EDGE_PROMPT = "逻辑化地连接畜牧实体。映射家族树(亲缘链接)、育种历史以及医疗/营养事件。确保准确使用'与...交配'或'饲喂'等关系类型。"
# ==============================================================================
# 3. 模板类 (Template Class)
@@ -107,9 +107,9 @@ class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=LIVESTOCK_GRAPH_PROMPT,
- prompt_for_node_extraction=LIVESTOCK_NODE_PROMPT,
- prompt_for_edge_extraction=LIVESTOCK_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs,
)
diff --git a/hyperextract/templates/zh/agriculture/pest_control.py b/hyperextract/templates/zh/agriculture/pest_control.py
index ddb6b8d..744b15d 100644
--- a/hyperextract/templates/zh/agriculture/pest_control.py
+++ b/hyperextract/templates/zh/agriculture/pest_control.py
@@ -38,7 +38,7 @@ class AgriPestRelation(BaseModel):
# 2. 提示词 (Prompt)
# ==============================================================================
-_TEMPLATE_PROMPT = """
+_PROMPT = """
你是一位资深农艺师和植物保护专家。
你的任务是从文本中提取详尽的农作物病虫害及其防治知识图谱。
@@ -87,7 +87,7 @@ class AgriPestControl(AutoGraph[AgriPestEntity, AgriPestRelation]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=_TEMPLATE_PROMPT,
+ prompt=_PROMPT,
**kwargs,
)
diff --git a/hyperextract/templates/zh/biology/metabolic.py b/hyperextract/templates/zh/biology/metabolic.py
index e9a9b6e..2d1108e 100644
--- a/hyperextract/templates/zh/biology/metabolic.py
+++ b/hyperextract/templates/zh/biology/metabolic.py
@@ -32,7 +32,7 @@ class MetabolicReactionHyperedge(BaseModel):
# 2. Prompts
# ==============================================================================
-METABOLIC_CONSOLIDATED_PROMPT = (
+_PROMPT = (
"你是一位擅长代谢工程的生物化学家。请提取复杂的 N 元反应。\n\n"
"规则:\n"
"- 将所有参与者(底物、产物和酶)归为一个超边(Hyperedge)。\n"
@@ -40,7 +40,7 @@ METABOLIC_CONSOLIDATED_PROMPT = (
"- 将催化酶作为超边参与者的一部分进行捕获。"
)
-METABOLIC_NODE_PROMPT = (
+_NODE_PROMPT = (
"你是一位生物化学家。你的任务是识别代谢过程中涉及的所有代谢物和催化酶(节点)。\n\n"
"提取规则:\n"
"- 识别化学组分(底物/产物)以及促进其转化的酶。\n"
@@ -49,7 +49,7 @@ METABOLIC_NODE_PROMPT = (
"- 在此阶段请勿构建反应方程式或复合物。"
)
-METABOLIC_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"你是一位生物化学家。根据以下代谢物和酶的清单,提取复杂的代谢反应(超边)。\n\n"
"提取规则:\n"
"- 将所有参与者(底物、产物和酶)归入单个反应事件中。\n"
@@ -91,9 +91,9 @@ class MetabolicHypergraph(AutoHypergraph[MetaboliteNode, MetabolicReactionHypere
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=METABOLIC_CONSOLIDATED_PROMPT,
- prompt_for_node_extraction=METABOLIC_NODE_PROMPT,
- prompt_for_edge_extraction=METABOLIC_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs
)
def show(
diff --git a/hyperextract/templates/zh/biology/network.py b/hyperextract/templates/zh/biology/network.py
index c882b5e..7a96d31 100644
--- a/hyperextract/templates/zh/biology/network.py
+++ b/hyperextract/templates/zh/biology/network.py
@@ -31,7 +31,7 @@ class BioInteractionEdge(BaseModel):
# 2. Prompts
# ==============================================================================
-NETWORK_CONSOLIDATED_PROMPT = (
+_PROMPT = (
"你是一位擅长分子信号转导和调节网络的生物信息学专家。"
"请从文本中提取相互作用,以构建生物网络图。\n\n"
"规则:\n"
@@ -40,7 +40,7 @@ NETWORK_CONSOLIDATED_PROMPT = (
"- 捕捉每条边具体的生化机制。"
)
-NETWORK_NODE_PROMPT = (
+_NODE_PROMPT = (
"你是一位生物信息学专家。你的任务是识别出文本中提及的所有分子实体(节点)。\n\n"
"提取规则:\n"
"- 识别基因、蛋白质、RNA 和代谢物。使用标准命名法(如:HGNC 符号)。\n"
@@ -49,7 +49,7 @@ NETWORK_NODE_PROMPT = (
"- 在此阶段请勿提取相互作用或状态变化。"
)
-NETWORK_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"你是一位生物信息学专家。根据以下分子实体清单,提取它们之间的物理和功能相互作用(边)。\n\n"
"提取规则:\n"
"- 识别相互作用的类型(磷酸化、抑制、激活、结合等)。\n"
@@ -91,9 +91,9 @@ class BiologicalNetwork(AutoGraph[BioEntityNode, BioInteractionEdge]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=NETWORK_CONSOLIDATED_PROMPT,
- prompt_for_node_extraction=NETWORK_NODE_PROMPT,
- prompt_for_edge_extraction=NETWORK_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs
)
def show(
diff --git a/hyperextract/templates/zh/biology/taxonomy.py b/hyperextract/templates/zh/biology/taxonomy.py
index 85d91d7..3ddcf9d 100644
--- a/hyperextract/templates/zh/biology/taxonomy.py
+++ b/hyperextract/templates/zh/biology/taxonomy.py
@@ -30,7 +30,7 @@ class TaxonomyRelation(BaseModel):
# 2. Prompts
# ==============================================================================
-TAXONOMY_CONSOLIDATED_PROMPT = (
+_PROMPT = (
"你是一位专业的分类学家和系统生物学家。请从文本中提取生物层级(分类学)信息。\n\n"
"规则:\n"
"- 识别所有分类阶元(从界到种)及其特定的等级。\n"
@@ -38,7 +38,7 @@ TAXONOMY_CONSOLIDATED_PROMPT = (
"- 捕捉可用的学名和常用名。"
)
-TAXONOMY_NODE_PROMPT = (
+_NODE_PROMPT = (
"你是一位专业的分类学家。你的任务是从文本中识别并提取所有生物分类单元(节点)。\n\n"
"提取规则:\n"
"- 为每个分类单元识别其学名和指定的等级(如:域、界、门、纲、目、科、属、种)。\n"
@@ -47,7 +47,7 @@ TAXONOMY_NODE_PROMPT = (
"- 在此阶段请勿提取分类单元之间的关系。"
)
-TAXONOMY_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"你是一位专业的分类学家。根据以下已识别分类单元的清单,提取文本中描述的层级关系(边)。\n\n"
"提取规则:\n"
"- 在高层级分类单元包含低层级分类单元时建立 'parent_of' 链接。\n"
@@ -89,9 +89,9 @@ class TaxonomyGraph(AutoGraph[TaxonNode, TaxonomyRelation]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=TAXONOMY_CONSOLIDATED_PROMPT,
- prompt_for_node_extraction=TAXONOMY_NODE_PROMPT,
- prompt_for_edge_extraction=TAXONOMY_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs
)
def show(
diff --git a/hyperextract/templates/zh/chemistry/molecular.py b/hyperextract/templates/zh/chemistry/molecular.py
index bf67105..679397b 100644
--- a/hyperextract/templates/zh/chemistry/molecular.py
+++ b/hyperextract/templates/zh/chemistry/molecular.py
@@ -31,7 +31,7 @@ class ChemicalBond(BaseModel):
# 2. Prompts
# ==============================================================================
-MOLECULAR_CONSOLIDATED_PROMPT = (
+_PROMPT = (
"你是一位计算化学家和晶体学家。请提取 3D 分子拓扑结构。\n\n"
"规则:\n"
"- 将每个原子识别为一个节点。\n"
@@ -39,7 +39,7 @@ MOLECULAR_CONSOLIDATED_PROMPT = (
"- 捕获每个原子的形式电荷和杂化轨道。"
)
-MOLECULAR_NODE_PROMPT = (
+_NODE_PROMPT = (
"你是一位计算化学家。你的任务是从分子结构中识别并提取所有单个原子(节点)。\n\n"
"提取规则:\n"
"- 识别唯一的原子标识符(如:C1)及其化学元素符号。\n"
@@ -48,7 +48,7 @@ MOLECULAR_NODE_PROMPT = (
"- 在此阶段请勿识别化学键或空间连接性。"
)
-MOLECULAR_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"你是一位计算化学家。根据原子清单,映射化学键和空间连接性(边)。\n\n"
"提取规则:\n"
"- 定义源原子与目标原子之间的化学键类型(单键、双键、芳香键等)。\n"
@@ -91,9 +91,9 @@ class MolecularStructureGraph(AutoSpatialGraph[AtomNode, ChemicalBond]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=MOLECULAR_CONSOLIDATED_PROMPT,
- prompt_for_node_extraction=MOLECULAR_NODE_PROMPT,
- prompt_for_edge_extraction=MOLECULAR_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs
)
def show(
diff --git a/hyperextract/templates/zh/chemistry/protocol.py b/hyperextract/templates/zh/chemistry/protocol.py
index 5b92258..45d2a45 100644
--- a/hyperextract/templates/zh/chemistry/protocol.py
+++ b/hyperextract/templates/zh/chemistry/protocol.py
@@ -32,7 +32,7 @@ class ProtocolTransition(BaseModel):
# 2. Prompts
# ==============================================================================
-PROTOCOL_CONSOLIDATED_PROMPT = (
+_PROMPT = (
"你是一位擅长实验方案记录的实验室技术员。请提取顺序性的实验步骤。\n\n"
"规则:\n"
"- 将每个操作表示为一个节点(Node)。\n"
@@ -41,7 +41,7 @@ PROTOCOL_CONSOLIDATED_PROMPT = (
"- 精确映射时间线(例如:'步骤 1' -> '步骤 2')。"
)
-PROTOCOL_NODE_PROMPT = (
+_NODE_PROMPT = (
"你是一位实验室技术员。你的任务是识别出单个实验方案操作(节点)。\n\n"
"提取规则:\n"
"- 识别离散的动作(如:离心、孵育、滴定)。\n"
@@ -50,7 +50,7 @@ PROTOCOL_NODE_PROMPT = (
"- 在此阶段请勿建立步骤之间的顺序或时间关系。"
)
-PROTOCOL_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"你是一位实验室技术员。根据实验室操作清单,提取顺序流向(边)。\n\n"
"提取规则:\n"
"- 按时间顺序将源步骤连接到目标步骤。\n"
@@ -93,9 +93,9 @@ class LabProtocolTemporal(AutoTemporalGraph[LabOperation, ProtocolTransition]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=PROTOCOL_CONSOLIDATED_PROMPT,
- prompt_for_node_extraction=PROTOCOL_NODE_PROMPT,
- prompt_for_edge_extraction=PROTOCOL_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs
)
def show(
diff --git a/hyperextract/templates/zh/chemistry/reaction.py b/hyperextract/templates/zh/chemistry/reaction.py
index ec1fe65..4c21603 100644
--- a/hyperextract/templates/zh/chemistry/reaction.py
+++ b/hyperextract/templates/zh/chemistry/reaction.py
@@ -34,7 +34,7 @@ class ReactionEvent(BaseModel):
# 2. Prompts
# ==============================================================================
-REACTION_CONSOLIDATED_PROMPT = (
+_PROMPT = (
"你是一位专业的有机和无机化学家。请提取多组分的反应事件。\n\n"
"规则:\n"
"- 将每个反应表示为一个超边(Hyperedge),连接所有反应物、产物和催化剂。\n"
@@ -42,7 +42,7 @@ REACTION_CONSOLIDATED_PROMPT = (
"- 在反应语境中正确识别每个化学实体的角色。"
)
-REACTION_NODE_PROMPT = (
+_NODE_PROMPT = (
"你是一位有机化学家。你的任务是识别出文本中提及的所有化学实体(节点)。\n\n"
"提取规则:\n"
"- 识别反应试剂、产物、催化剂和溶剂。\n"
@@ -51,7 +51,7 @@ REACTION_NODE_PROMPT = (
"- 在此阶段请勿构建反应序列或对参与者进行分组。"
)
-REACTION_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"你是一位有机化学家。根据化学实体清单,提取多组分反应事件(超边)。\n\n"
"提取规则:\n"
"- 将所有参与者(反应物、产物、催化剂、溶剂)归入单个反应超边中。\n"
@@ -93,9 +93,9 @@ class ChemicalReactionHyper(AutoHypergraph[ChemicalEntity, ReactionEvent]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=REACTION_CONSOLIDATED_PROMPT,
- prompt_for_node_extraction=REACTION_NODE_PROMPT,
- prompt_for_edge_extraction=REACTION_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs
)
def show(
diff --git a/hyperextract/templates/zh/education/academic_lexicon.py b/hyperextract/templates/zh/education/academic_lexicon.py
index 1bb0795..45f563f 100644
--- a/hyperextract/templates/zh/education/academic_lexicon.py
+++ b/hyperextract/templates/zh/education/academic_lexicon.py
@@ -33,7 +33,7 @@ class AcademicTerm(BaseModel):
# 2. Prompts 提示词
# ==============================================================================
-ACADEMIC_LEXICON_PROMPT = (
+_PROMPT = (
"你是一位学术百科全书编辑和词典编纂者。你的目标是提取并标准化学术定义。\n\n"
"提取规则:\n"
"- 识别唯一的学术术语及其高度精确的定义。\n"
@@ -92,7 +92,7 @@ class AcademicLexiconSet(AutoSet[AcademicTerm]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=ACADEMIC_LEXICON_PROMPT,
+ prompt=_PROMPT,
**kwargs,
)
def show(
diff --git a/hyperextract/templates/zh/education/interdisciplinary_nexus.py b/hyperextract/templates/zh/education/interdisciplinary_nexus.py
index 2c70524..2205b73 100644
--- a/hyperextract/templates/zh/education/interdisciplinary_nexus.py
+++ b/hyperextract/templates/zh/education/interdisciplinary_nexus.py
@@ -33,7 +33,7 @@ class InterdisciplinaryEdge(BaseModel):
# 2. Prompts 提示词
# ==============================================================================
-NEXUS_CONSOLIDATED_PROMPT = (
+_PROMPT = (
"你是一位通才和跨学科研究专家。请识别不同学术领域概念之间的深层联系。\n\n"
"提取规则:\n"
"- 识别核心概念作为节点。\n"
@@ -41,14 +41,14 @@ NEXUS_CONSOLIDATED_PROMPT = (
"- 专注于发现令人惊讶但科学有效的桥梁连接(例如:通过博弈论连接生物学和经济学)。"
)
-NEXUS_NODE_PROMPT = (
+_NODE_PROMPT = (
"识别具有跨学科潜力的基础学术概念。\n\n"
"提取规则:\n"
"- 提取对各自领域至关重要的名词/概念。\n"
"- 标注其学科来源。"
)
-NEXUS_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"识别连接一组概念的“纽带”或称之为超边。\n\n"
"提取规则:\n"
"- 只要可能,一个超边应涉及两个以上的节点。\n"
@@ -111,9 +111,9 @@ class InterdisciplinaryNexusHypergraph(AutoHypergraph[ConceptNode, Interdiscipli
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=NEXUS_CONSOLIDATED_PROMPT,
- prompt_for_node_extraction=NEXUS_NODE_PROMPT,
- prompt_for_edge_extraction=NEXUS_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs,
)
def show(
diff --git a/hyperextract/templates/zh/education/prerequisite_map.py b/hyperextract/templates/zh/education/prerequisite_map.py
index 7b1eab0..826435c 100644
--- a/hyperextract/templates/zh/education/prerequisite_map.py
+++ b/hyperextract/templates/zh/education/prerequisite_map.py
@@ -43,7 +43,7 @@ class PrerequisiteRelation(BaseModel):
# 2. Prompts 提示词
# ==============================================================================
-EDUCATION_CONSOLIDATED_PROMPT = (
+_PROMPT = (
"你是一位资深课程架构师和教育心理学家。请从文本中提取知识点的逻辑结构。\n\n"
"提取规则:\n"
"- 识别构成学习路径的原子化概念。\n"
@@ -51,7 +51,7 @@ EDUCATION_CONSOLIDATED_PROMPT = (
"- 确保生成的图谱符合科学的教学演进逻辑。"
)
-EDUCATION_NODE_PROMPT = (
+_NODE_PROMPT = (
"你是一位擅长知识拆解的教育心理学家。你的任务是识别所有离散的知识点(节点)。\n\n"
"提取规则:\n"
"- 关注代表特定学术概念、公式或方法的名词或名词短语。\n"
@@ -59,7 +59,7 @@ EDUCATION_NODE_PROMPT = (
"- 此阶段不要识别关系或依赖。"
)
-EDUCATION_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"你是一位课程设计师。根据已识别的知识点,映射先修关系(边)。\n\n"
"提取规则:\n"
"- 确定概念 A 是否是学习概念 B 的必要前提。\n"
@@ -125,9 +125,9 @@ class PrerequisiteMapGraph(AutoGraph[KnowledgePointNode, PrerequisiteRelation]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=EDUCATION_CONSOLIDATED_PROMPT,
- prompt_for_node_extraction=EDUCATION_NODE_PROMPT,
- prompt_for_edge_extraction=EDUCATION_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs,
)
def show(
diff --git a/hyperextract/templates/zh/environment/__init__.py b/hyperextract/templates/zh/environment/__init__.py
index e69de29..3af7f41 100644
--- a/hyperextract/templates/zh/environment/__init__.py
+++ b/hyperextract/templates/zh/environment/__init__.py
@@ -0,0 +1,11 @@
+"""环境领域模板,用于生态和环保分析。"""
+
+from .species_interaction import SpeciesInteractionNetwork
+from .pollutant_impact import PollutantImpactMap
+from .endangered_species import EndangeredSpeciesList
+
+__all__ = [
+ "SpeciesInteractionNetwork",
+ "PollutantImpactMap",
+ "EndangeredSpeciesList",
+]
diff --git a/hyperextract/templates/zh/environment/endangered_species.py b/hyperextract/templates/zh/environment/endangered_species.py
new file mode 100644
index 0000000..fd6c032
--- /dev/null
+++ b/hyperextract/templates/zh/environment/endangered_species.py
@@ -0,0 +1,126 @@
+from typing import Optional, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types.set import AutoSet
+
+# ==============================================================================
+# 1. Schema 定义
+# ==============================================================================
+
+
+class SpeciesStatus(BaseModel):
+ """物种的保护和濒危状态。"""
+
+ name: str = Field(description="物种的学名或常用名。")
+ endangered_level: str = Field(
+ description="保护状态:'Extinct'(灭绝), 'Extinct in the Wild'(野外灭绝), 'Critically Endangered'(极危), 'Endangered'(濒危), 'Vulnerable'(易危), 'Near Threatened'(近危), 'Least Concern'(无危)。"
+ )
+ main_threats: Optional[str] = Field(
+ None,
+ description="物种面临的主要威胁(如'habitat loss'(栖息地丧失), 'poaching'(偷猎), 'climate change'(气候变化), 'pollution'(污染))。"
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = """
+你是一位保护生物学和野生动物保护专家。
+你的任务是从保护报告、IUCN红色名录摘要或生物多样性评估中提取濒危物种的信息。
+
+指导原则:
+1. 识别文本中提到的所有物种及其保护或濒危状态。
+2. 对于每个物种,根据标准保护等级进行分类:灭绝、野外灭绝、极危、濒危、易危、近危或无危。
+3. 提取危害物种的主要威胁(栖息地丧失、偷猎、气候变化、疾病、污染等)。
+4. 确保物种名称和分类的科学准确性。
+5. 避免重复:如果同一物种多次出现且状态和威胁相同,应合并为一个条目。
+
+输出格式:
+- 每个物种应该有名称、濒危等级和主要威胁。
+- 将同一物种的多个提及合并为一个综合条目。
+"""
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class EndangeredSpeciesList(AutoSet[SpeciesStatus]):
+ """
+ 濒危和受威胁物种文档的唯一集合模板。
+
+ 将保护评估和生物多样性报告转化为一个去重的物种清单,
+ 包含其濒危状态和主要威胁,支持保护优先级设定和资源配置。
+
+ Example:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4")
+ >>> embedder = OpenAIEmbeddings()
+ >>>
+ >>> endangered_list = EndangeredSpeciesList(llm_client=llm, embedder=embedder)
+ >>> text = "大熊猫(易危)面临栖息地丧失。爪哇犀牛(极危)受到偷猎威胁。"
+ >>> endangered_list.feed_text(text)
+ >>> endangered_list.show() # 显示去重的濒危物种
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """初始化濒危物种清单模板。
+
+ Args:
+ llm_client (BaseChatModel):用于提取物种和威胁信息的语言模型客户端。
+ embedder (Embeddings):用于物种去重和威胁描述索引的嵌入模型。
+ chunk_size (int, optional):每个文本块的最大字符数。默认为 2048。
+ chunk_overlap (int, optional):块之间的重叠字符数,用于保持上下文连贯性。默认为 256。
+ max_workers (int, optional):并发提取的最大工作进程数。默认为 10。
+ verbose (bool, optional):如果为 True,则打印详细的提取和去重进度日志。默认为 False。
+ **kwargs:传递给 AutoSet 基类的参数,用于控制去重行为。
+ """
+ super().__init__(
+ item_schema=SpeciesStatus,
+ key_extractor=lambda x: x.name.strip().lower(),
+ llm_client=llm_client,
+ embedder=embedder,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ prompt=_PROMPT,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 3,
+ top_k_for_chat: int = 3,
+ ) -> None:
+ """可视化濒危物种清单用于保护规划。
+
+ 使用 OntoSight 展示去重的唯一物种集合,包含濒危等级和威胁信息。
+ 在内部定义物种的前端展示标签(名称 + 濒危等级,用于保护优先级可视化)。
+
+ Args:
+ top_k_for_search (int, optional):搜索触发时从去重集合中检索的物种数量。默认为 3。
+ top_k_for_chat (int, optional):聊天触发时从去重集合中检索的物种数量。默认为 3。
+ """
+
+ def item_label_extractor(item: SpeciesStatus) -> str:
+ return f"{item.name} - {item.endangered_level}"
+
+ super().show(
+ item_label_extractor=item_label_extractor,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/zh/environment/pollutant_impact.py b/hyperextract/templates/zh/environment/pollutant_impact.py
new file mode 100644
index 0000000..839de18
--- /dev/null
+++ b/hyperextract/templates/zh/environment/pollutant_impact.py
@@ -0,0 +1,191 @@
+from typing import Optional, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types.graph import AutoGraph
+
+# ==============================================================================
+# 1. Schema 定义
+# ==============================================================================
+
+
+class EnvironmentalEntity(BaseModel):
+ """环境污染领域中的实体。"""
+
+ name: str = Field(description="污染物、污染源或受影响实体的名称。")
+ entity_type: str = Field(
+ description="实体类型:'Pollutant'(污染物-化学物质、颗粒等), 'Source'(源头-工厂、车辆等), 'Target'(受体-水体、空气、土壤、生物)。"
+ )
+ description: Optional[str] = Field(
+ None, description="额外信息,如化学性质、位置或特征。"
+ )
+
+
+class PollutantImpact(BaseModel):
+ """污染物或污染源与受影响实体之间的影响关系。"""
+
+ source: str = Field(description="污染物或污染源。")
+ target: str = Field(description="受影响的实体(生态系统、生物、地点)。")
+ impact_type: str = Field(
+ description="影响类型:'bioaccumulation'(生物富集), 'toxicity'(毒性), 'contamination'(污染), 'ecosystem damage'(生态破坏), 'health effect'(健康影响)。"
+ )
+ severity: Optional[str] = Field(
+ None, description="严重程度:'critical'(严重), 'high'(较高), 'moderate'(中等), 'low'(轻微)。如果有,包含定量数据。"
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = """
+你是一位环境科学家,专长于污染评估和生态影响分析。
+你的任务是从报告、监测数据和新闻文章中提取污染源、污染物及其环保影响。
+
+指导原则:
+1. 识别文本中提到的所有污染物(如汞、PM2.5、塑料、二氧化碳等)。
+2. 识别污染源(工厂、车辆、农业径流等)和受影响的对象(河流、空气、土壤、人口、野生动物)。
+3. 提取因果关系:哪种污染物影响了哪个实体以及如何影响。
+4. 记录严重程度或定量影响信息(如"50毫克/升浓度"、"污染等级为严重")。
+5. 精确表示污染流向:从污染源指向受体。
+
+输出格式:
+- 污染物和受影响的实体应该是不同的节点。
+- 影响应该有明确的源头(污染物/污染源)、目标(受体)、影响类型和严重程度(如果有)。
+"""
+
+_NODE_PROMPT = """
+你是一位专注于污染评估的环境科学家。
+你的任务是在第一个提取阶段只提取环境实体(污染物、污染源、受体),不提取污染影响。
+专注于找到所有实体。
+
+指导原则:
+1. 识别提到的所有污染物(化学物质、颗粒、化合物)。
+2. 识别所有污染源(工厂、车辆、场所)。
+3. 识别所有受体目标(水体、生物体、人口、生态系统)。
+4. 对于每个实体,捕获:名称、实体_类型,以及任何相关特征。
+5. 避免重复:整合对同一实体的引用。
+
+输出格式:
+- 每个实体应为不同的节点,包含名称、类型(污染物/污染源/受体)和描述。
+"""
+
+_EDGE_PROMPT = """
+你是一位分析污染影响的环境科学家。
+你的任务是在第二个提取阶段只提取已给定实体间的因果关系。
+你将获得环境实体(节点)列表。你的工作是识别它们之间的污染影响关系。
+
+指导原则:
+1. 根据确认的实体列表,找出文本中的所有污染影响关系。
+2. 对于每个影响,捕获:源(污染物/污染源实体)、目标(受影响实体)、影响_类型和严重程度。
+3. 保留方向性:污染物从污染源流向目标。
+4. 仅提取给定实体间的影响;忽略独立的实体提及。
+5. 包括定量测量(浓度、严重程度)如有。
+
+输出格式:
+- 每个影响是一条边:源 → 目标,包含影响_类型和严重程度。
+"""
+
+# ==============================================================================
+# 3. 模板类
+# =============================================================================="
+
+
+class PollutantImpactMap(AutoGraph[EnvironmentalEntity, PollutantImpact]):
+ """
+ 环境污染追踪与影响评估知识图谱模板。
+
+ 将环境监测报告和可持续性分析转化为结构化的污染源-受体关系,
+ 用于环保健康风险分析。
+
+ Example:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4")
+ >>> embedder = OpenAIEmbeddings()
+ >>>
+ >>> pollutant_map = PollutantImpactMap(llm_client=llm, embedder=embedder)
+ >>> text = "工厂排放的汞污染了河流,导致鱼类受到严重毒性影响。"
+ >>> pollutant_map.feed_text(text)
+ >>> pollutant_map.show() # 可视化污染物影响及严重程度
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "one_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """初始化污染物影响图模板。
+
+ Args:
+ llm_client (BaseChatModel):用于提取污染物和影响信息的语言模型客户端。
+ embedder (Embeddings):用于索引污染物、污染源和受影响对象的嵌入模型。
+ extraction_mode (str, optional):提取策略。默认为 "one_stage"。
+ - "one_stage":同时提取污染物和影响(更快)。
+ - "two_stage":先提取污染物,再提取影响(准确度更高)。
+ chunk_size (int, optional):每个文本块的最大字符数。默认为 2048。
+ chunk_overlap (int, optional):块之间的重叠字符数,用于保持上下文连贯性。默认为 256。
+ max_workers (int, optional):用于并行处理的最大并发提取工作进程数。默认为 10。
+ verbose (bool, optional):如果为 True,则打印详细的提取进度和污染物追踪日志。默认为 False。
+ **kwargs:传递给 AutoGraph 基类的其他参数。
+ """
+ super().__init__(
+ node_schema=EnvironmentalEntity,
+ edge_schema=PollutantImpact,
+ node_key_extractor=lambda x: x.name.strip(),
+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.impact_type.lower()})-->{x.target.strip()}",
+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),
+ llm_client=llm_client,
+ embedder=embedder,
+ extraction_mode=extraction_mode,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_nodes_for_search: int = 3,
+ top_k_edges_for_search: int = 3,
+ top_k_nodes_for_chat: int = 3,
+ top_k_edges_for_chat: int = 3,
+ ) -> None:
+ """可视化污染物影响网络用于环境评估。
+
+ 使用 OntoSight 展示污染源、污染物及受影响对象和严重程度信息。
+ 在内部定义实体的前端展示标签(名称 + 实体类型)和影响标签(影响类型 + 严重程度)。
+
+ Args:
+ top_k_nodes_for_search (int, optional):搜索触发时要检索的环境实体(污染物/污染源/受体)数量。默认为 3。
+ top_k_edges_for_search (int, optional):搜索触发时要检索的影响关系数。默认为 3。
+ top_k_nodes_for_chat (int, optional):聊天触发时要检索的环境实体数量。默认为 3。
+ top_k_edges_for_chat (int, optional):聊天触发时要检索的影响关系数。默认为 3。
+ """
+
+ def node_label_extractor(node: EnvironmentalEntity) -> str:
+ return f"{node.name} ({node.entity_type})"
+
+ def edge_label_extractor(edge: PollutantImpact) -> str:
+ severity = f" [{edge.severity}]" if edge.severity else ""
+ return f"{edge.impact_type}{severity}"
+
+ super().show(
+ node_label_extractor=node_label_extractor,
+ edge_label_extractor=edge_label_extractor,
+ top_k_nodes_for_search=top_k_nodes_for_search,
+ top_k_edges_for_search=top_k_edges_for_search,
+ top_k_nodes_for_chat=top_k_nodes_for_chat,
+ top_k_edges_for_chat=top_k_edges_for_chat,
+ )
diff --git a/hyperextract/templates/zh/environment/species_interaction.py b/hyperextract/templates/zh/environment/species_interaction.py
new file mode 100644
index 0000000..c545de7
--- /dev/null
+++ b/hyperextract/templates/zh/environment/species_interaction.py
@@ -0,0 +1,191 @@
+from typing import Optional, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types.graph import AutoGraph
+
+# ==============================================================================
+# 1. Schema 定义
+# ==============================================================================
+
+
+class Species(BaseModel):
+ """生态系统中的生物体。"""
+
+ name: str = Field(description="生物的学名或常用名。")
+ category: str = Field(
+ description="分类学分类:'Mammal'(哺乳动物), 'Bird'(鸟类), 'Insect'(昆虫), 'Plant'(植物), 'Microorganism'(微生物)等。"
+ )
+ protection_level: Optional[str] = Field(
+ None, description="保护等级:'Endangered'(濒危), 'Vulnerable'(易危), 'Least Concern'(无危)等。"
+ )
+
+
+class Interaction(BaseModel):
+ """两个物种之间的生物互作关系。"""
+
+ source: str = Field(description="初始物种(捕食者、竞争者等)。")
+ target: str = Field(description="接收物种(猎物、竞争者、寄主等)。")
+ interaction_type: str = Field(
+ description="互作类型:'predation'(捕食), 'parasitism'(寄生), 'mutualism'(互利共生), 'commensalism'(偏利共生), 'competition'(竞争), 'symbiosis'(共生)。"
+ )
+ detail: Optional[str] = Field(
+ None, description="互作的具体细节(如频率、季节性规律、生态影响等)。"
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = """
+你是一位生态学和生物多样性专家。
+你的任务是从科学文献、野外调查报告或自然纪录片中提取生物互作网络。
+
+指导原则:
+1. 识别文本中提到的所有生物,并按类别分类(物种类型)。
+2. 提取生物之间的关系(捕食、寄生、竞争、互利共生等)。
+3. 对于每个互作,捕捉互作类型和具体的生态学细节(时间、频率、条件)。
+4. 保持互作的方向性:例如"狮子捕食斑马"和"斑马躲避狮子"是不同的。
+5. 如果提到了保护等级信息的,要进行记录。
+
+输出格式:
+- 每个物种应该是一个独立的实体,包括名称、类别和保护等级(如果有)。
+- 每个互作应该清楚地表示源头(发起方生物)、目标(接收方生物)和互作类型。
+"""
+
+_NODE_PROMPT = """
+你是一位生态学和生物多样性专家。
+你的任务是在第一个提取阶段只提取文本中的物种和生物体,不提取它们之间的互作。
+专注于识别文本中提到的所有不同生物体。
+
+指导原则:
+1. 列出文本中提到的所有物种、生物体或种群。
+2. 对于每个生物体,捕获:名称、分类(例如捕食者、猎物、植物、分解者)、以及保护状态(如有)。
+3. 避免重复:如果"狮子"和"非洲狮"指的是同一物种,统一为最具体的名称。
+4. 忽略模糊的指代;仅提取明确提到的生物体。
+
+输出格式:
+- 每个生物体应为不同的节点,具有清晰的名称、分类和状态。
+"""
+
+_EDGE_PROMPT = """
+你是一位分析物种互作的生态学家。
+你的任务是在第二个提取阶段只提取已给定物种间的生物关系。
+你将获得一份已提取物种(节点)的列表。你的工作是识别它们之间的互作。
+
+指导原则:
+1. 根据确认的物种列表,找出文本中提到的所有两两互作关系。
+2. 对于每个互作,捕获:源物种、目标物种、互作类型(捕食、共生、竞争等)和详细信息。
+3. 保留方向性:"A 捕食 B" 是捕食(A→B),不同于 "B 躲避 A"。
+4. 仅提取连接已给定物种的互作;忽略不在提供列表中的物种提及。
+5. 包括生态学背景(季节性、频率、条件)作为详细信息。
+
+输出格式:
+- 每个互作是一条边:源物种 → 目标物种,包含关系类型和详细信息。
+"""
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class SpeciesInteractionNetwork(AutoGraph[Species, Interaction]):
+ """
+ 物种生态互作知识图谱模板。
+
+ 将科学文献和野外研究转化为结构化的互作网络,
+ 使得生态系统生物多样性和食物链分析成为可能。
+
+ Example:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4")
+ >>> embedder = OpenAIEmbeddings()
+ >>>
+ >>> network = SpeciesInteractionNetwork(llm_client=llm, embedder=embedder)
+ >>> text = "狮子在非洲草原狩猎斑马。寄生蜂被鸟类捕食。"
+ >>> network.feed_text(text)
+ >>> network.show() # 可视化物种互作网络
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "one_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """初始化物种互作网络模板。
+
+ Args:
+ llm_client (BaseChatModel):用于物种和互作关系提取的语言模型客户端。
+ embedder (Embeddings):用于物种节点和互作边向量索引的嵌入模型。
+ extraction_mode (str, optional):提取策略。默认为 "one_stage"。
+ - "one_stage":同时提取物种和互作(更快)。
+ - "two_stage":先提取物种,再提取互作(准确度更高)。
+ chunk_size (int, optional):每个文本块的最大字符数。默认为 2048。
+ chunk_overlap (int, optional):块之间的重叠字符数,用于保持上下文连贯性。默认为 256。
+ max_workers (int, optional):并发提取的最大工作进程数。默认为 10。
+ verbose (bool, optional):如果为 True,则打印详细的提取进度日志。默认为 False。
+ **kwargs:传递给 AutoGraph 基类的其他参数。
+ """
+ super().__init__(
+ node_schema=Species,
+ edge_schema=Interaction,
+ node_key_extractor=lambda x: x.name.strip(),
+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.interaction_type.lower()})-->{x.target.strip()}",
+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),
+ llm_client=llm_client,
+ embedder=embedder,
+ extraction_mode=extraction_mode,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_nodes_for_search: int = 3,
+ top_k_edges_for_search: int = 3,
+ top_k_nodes_for_chat: int = 3,
+ top_k_edges_for_chat: int = 3,
+ ) -> None:
+ """可视化物种互作网络用于生态分析。
+
+ 使用 OntoSight 可视化已提取的物种(节点)及其互作关系(边)。
+ 在内部定义物种的前端展示标签(名称 + 类别 + 保护等级)
+ 和互作关系标签(互作类型)。
+
+ Args:
+ top_k_nodes_for_search (int, optional):搜索触发时要检索的物种节点数。默认为 3。
+ top_k_edges_for_search (int, optional):搜索触发时要检索的互作边数。默认为 3。
+ top_k_nodes_for_chat (int, optional):聊天触发时要检索的物种节点数。默认为 3。
+ top_k_edges_for_chat (int, optional):聊天触发时要检索的互作边数。默认为 3。
+ """
+
+ def node_label_extractor(node: Species) -> str:
+ status = f" [{node.protection_level}]" if node.protection_level else ""
+ return f"{node.name} ({node.category}){status}"
+
+ def edge_label_extractor(edge: Interaction) -> str:
+ return f"{edge.interaction_type}"
+
+ super().show(
+ node_label_extractor=node_label_extractor,
+ edge_label_extractor=edge_label_extractor,
+ top_k_nodes_for_search=top_k_nodes_for_search,
+ top_k_edges_for_search=top_k_edges_for_search,
+ top_k_nodes_for_chat=top_k_nodes_for_chat,
+ top_k_edges_for_chat=top_k_edges_for_chat,
+ )
diff --git a/hyperextract/templates/zh/general/concept_map.py b/hyperextract/templates/zh/general/concept_map.py
index 960bbc7..7ec411f 100644
--- a/hyperextract/templates/zh/general/concept_map.py
+++ b/hyperextract/templates/zh/general/concept_map.py
@@ -27,7 +27,7 @@ class ConceptRelation(BaseModel):
# 2. 提示词 (Prompts)
# ==============================================================================
-CONCEPT_MAP_PROMPT = (
+_PROMPT = (
"你是一位语义建模专家。请从文本中提取概念图(Concept Map),重点关注术语定义及其层级或关联关系。\n\n"
"提取指南:\n"
"- 识别核心术语,并基于文本提供精确定义。\n"
@@ -35,12 +35,12 @@ CONCEPT_MAP_PROMPT = (
"- 如果文本提到了说明性的示例,请一并捕获。"
)
-CONCEPT_MAP_NODE_PROMPT = (
+_NODE_PROMPT = (
"请从文本中提取所有基础概念和技术术语。对于每个概念,提供其术语名称、精确定义、关键属性列表,"
"以及文本中提到的任何具体示例。"
)
-CONCEPT_MAP_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"在提供的概念之间建立语义关系。重点关注层级分类(是一种、属于)以及功能性关联(用于、为...的实例)。"
"确保边逻辑上连接了已定义的各个概念。"
)
@@ -106,9 +106,9 @@ class ConceptMap(AutoGraph[Concept, ConceptRelation]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=CONCEPT_MAP_PROMPT,
- prompt_for_node_extraction=CONCEPT_MAP_NODE_PROMPT,
- prompt_for_edge_extraction=CONCEPT_MAP_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs
)
def show(
diff --git a/hyperextract/templates/zh/general/knowledge_graph.py b/hyperextract/templates/zh/general/knowledge_graph.py
index 0bde8f4..326f8f7 100644
--- a/hyperextract/templates/zh/general/knowledge_graph.py
+++ b/hyperextract/templates/zh/general/knowledge_graph.py
@@ -29,7 +29,7 @@ class Relation(BaseModel):
# 2. 提示词 (Prompts)
# ==============================================================================
-KNOWLEDGE_GRAPH_PROMPT = (
+_PROMPT = (
"你是一个专业的知识提取专家。你的任务是从提供的文本中提取一个事实知识图谱。"
"重点识别关键实体(人物、组织、地理位置、重要物体)以及它们之间明确的关系。\n\n"
"提取指南:\n"
@@ -38,12 +38,12 @@ KNOWLEDGE_GRAPH_PROMPT = (
"- 简洁性:使用清晰、简洁的语言进行描述和关系定义。"
)
-KNOWLEDGE_GRAPH_NODE_PROMPT = (
+_NODE_PROMPT = (
"请从文本中提取所有关键实体。重点识别人物、组织、地理位置以及重要的物体。"
"为每个实体提供名称、类别以及简明扼要的描述。"
)
-KNOWLEDGE_GRAPH_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"基于文本识别以下已知实体之间的事实关系。重点关注如“任职于”、“位于”、“创立”或“收购”等互动。"
"请勿虚构不在列表中的实体。"
)
@@ -109,9 +109,9 @@ class KnowledgeGraph(AutoGraph[Entity, Relation]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=KNOWLEDGE_GRAPH_PROMPT,
- prompt_for_node_extraction=KNOWLEDGE_GRAPH_NODE_PROMPT,
- prompt_for_edge_extraction=KNOWLEDGE_GRAPH_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs
)
def show(
diff --git a/hyperextract/templates/zh/general/logic_graph.py b/hyperextract/templates/zh/general/logic_graph.py
index 2d4f583..4bf3e60 100644
--- a/hyperextract/templates/zh/general/logic_graph.py
+++ b/hyperextract/templates/zh/general/logic_graph.py
@@ -28,7 +28,7 @@ class LogicRelation(BaseModel):
# 2. 提示词 (Prompts)
# ==============================================================================
-LOGIC_GRAPH_PROMPT = (
+_PROMPT = (
"你是一位逻辑分析师。请将文本中的论证结构提取并转化为一个有向图。\n\n"
"提取指南:\n"
"- 识别主要主张(结论)以及引向这些结论的证据或前提。\n"
@@ -36,11 +36,11 @@ LOGIC_GRAPH_PROMPT = (
"- 不仅要提取事实,更要提取“论证”和“推理”的流向。"
)
-LOGIC_GRAPH_NODE_PROMPT = (
+_NODE_PROMPT = (
"请提取论证中的各个基本构成要素。识别核心主张、支持性证据和底层前提。对于每一项,确定其类型并记录提及的任何来源出处。"
)
-LOGIC_GRAPH_EDGE_PROMPT = (
+_EDGE_PROMPT = (
"映射提取出的主张与证据之间的逻辑流向。重点关注各个陈述之间是如何相互 支持、反驳 或 导致 彼此的。确保每条边都代表推理链中的一个步骤。"
)
@@ -105,9 +105,9 @@ class LogicGraph(AutoGraph[LogicNode, LogicRelation]):
chunk_overlap=chunk_overlap,
max_workers=max_workers,
verbose=verbose,
- prompt=LOGIC_GRAPH_PROMPT,
- prompt_for_node_extraction=LOGIC_GRAPH_NODE_PROMPT,
- prompt_for_edge_extraction=LOGIC_GRAPH_EDGE_PROMPT,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
**kwargs
)
def show(