Skip to content

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

feat: 更新LLM模型为gpt-4o-mini并清理无用模板

yifanfeng97699b45b9acc3
diff --git a/README.md b/README.md
index 131587d..8536dab 100644
--- a/README.md
+++ b/README.md
@@ -59,7 +59,7 @@ from hyperextract.templates.en.finance import ResearchNoteSummary
from langchain_openai import ChatOpenAI
# 1. Load an industry-expert template
-llm = ChatOpenAI(model="gpt-5-mini")
+llm = ChatOpenAI(model="gpt-4o-mini")
kb = AutoGraph.from_template(ResearchNoteSummary, llm_client=llm)
# 2. Feed your domain text (Extraction happens automatically!)
diff --git a/README_ZH.md b/README_ZH.md
index 1b9a496..f3330de 100644
--- a/README_ZH.md
+++ b/README_ZH.md
@@ -59,7 +59,7 @@ from hyperextract.templates.zh.finance import ResearchNoteSummary
from langchain_openai import ChatOpenAI
# 1. 加载一个行业模板 (例如: 金融研报摘要)
-llm = ChatOpenAI(model="gpt-5-mini")
+llm = ChatOpenAI(model="gpt-4o-mini")
kb = AutoGraph.from_template(ResearchNoteSummary, llm_client=llm)
# 2. “喂入” 领域文本 (自动完成知识提取与建模)
diff --git a/examples/atom_demo.py b/examples/atom_demo.py
index 8e8d448..0aad04b 100644
--- a/examples/atom_demo.py
+++ b/examples/atom_demo.py
@@ -100,7 +100,7 @@ def main():
# 1. 初始化
print("📦 初始化组件...")
- llm = ChatOpenAI(model="gpt-5-mini", temperature=0)
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
embedder = OpenAIEmbeddings(model="text-embedding-3-small")
obs_time = "2024-12-15"
diff --git a/examples/auto_graph_demo.py b/examples/auto_graph_demo.py
index 97bdc0e..e73ae31 100644
--- a/examples/auto_graph_demo.py
+++ b/examples/auto_graph_demo.py
@@ -272,7 +272,7 @@ def run_demo():
# 初始化 LLM
print("\n🔧 初始化 LLM 和嵌入模型...")
- llm = ChatOpenAI(model="gpt-5-mini", temperature=0)
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
embedder = OpenAIEmbeddings()
# 创建 AutoGraph
diff --git a/examples/auto_hypergraph_demo.py b/examples/auto_hypergraph_demo.py
index 7e9ad05..42a444d 100644
--- a/examples/auto_hypergraph_demo.py
+++ b/examples/auto_hypergraph_demo.py
@@ -120,7 +120,7 @@ def main():
"""主函数:完整的 AutoHypergraph 提取与分析流程"""
# 初始化 LLM 和嵌入模型
- llm_client = ChatOpenAI(model="gpt-5-mini", temperature=0)
+ llm_client = ChatOpenAI(model="gpt-4o-mini", temperature=0)
embedder = OpenAIEmbeddings()
# 1. 节点指纹:用名字即可
diff --git a/examples/auto_list_demo.py b/examples/auto_list_demo.py
index 0e98da0..19cbdd4 100644
--- a/examples/auto_list_demo.py
+++ b/examples/auto_list_demo.py
@@ -102,7 +102,7 @@ def main():
# 2. 初始化 LLM 和 Embedder
print("\n[2] 初始化 LLM 和 Embedder...")
- llm = ChatOpenAI(model="gpt-5-mini", temperature=0)
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
embedder = OpenAIEmbeddings(model="text-embedding-3-small")
# 3. 创建 AutoList 实例 (使用小的 chunk_size 测试多 chunk)
diff --git a/examples/auto_model_demo.py b/examples/auto_model_demo.py
index 47eeda1..dfb18d2 100644
--- a/examples/auto_model_demo.py
+++ b/examples/auto_model_demo.py
@@ -150,7 +150,7 @@ def main():
# 2. 初始化 LLM 和 Embedder
print("\n[2] 初始化 LLM 和 Embedder...")
- llm_client = ChatOpenAI(model="gpt-5-mini")
+ llm_client = ChatOpenAI(model="gpt-4o-mini")
embedder = OpenAIEmbeddings(model="text-embedding-3-small")
# 3. 创建 AutoModel 实例 (使用小的 chunk_size 测试多 chunk)
diff --git a/examples/auto_set_demo.py b/examples/auto_set_demo.py
index aecd8e9..9fe65a3 100644
--- a/examples/auto_set_demo.py
+++ b/examples/auto_set_demo.py
@@ -53,7 +53,7 @@ class MonsterEntry(BaseModel):
def main():
# 初始化LLM和嵌入模型
- llm = ChatOpenAI(model="gpt-5-mini", temperature=0)
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
embedder = OpenAIEmbeddings(model="text-embedding-3-small")
# 创建AutoSet,使用LLM_MERGE策略
diff --git a/examples/auto_spatial_graph_demo.py b/examples/auto_spatial_graph_demo.py
index 37e578c..74585e8 100644
--- a/examples/auto_spatial_graph_demo.py
+++ b/examples/auto_spatial_graph_demo.py
@@ -147,7 +147,7 @@ def run_demo():
# 初始化 LLM
print("\n🔧 初始化 LLM 和嵌入模型...")
- llm = ChatOpenAI(model="gpt-5-mini", temperature=0)
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
embedder = OpenAIEmbeddings()
# 创建 AutoSpatialGraph
diff --git a/examples/auto_spatio_temporal_graph_demo.py b/examples/auto_spatio_temporal_graph_demo.py
index eb38942..d620a8f 100644
--- a/examples/auto_spatio_temporal_graph_demo.py
+++ b/examples/auto_spatio_temporal_graph_demo.py
@@ -90,7 +90,7 @@ def run_demo():
print("🕵️ AutoSpatioTemporalGraph 演示:冷战柏林行动")
print("=" * 80)
- llm = ChatOpenAI(model="gpt-5-mini", temperature=0)
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
embedder = OpenAIEmbeddings()
# 创建 AutoSpatioTemporalGraph 实例
diff --git a/examples/auto_temporal_graph_demo.py b/examples/auto_temporal_graph_demo.py
index e927482..8a17749 100644
--- a/examples/auto_temporal_graph_demo.py
+++ b/examples/auto_temporal_graph_demo.py
@@ -127,7 +127,7 @@ def run_demo():
# 初始化 LLM
print("\n🔧 初始化 LLM 和嵌入模型...")
- llm = ChatOpenAI(model="gpt-5-mini", temperature=0)
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
embedder = OpenAIEmbeddings()
# 创建 AutoTemporalGraph
diff --git a/examples/hyper_rag_demo.py b/examples/hyper_rag_demo.py
index e012593..ee08090 100644
--- a/examples/hyper_rag_demo.py
+++ b/examples/hyper_rag_demo.py
@@ -81,9 +81,9 @@ if __name__ == "__main__":
print("Initializing Hyper-RAG System...")
print("=" * 80)
- # llm_client = ChatOpenAI(model="gpt-5-mini", temperature=0)
+ # llm_client = ChatOpenAI(model="gpt-4o-mini", temperature=0)
llm_client = ChatOpenAI(
- model="gpt-5-mini",
+ model="gpt-4o-mini",
extra_body={
"system": "You are a helpful assistant. Always respond in Chinese."
},
diff --git a/examples/hypergraph_rag_demo.py b/examples/hypergraph_rag_demo.py
index 7ffc22f..dbb45b1 100644
--- a/examples/hypergraph_rag_demo.py
+++ b/examples/hypergraph_rag_demo.py
@@ -79,7 +79,7 @@ if __name__ == "__main__":
print("=" * 80)
llm_client = ChatOpenAI(
- model="gpt-5-mini",
+ model="gpt-4o-mini",
extra_body={
"system": "You are a helpful assistant. Always respond in Chinese."
},
diff --git a/examples/itext2kg_demo.py b/examples/itext2kg_demo.py
index f40b88a..853b67c 100644
--- a/examples/itext2kg_demo.py
+++ b/examples/itext2kg_demo.py
@@ -201,7 +201,7 @@ def main():
# 1. 初始化
print("📦 初始化组件...")
- llm = ChatOpenAI(model="gpt-5-mini", temperature=0)
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
embedder = OpenAIEmbeddings()
print("🚀 创建 iText2KG 实例...")
diff --git a/examples/itext2kg_star_demo.py b/examples/itext2kg_star_demo.py
index 898e1bf..f2c82ec 100644
--- a/examples/itext2kg_star_demo.py
+++ b/examples/itext2kg_star_demo.py
@@ -217,7 +217,7 @@ def main():
# 1. 初始化
print("\n📦 初始化组件...")
- llm = ChatOpenAI(model="gpt-5-mini", temperature=0)
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
embedder = OpenAIEmbeddings()
print("🚀 创建 iText2KG_Star 实例...")
diff --git a/examples/kg_gen_demo.py b/examples/kg_gen_demo.py
index 7037127..9b7b031 100644
--- a/examples/kg_gen_demo.py
+++ b/examples/kg_gen_demo.py
@@ -233,7 +233,7 @@ def main():
# 1. 初始化
print("📦 初始化组件...")
- llm = ChatOpenAI(model="gpt-5-mini", temperature=0)
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
embedder = OpenAIEmbeddings()
print("🚀 创建 KGGenGraph 实例...")
diff --git a/examples/light_rag_demo.py b/examples/light_rag_demo.py
index 443034d..f8c0e1e 100644
--- a/examples/light_rag_demo.py
+++ b/examples/light_rag_demo.py
@@ -82,7 +82,7 @@ if __name__ == "__main__":
# Use a capable model for extraction
llm_client = ChatOpenAI(
- model="gpt-5-mini",
+ model="gpt-4o-mini",
extra_body={
"system": "You are a helpful assistant. Always respond in Chinese."
},
diff --git a/examples/method_cog_rag_demo.py b/examples/method_cog_rag_demo.py
index 81ccd55..a3fac67 100644
--- a/examples/method_cog_rag_demo.py
+++ b/examples/method_cog_rag_demo.py
@@ -87,7 +87,7 @@ if __name__ == "__main__":
# Use a capable model for extraction
llm_client = ChatOpenAI(
- model="gpt-5-mini",
+ model="gpt-4o-mini",
extra_body={
"system": "You are a helpful assistant. Always respond in Chinese."
},
diff --git a/examples/template_biology_demo.py b/examples/template_biology_demo.py
index 04f92e5..0ab0213 100644
--- a/examples/template_biology_demo.py
+++ b/examples/template_biology_demo.py
@@ -108,7 +108,7 @@ def main():
print("\n🔧 初始化 LLM 客户端...")
try:
llm = ChatOpenAI(
- model="gpt-5-mini",
+ model="gpt-4o-mini",
temperature=0,
)
embedder = OpenAIEmbeddings(model="text-embedding-3-small")
diff --git a/examples/template_general_demo.py b/examples/template_general_demo.py
index e37dd25..b9c575b 100644
--- a/examples/template_general_demo.py
+++ b/examples/template_general_demo.py
@@ -129,7 +129,7 @@ def main():
print("\n🔧 初始化 LLM 客户端...")
try:
llm = ChatOpenAI(
- model="gpt-5-mini",
+ model="gpt-4o-mini",
temperature=0,
)
embedder = OpenAIEmbeddings(model="text-embedding-3-small")
diff --git a/examples/template_history_demo.py b/examples/template_history_demo.py
index 1274404..d762511 100644
--- a/examples/template_history_demo.py
+++ b/examples/template_history_demo.py
@@ -73,13 +73,13 @@ TEMPLATE_TO_INPUT = {
# 编年史
# TEMPLATE = ChronologicalEventChain
-TEMPLATE = HistoricalContextGraph
+# TEMPLATE = HistoricalContextGraph
# TEMPLATE = PoliticalStruggleHypergraph
# 口述历史
# TEMPLATE = PersonalTrajectoryHypergraph
# TEMPLATE = NarrativeRelationGraph
-# TEMPLATE = MemoryFlashbackList
+TEMPLATE = MemoryFlashbackList
# 档案馆藏信札
# TEMPLATE = EpistolaryKnowledgeGraph
@@ -111,7 +111,7 @@ def main():
print("\n🔧 初始化 LLM 客户端...")
try:
llm = ChatOpenAI(
- model="gpt-5-mini",
+ model="gpt-4o-mini",
temperature=0,
)
embedder = OpenAIEmbeddings(model="text-embedding-3-small")
diff --git a/examples/template_medicine_demo.py b/examples/template_medicine_demo.py
index 3176267..e8e7228 100644
--- a/examples/template_medicine_demo.py
+++ b/examples/template_medicine_demo.py
@@ -136,7 +136,7 @@ def main():
print("\n🔧 初始化 LLM 客户端...")
try:
llm = ChatOpenAI(
- model="gpt-5-mini",
+ model="gpt-4o-mini",
temperature=0,
)
embedder = OpenAIEmbeddings(model="text-embedding-3-small")
diff --git a/examples/template_tcm_demo.py b/examples/template_tcm_demo.py
index 79cf191..f5e19e5 100644
--- a/examples/template_tcm_demo.py
+++ b/examples/template_tcm_demo.py
@@ -114,7 +114,7 @@ def main():
print("\n🔧 初始化 LLM 客户端...")
try:
llm = ChatOpenAI(
- model="gpt-5-mini",
+ model="gpt-4o-mini",
temperature=0,
)
embedder = OpenAIEmbeddings(model="text-embedding-3-small")
diff --git a/hyperextract/methods/typical/atom.py b/hyperextract/methods/typical/atom.py
index 2cb739d..7f5b407 100644
--- a/hyperextract/methods/typical/atom.py
+++ b/hyperextract/methods/typical/atom.py
@@ -301,7 +301,7 @@ class Atom(AutoGraph[NodeSchema, EdgeSchema]):
Example:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini", temperature=0)
+ >>> llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
>>> embedder = OpenAIEmbeddings()
>>> kg = Atom(llm_client=llm, embedder=embedder)
diff --git a/hyperextract/methods/typical/itext2kg.py b/hyperextract/methods/typical/itext2kg.py
index 17372bc..808e500 100644
--- a/hyperextract/methods/typical/itext2kg.py
+++ b/hyperextract/methods/typical/itext2kg.py
@@ -108,7 +108,7 @@ class iText2KG(AutoGraph[NodeSchema, EdgeSchema]):
- Two-stage extraction: entities first, then relationships
Example:
- >>> llm = ChatOpenAI(model="gpt-5-mini", temperature=0)
+ >>> llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
>>> embedder = OpenAIEmbeddings()
>>> kg = iText2KG(llm_client=llm, embedder=embedder)
>>> kg.feed_text(text)
diff --git a/hyperextract/methods/typical/itext2kg_star.py b/hyperextract/methods/typical/itext2kg_star.py
index 53910d4..71f1bc0 100644
--- a/hyperextract/methods/typical/itext2kg_star.py
+++ b/hyperextract/methods/typical/itext2kg_star.py
@@ -116,7 +116,7 @@ class iText2KG_Star(AutoGraph[NodeSchema, EdgeSchema]):
Example:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini", temperature=0)
+ >>> llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
>>> embedder = OpenAIEmbeddings()
>>> kg = iText2KG_Star(llm_client=llm, embedder=embedder)
diff --git a/hyperextract/methods/typical/kg_gen.py b/hyperextract/methods/typical/kg_gen.py
index fdf1207..56da4b1 100644
--- a/hyperextract/methods/typical/kg_gen.py
+++ b/hyperextract/methods/typical/kg_gen.py
@@ -90,7 +90,7 @@ class KG_Gen(AutoGraph[NodeSchema, EdgeSchema]):
- Two-stage extraction: entities first, then relationships
Example:
- >>> llm = ChatOpenAI(model="gpt-5-mini", temperature=0)
+ >>> llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
>>> embedder = OpenAIEmbeddings()
>>> kg = KG_Gen(llm_client=llm, embedder=embedder)
>>> kg.feed_text(text)
diff --git a/hyperextract/templates/en/__init__.py b/hyperextract/templates/en/__init__.py
index 6872cab..8737662 100644
--- a/hyperextract/templates/en/__init__.py
+++ b/hyperextract/templates/en/__init__.py
@@ -19,7 +19,6 @@ from .general import (
PenaltyMapping,
ComplianceLogic,
)
-from .agriculture import CropCycleGraph, LivestockGraph, AgriPestControl
from .finance import (
RiskAssessmentGraph,
SupplyChainGraph,
@@ -45,9 +44,6 @@ from .finance import (
MultiSourceSentimentHypergraph,
MarketNarrativeTimeline,
)
-from .literature import CharacterRelationshipGraph, NarrativeTimeline, SymbolismSet
-# from .medicine import DrugInteractionGraph, ClinicalTreatmentTimeline, DiagnosticCriteriaSet
-from .news import BreakingEventGraph, TopicTimeline, OpinionSet
__all__ = [
# general
@@ -90,15 +86,4 @@ __all__ = [
"FinancialEventCausalGraph",
"MultiSourceSentimentHypergraph",
"MarketNarrativeTimeline",
- # Literature
- "CharacterRelationshipGraph",
- "NarrativeTimeline",
- "SymbolismSet",
- "BreakingEventGraph",
- "TopicTimeline",
- "OpinionSet",
- # Agriculture
- "CropCycleGraph",
- "LivestockGraph",
- "AgriPestControl",
]
diff --git a/hyperextract/templates/en/agriculture/__init__.py b/hyperextract/templates/en/agriculture/__init__.py
index 556a0eb..5f28270 100644
--- a/hyperextract/templates/en/agriculture/__init__.py
+++ b/hyperextract/templates/en/agriculture/__init__.py
@@ -1,15 +1 @@
-from .crop_cycle import CropCycleGraph, AgriEntity, AgriRelation
-from .livestock import LivestockGraph, AnimalNode, BreedingRelation
-from .pest_control import AgriPestControl, AgriPestEntity, AgriPestRelation
-
-__all__ = [
- "CropCycleGraph",
- "AgriEntity",
- "AgriRelation",
- "LivestockGraph",
- "AnimalNode",
- "BreedingRelation",
- "AgriPestControl",
- "AgriPestEntity",
- "AgriPestRelation"
-]
+
\ No newline at end of file
diff --git a/hyperextract/templates/en/agriculture/crop_cycle.py b/hyperextract/templates/en/agriculture/crop_cycle.py
deleted file mode 100644
index 2b05b33..0000000
--- a/hyperextract/templates/en/agriculture/crop_cycle.py
+++ /dev/null
@@ -1,167 +0,0 @@
-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 import AutoGraph
-
-# ==============================================================================
-# 1. Schema Definitions
-# ==============================================================================
-
-
-class AgriEntity(BaseModel):
- """An entity in the agricultural domain (e.g., Crop, Soil, Pest, Pest Control, Equipment)."""
-
- name: str = Field(description="The name of the agricultural entity.")
- category: str = Field(
- description="Category: 'Crop', 'Growth Stage', 'Soil/Climate Condition', 'Task/Activity', 'Stress/Pest', 'Input/Fertilizer'."
- )
- description: Optional[str] = Field(
- description="Specific characteristics or state of the entity."
- )
-
-
-class AgriRelation(BaseModel):
- """A relationship between agricultural entities (e.g., 'requires', 'affected by', 'follows')."""
-
- source: str = Field(description="The source entity name.")
- target: str = Field(description="The target entity name.")
- relation_type: str = Field(
- description="Type: 'is at stage', 'impacts', 'requires task', 'applied to', 'leads to next stage'."
- )
- specification: Optional[str] = Field(
- description="Dosage, timing, or specific impact details."
- )
-
-
-# ==============================================================================
-# 2. Prompts
-# ==============================================================================
-
-_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"
- "- Map soil conditions, weather requirements, and necessary farming activities (irrigation, fertilization) to specific stages.\n"
- "- Note any threats like pests or diseases and their impact on the crop."
-)
-
-_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"
- "- Capture biological stresses such as specific pests, fungi, or diseases.\n"
- "- Classify each node into the appropriate category: 'Crop', 'Growth Stage', 'Task/Activity', etc.\n"
- "- DO NOT identify sequences or dependencies between these entities at this stage."
-)
-
-_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"
- "- Link farming tasks to the specific growth stages where they must be performed.\n"
- "- Map how environmental conditions and pests impact the crop or its stages.\n"
- "- Use specific relation types such as 'is at stage', 'requires task', 'inhibits', or 'applied to'.\n"
- "- Only connect entities that exist in the provided agricultural entity list."
-)
-
-# ==============================================================================
-# 3. Template Class
-# ==============================================================================
-
-
-class CropCycleGraph(AutoGraph[AgriEntity, AgriRelation]):
- """
- Template for mapping crop growth stages, environmental requirements, and farming activities.
-
- Ideal for precision agriculture, crop management guides, and seasonal planning.
-
- Example:
- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
- >>> embedder = OpenAIEmbeddings()
- >>> graph = CropCycleGraph(llm_client=llm, embedder=embedder)
- >>> text = "Corn requires high nitrogen during the vegetative stage."
- >>> graph.feed_text(text)
- >>> print(graph.nodes) # Extracted Corn, Nitrogen, Vegetative Stage
- """
-
- 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 CropCycleGraph template.
-
- Args:
- llm_client: The language model client for extraction.
- embedder: The embedding model for deduplication.
- extraction_mode: "one_stage" or "two_stage".
- chunk_size: Max characters per chunk.
- chunk_overlap: Overlap between chunks.
- max_workers: Parallel processing workers.
- verbose: Enable progress logging.
- **kwargs: Extra arguments for AutoGraph.
- """
- super().__init__(
- node_schema=AgriEntity,
- edge_schema=AgriRelation,
- node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: (
- f"{x.source.strip()}--({x.relation_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 graph using OntoSight.
-
- Args:
- top_k_nodes_for_search (int): Number of nodes to retrieve for search context. Default 3.
- top_k_edges_for_search (int): Number of edges to retrieve for search context. Default 3.
- top_k_nodes_for_chat (int): Number of nodes to retrieve for chat context. Default 3.
- top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
- """
-
- def node_label_extractor(node: AgriEntity) -> str:
- info = f" ({node.category})" if getattr(node, "category", None) else ""
- return f"{node.name}{info}"
-
- def edge_label_extractor(edge: AgriRelation) -> str:
- return f"{edge.relation_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/agriculture/livestock.py b/hyperextract/templates/en/agriculture/livestock.py
deleted file mode 100644
index 386973d..0000000
--- a/hyperextract/templates/en/agriculture/livestock.py
+++ /dev/null
@@ -1,158 +0,0 @@
-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 import AutoGraph
-
-# ==============================================================================
-# 1. Schema Definitions
-# ==============================================================================
-
-
-class AnimalNode(BaseModel):
- """An entity in livestock management (e.g., individual animal, breed, group, health condition)."""
-
- name: str = Field(description="Name or ID of the animal/group.")
- category: str = Field(
- description="Category: 'Individual', 'Breed', 'Strain', 'Health Status', 'Nutrient/Feed', 'Facility'."
- )
- traits: Optional[str] = Field(
- description="Key physical traits, genetic markers, or health metrics."
- )
-
-
-class BreedingRelation(BaseModel):
- """Relationships in breeding and health management."""
-
- source: str = Field(description="The source livestock entity.")
- target: str = Field(description="The target livestock entity.")
- relation_type: str = Field(
- description="Type: 'parent of', 'bred with', 'member of', 'diagnosed with', 'fed with'."
- )
- details: Optional[str] = Field(
- description="Inherited traits, dosage, or specific health observations."
- )
-
-
-# ==============================================================================
-# 2. Prompts
-# ==============================================================================
-
-_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"
- "- Map pedigree relationships (parent-offspring) and breeding pairs.\n"
- "- Link animals to their health status, vaccinations, and nutrition records."
-)
-
-_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."
-)
-
-_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."
-)
-
-# ==============================================================================
-# 3. Template Class
-# ==============================================================================
-
-
-class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):
- """
- Template for managing livestock pedigrees, health records, and breeding programs.
-
- Useful for farm management software, veterinary records, and genetic tracking.
-
- Example:
- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
- >>> embedder = OpenAIEmbeddings()
- >>> graph = LivestockGraph(llm_client=llm, embedder=embedder)
- >>> text = "Cow #402 (Angus) was crossbred with Bull #09 to improve meat quality."
- >>> graph.feed_text(text)
- >>> print(graph.edges) # Extracted breeding relationship
- """
-
- 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 LivestockGraph template.
-
- Args:
- llm_client: The language model client for extraction.
- embedder: The embedding model for deduplication.
- extraction_mode: "one_stage" or "two_stage".
- chunk_size: Max characters per chunk.
- chunk_overlap: Overlap between chunks.
- max_workers: Parallel processing workers.
- verbose: Enable progress logging.
- **kwargs: Extra arguments for AutoGraph.
- """
- super().__init__(
- node_schema=AnimalNode,
- edge_schema=BreedingRelation,
- node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: (
- f"{x.source.strip()}--({x.relation_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 graph using OntoSight.
-
- Args:
- top_k_nodes_for_search (int): Number of nodes to retrieve for search context. Default 3.
- top_k_edges_for_search (int): Number of edges to retrieve for search context. Default 3.
- top_k_nodes_for_chat (int): Number of nodes to retrieve for chat context. Default 3.
- top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
- """
-
- def node_label_extractor(node: AnimalNode) -> str:
- info = f" ({node.category})" if getattr(node, "category", None) else ""
- return f"{node.name}{info}"
-
- def edge_label_extractor(edge: BreedingRelation) -> str:
- return f"{edge.relation_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/agriculture/pest_control.py b/hyperextract/templates/en/agriculture/pest_control.py
deleted file mode 100644
index fbf54b2..0000000
--- a/hyperextract/templates/en/agriculture/pest_control.py
+++ /dev/null
@@ -1,117 +0,0 @@
-from typing import Optional, Any, Callable
-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 AgriPestEntity(BaseModel):
- """An entity in the pest control domain (Pest, Disease, Crop, Symptom, Treatment)."""
-
- name: str = Field(description="Name of the pest, crop, disease, or chemical agent.")
- category: str = Field(
- description="Category: 'Pest', 'Disease', 'Host Crop', 'Symptom', 'Prevention Method', 'Chemical Treatment'."
- )
- description: Optional[str] = Field(
- None, description="Detailed description, biological traits, or characteristics."
- )
-
-
-class AgriPestRelation(BaseModel):
- """The relationship between agricultural entities (e.g., 'infests', 'causes', 'treated_by')."""
-
- source: str = Field(description="The source entity name.")
- target: str = Field(description="The target entity name.")
- relation_type: str = Field(
- description="Type: 'infests', 'parasitizes', 'damages', 'causes symptom', 'prevented by', 'sensitive to'."
- )
- detail: Optional[str] = Field(
- None, description="Specific conditions, dosage, or damage severity."
- )
-
-
-# ==============================================================================
-# 2. Prompts
-# ==============================================================================
-
-_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.
-
-Guidelines:
-1. Identify biological threats: Pests, insects, fungi, bacteria, or viruses.
-2. Link threats to their host crops and the specific symptoms they cause (e.g., leaf spot, stem rot).
-3. Map out integrated pest management (IPM) strategies, including biological, physical, and chemical control methods.
-4. Extract specific chemical agents, dosages, and application timings mentioned in the text.
-"""
-
-# ==============================================================================
-# 3. Template Class
-# ==============================================================================
-
-
-class AgriPestControl(AutoGraph[AgriPestEntity, AgriPestRelation]):
- """
- Knowledge graph template for agricultural pest and disease management.
-
- Transforms technical manuals and guidelines into structured control strategies.
- """
-
- 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 AgriPestControl template."""
- super().__init__(
- node_schema=AgriPestEntity,
- edge_schema=AgriPestRelation,
- node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation_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,
- **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 pest control knowledge graph."""
-
- def node_label_extractor(node: AgriPestEntity) -> str:
- return f"{node.name} ({node.category})"
-
- def edge_label_extractor(edge: AgriPestRelation) -> str:
- return f"{edge.relation_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/finance/analyst_qa_graph.py b/hyperextract/templates/en/finance/analyst_qa_graph.py
index 821b637..940ad01 100644
--- a/hyperextract/templates/en/finance/analyst_qa_graph.py
+++ b/hyperextract/templates/en/finance/analyst_qa_graph.py
@@ -110,7 +110,7 @@ class AnalystQAGraph(AutoGraph[QAParticipant, QAInteraction]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> qa = AnalystQAGraph(llm_client=llm, embedder=embedder)
>>> transcript = "Analyst: Can you discuss your margin outlook? CEO: We expect margins to..."
diff --git a/hyperextract/templates/en/finance/call_sentiment_hypergraph.py b/hyperextract/templates/en/finance/call_sentiment_hypergraph.py
index 884f391..6dd80ce 100644
--- a/hyperextract/templates/en/finance/call_sentiment_hypergraph.py
+++ b/hyperextract/templates/en/finance/call_sentiment_hypergraph.py
@@ -110,7 +110,7 @@ class CallSentimentHypergraph(AutoHypergraph[CallTopic, SentimentCluster]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> sentiment = CallSentimentHypergraph(llm_client=llm, embedder=embedder)
>>> transcript = "CEO: We are very excited about AI revenue growth..."
diff --git a/hyperextract/templates/en/finance/company_history_timeline.py b/hyperextract/templates/en/finance/company_history_timeline.py
index 73559ea..9433fa2 100644
--- a/hyperextract/templates/en/finance/company_history_timeline.py
+++ b/hyperextract/templates/en/finance/company_history_timeline.py
@@ -110,7 +110,7 @@ class CompanyHistoryTimeline(
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> history = CompanyHistoryTimeline(llm_client=llm, embedder=embedder)
>>> text = "Founded in 2015 by John Doe. Raised $10M Series A in 2017..."
diff --git a/hyperextract/templates/en/finance/earnings_call_summary.py b/hyperextract/templates/en/finance/earnings_call_summary.py
index 9002990..217bb95 100644
--- a/hyperextract/templates/en/finance/earnings_call_summary.py
+++ b/hyperextract/templates/en/finance/earnings_call_summary.py
@@ -109,7 +109,7 @@ class EarningsCallSummary(AutoModel[EarningsCallSummarySchema]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> summary = EarningsCallSummary(llm_client=llm, embedder=embedder)
>>> transcript = "Good afternoon. Q3 revenue was $94.8 billion, beating consensus..."
diff --git a/hyperextract/templates/en/finance/factor_influence_hypergraph.py b/hyperextract/templates/en/finance/factor_influence_hypergraph.py
index f0944e6..bdbfab1 100644
--- a/hyperextract/templates/en/finance/factor_influence_hypergraph.py
+++ b/hyperextract/templates/en/finance/factor_influence_hypergraph.py
@@ -111,7 +111,7 @@ class FactorInfluenceHypergraph(AutoHypergraph[InvestmentFactor, FactorInteracti
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> factors = FactorInfluenceHypergraph(llm_client=llm, embedder=embedder)
>>> report = "Rising rates combined with strong GDP and AI capex create a rotation into quality growth..."
diff --git a/hyperextract/templates/en/finance/filing_financial_snapshot.py b/hyperextract/templates/en/finance/filing_financial_snapshot.py
index d76a4c9..00086ce 100644
--- a/hyperextract/templates/en/finance/filing_financial_snapshot.py
+++ b/hyperextract/templates/en/finance/filing_financial_snapshot.py
@@ -119,7 +119,7 @@ class FilingFinancialSnapshot(AutoModel[FilingFinancialSnapshotSchema]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> snapshot = FilingFinancialSnapshot(llm_client=llm, embedder=embedder)
>>> filing_text = "Item 8. Financial Statements: Revenue was $394.3 billion..."
diff --git a/hyperextract/templates/en/finance/filing_risk_factor_set.py b/hyperextract/templates/en/finance/filing_risk_factor_set.py
index aab5bc2..f2b695d 100644
--- a/hyperextract/templates/en/finance/filing_risk_factor_set.py
+++ b/hyperextract/templates/en/finance/filing_risk_factor_set.py
@@ -78,7 +78,7 @@ class FilingRiskFactorSet(AutoSet[RiskFactorItem]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> risk_set = FilingRiskFactorSet(llm_client=llm, embedder=embedder)
>>> filing = "Item 1A. Risk Factors: We face significant cybersecurity risks..."
diff --git a/hyperextract/templates/en/finance/financial_data_temporal_graph.py b/hyperextract/templates/en/finance/financial_data_temporal_graph.py
index 1a23b83..20cb9ac 100644
--- a/hyperextract/templates/en/finance/financial_data_temporal_graph.py
+++ b/hyperextract/templates/en/finance/financial_data_temporal_graph.py
@@ -141,7 +141,7 @@ class FinancialDataTemporalGraph(
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> graph = FinancialDataTemporalGraph(llm_client=llm, embedder=embedder)
>>> filing = "For FY2024, Apple reported revenue of $394.3B, up 7.8% from $365.8B in FY2023..."
diff --git a/hyperextract/templates/en/finance/financial_event_causal_graph.py b/hyperextract/templates/en/finance/financial_event_causal_graph.py
index 4030103..6c9bf83 100644
--- a/hyperextract/templates/en/finance/financial_event_causal_graph.py
+++ b/hyperextract/templates/en/finance/financial_event_causal_graph.py
@@ -109,7 +109,7 @@ class FinancialEventCausalGraph(AutoGraph[FinancialEventNode, EventCausalEdge]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> causal = FinancialEventCausalGraph(llm_client=llm, embedder=embedder)
>>> news = "The Fed raised rates by 25bps, sending bank stocks higher while tech sold off..."
diff --git a/hyperextract/templates/en/finance/financial_forecast.py b/hyperextract/templates/en/finance/financial_forecast.py
index c06cc47..e29f500 100644
--- a/hyperextract/templates/en/finance/financial_forecast.py
+++ b/hyperextract/templates/en/finance/financial_forecast.py
@@ -80,7 +80,7 @@ class FinancialForecast(AutoList[ForecastItem]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> forecast = FinancialForecast(llm_client=llm, embedder=embedder)
>>> report = "We raise our FY2025 revenue estimate to $120.5B (from $115B)..."
diff --git a/hyperextract/templates/en/finance/management_guidance_list.py b/hyperextract/templates/en/finance/management_guidance_list.py
index 070a27d..076058d 100644
--- a/hyperextract/templates/en/finance/management_guidance_list.py
+++ b/hyperextract/templates/en/finance/management_guidance_list.py
@@ -85,7 +85,7 @@ class ManagementGuidanceList(AutoList[GuidanceItem]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> guidance = ManagementGuidanceList(llm_client=llm, embedder=embedder)
>>> transcript = "For Q4, we expect revenue in the range of $95-97 billion..."
diff --git a/hyperextract/templates/en/finance/market_narrative_timeline.py b/hyperextract/templates/en/finance/market_narrative_timeline.py
index 5bc3b7d..9f30ecd 100644
--- a/hyperextract/templates/en/finance/market_narrative_timeline.py
+++ b/hyperextract/templates/en/finance/market_narrative_timeline.py
@@ -115,7 +115,7 @@ class MarketNarrativeTimeline(
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> narrative = MarketNarrativeTimeline(llm_client=llm, embedder=embedder)
>>> commentary = "Markets shifted from inflation fear to soft landing hope in Q2 2024..."
diff --git a/hyperextract/templates/en/finance/market_sentiment_model.py b/hyperextract/templates/en/finance/market_sentiment_model.py
index 227a2aa..bf6b7a0 100644
--- a/hyperextract/templates/en/finance/market_sentiment_model.py
+++ b/hyperextract/templates/en/finance/market_sentiment_model.py
@@ -96,7 +96,7 @@ class MarketSentimentModel(AutoModel[MarketSentimentSnapshot]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> sentiment = MarketSentimentModel(llm_client=llm, embedder=embedder)
>>> news = "Tech stocks rallied sharply after NVDA reported record earnings..."
diff --git a/hyperextract/templates/en/finance/material_event_timeline.py b/hyperextract/templates/en/finance/material_event_timeline.py
index 8eba526..8bd2478 100644
--- a/hyperextract/templates/en/finance/material_event_timeline.py
+++ b/hyperextract/templates/en/finance/material_event_timeline.py
@@ -111,7 +111,7 @@ class MaterialEventTimeline(AutoTemporalGraph[MaterialEventEntity, MaterialEvent
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> timeline = MaterialEventTimeline(llm_client=llm, embedder=embedder)
>>> filing = "Item 5.02: On March 15, 2024, the Board appointed John Smith as CEO..."
diff --git a/hyperextract/templates/en/finance/mda_narrative_graph.py b/hyperextract/templates/en/finance/mda_narrative_graph.py
index 61b8248..a978583 100644
--- a/hyperextract/templates/en/finance/mda_narrative_graph.py
+++ b/hyperextract/templates/en/finance/mda_narrative_graph.py
@@ -103,7 +103,7 @@ class MDANarrativeGraph(AutoGraph[MDAFactor, MDANarrativeEdge]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> mda = MDANarrativeGraph(llm_client=llm, embedder=embedder)
>>> text = "Revenue increased 12% driven by strong demand in our cloud segment..."
diff --git a/hyperextract/templates/en/finance/multi_source_sentiment_hypergraph.py b/hyperextract/templates/en/finance/multi_source_sentiment_hypergraph.py
index 2bbcf00..d135716 100644
--- a/hyperextract/templates/en/finance/multi_source_sentiment_hypergraph.py
+++ b/hyperextract/templates/en/finance/multi_source_sentiment_hypergraph.py
@@ -121,7 +121,7 @@ class MultiSourceSentimentHypergraph(
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> fusion = MultiSourceSentimentHypergraph(llm_client=llm, embedder=embedder)
>>> text = "Bloomberg reports tech rally. Meanwhile, GS upgrades AAPL. Twitter sentiment bullish."
diff --git a/hyperextract/templates/en/finance/proceeds_usage.py b/hyperextract/templates/en/finance/proceeds_usage.py
index ec4eccc..1540b0d 100644
--- a/hyperextract/templates/en/finance/proceeds_usage.py
+++ b/hyperextract/templates/en/finance/proceeds_usage.py
@@ -78,7 +78,7 @@ class ProceedsUsage(AutoList[ProceedsItem]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> proceeds = ProceedsUsage(llm_client=llm, embedder=embedder)
>>> prospectus = "We intend to use approximately $150M for R&D, $100M for debt repayment..."
diff --git a/hyperextract/templates/en/finance/research_note_summary.py b/hyperextract/templates/en/finance/research_note_summary.py
index a14aacc..39cc579 100644
--- a/hyperextract/templates/en/finance/research_note_summary.py
+++ b/hyperextract/templates/en/finance/research_note_summary.py
@@ -104,7 +104,7 @@ class ResearchNoteSummary(AutoModel[ResearchNoteSummarySchema]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> summary = ResearchNoteSummary(llm_client=llm, embedder=embedder)
>>> report = "We upgrade AAPL to Buy with a $200 price target..."
diff --git a/hyperextract/templates/en/finance/risk_assessment.py b/hyperextract/templates/en/finance/risk_assessment.py
index 7898941..0edaa12 100644
--- a/hyperextract/templates/en/finance/risk_assessment.py
+++ b/hyperextract/templates/en/finance/risk_assessment.py
@@ -109,7 +109,7 @@ class RiskAssessmentGraph(AutoGraph[RiskFactor, RiskTransmissionEdge]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> risk_graph = RiskAssessmentGraph(llm_client=llm, embedder=embedder)
>>> filing_text = "Item 1A. Risk Factors: Currency fluctuations could materially impact our margins..."
diff --git a/hyperextract/templates/en/finance/risk_factor_list.py b/hyperextract/templates/en/finance/risk_factor_list.py
index 395d65f..7030894 100644
--- a/hyperextract/templates/en/finance/risk_factor_list.py
+++ b/hyperextract/templates/en/finance/risk_factor_list.py
@@ -75,7 +75,7 @@ class RiskFactorList(AutoList[RiskItem]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> risks = RiskFactorList(llm_client=llm, embedder=embedder)
>>> report = "Key risks include: 1) EU Digital Markets Act compliance costs..."
diff --git a/hyperextract/templates/en/finance/segment_performance_list.py b/hyperextract/templates/en/finance/segment_performance_list.py
index 137e5dc..7d1ae5c 100644
--- a/hyperextract/templates/en/finance/segment_performance_list.py
+++ b/hyperextract/templates/en/finance/segment_performance_list.py
@@ -78,7 +78,7 @@ class SegmentPerformanceList(AutoList[SegmentPerformanceItem]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> segments = SegmentPerformanceList(llm_client=llm, embedder=embedder)
>>> filing = "Americas segment revenue was $48.2B, up 12% YoY..."
diff --git a/hyperextract/templates/en/finance/shareholder_structure.py b/hyperextract/templates/en/finance/shareholder_structure.py
index 7d4331a..62b045c 100644
--- a/hyperextract/templates/en/finance/shareholder_structure.py
+++ b/hyperextract/templates/en/finance/shareholder_structure.py
@@ -116,7 +116,7 @@ class ShareholderStructure(AutoGraph[OwnershipEntity, OwnershipEdge]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> ownership = ShareholderStructure(llm_client=llm, embedder=embedder)
>>> prospectus = "The following table sets forth beneficial ownership: CEO holds 15.3%..."
diff --git a/hyperextract/templates/en/finance/supply_chain.py b/hyperextract/templates/en/finance/supply_chain.py
index 048b1dc..5926215 100644
--- a/hyperextract/templates/en/finance/supply_chain.py
+++ b/hyperextract/templates/en/finance/supply_chain.py
@@ -84,7 +84,7 @@ class SupplyChainGraph(AutoGraph[SupplyEntity, SupplyTransaction]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> supply_chain = SupplyChainGraph(llm_client=llm, embedder=embedder)
>>> filing = "Supplier XYZ provides 70% of our components. We also depend on..."
diff --git a/hyperextract/templates/en/finance/valuation_logic_map.py b/hyperextract/templates/en/finance/valuation_logic_map.py
index 9a0218b..c764496 100644
--- a/hyperextract/templates/en/finance/valuation_logic_map.py
+++ b/hyperextract/templates/en/finance/valuation_logic_map.py
@@ -105,7 +105,7 @@ class ValuationLogicMap(AutoGraph[ValuationDriver, ValuationEdge]):
Example Usage:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> valuation = ValuationLogicMap(llm_client=llm, embedder=embedder)
>>> report = "Cloud adoption drives recurring revenue, justifying a 30x forward P/E..."
diff --git a/hyperextract/templates/en/food/__init__.py b/hyperextract/templates/en/food/__init__.py
index cb9481b..e69de29 100644
--- a/hyperextract/templates/en/food/__init__.py
+++ b/hyperextract/templates/en/food/__init__.py
@@ -1,17 +0,0 @@
-"""
-Food & Agriculture domain templates for extracting structured knowledge from food industry documents.
-
-Includes templates for HACCP safety, recipe processes, flavor pairing, and culinary collections.
-"""
-
-from .haccp_safety import FoodSafetyHACCPGraph
-from .recipe_process import RecipeProcessGraph
-from .flavor_pairing import FlavorPairingGraph
-from .culinary_dish import CulinaryDishSet
-
-__all__ = [
- "FoodSafetyHACCPGraph",
- "RecipeProcessGraph",
- "FlavorPairingGraph",
- "CulinaryDishSet",
-]
diff --git a/hyperextract/templates/en/food/culinary_dish.py b/hyperextract/templates/en/food/culinary_dish.py
deleted file mode 100644
index 0d9d8f1..0000000
--- a/hyperextract/templates/en/food/culinary_dish.py
+++ /dev/null
@@ -1,102 +0,0 @@
-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 import AutoSet
-
-# ==============================================================================
-# 1. Schema Definitions
-# ==============================================================================
-
-
-class CulinaryDish(BaseModel):
- """
- A representative culinary dish with standardized characteristics.
- """
-
- name: str = Field(
- description="Standardized dish name (e.g., 'Kung Pao Chicken')."
- )
- origin: Optional[str] = Field(
- None, description="Cuisine type, geographic origin, and seasonal relevance."
- )
- ingredients: Optional[str] = Field(
- None, description="Core ingredients, proteins, and key spices."
- )
- profile: Optional[str] = Field(
- None,
- description="Flavor characteristics, texture notes, and cooking techniques."
- )
- description: Optional[str] = Field(
- None,
- description="General description including dietary info, serving suggestions, and history.",
- )
-
-
-# ==============================================================================
-# 2. Prompts
-# ==============================================================================
-
-_PROMPT = (
- "You are a culinary expert. Extract representative culinary dishes from text.\n\n"
- "Extraction Rules:\n"
- "- Standardize dish names.\n"
- "- **origin**: Combine cuisine, region, and seasonality.\n"
- "- **ingredients**: List main proteins and vegetables/spices.\n"
- "- **profile**: Describe flavor, texture, and method (e.g. 'Spicy, Stir-fried').\n"
- "- **description**: Capture dietary notes, serving context, and any cultural backstory.\n"
-)
-
-# ==============================================================================
-# 3. Template Class
-# ==============================================================================
-
-
-class CulinaryDishSet(AutoSet[CulinaryDish]):
- """
- Applicable to: Restaurant Menus, Cookbooks, Food Encyclopedias.
-
- Template for building a standardized culinary foundation through **key-based information accumulation**.
- """
-
- 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,
- ):
- super().__init__(
- item_schema=CulinaryDish,
- 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:
- def item_label_extractor(item: CulinaryDish) -> str:
- parts = [item.name]
- if item.origin:
- parts.append(f"({item.origin})")
- return " ".join(parts)
-
- 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/food/haccp_safety.py b/hyperextract/templates/en/food/haccp_safety.py
deleted file mode 100644
index 10d37f5..0000000
--- a/hyperextract/templates/en/food/haccp_safety.py
+++ /dev/null
@@ -1,195 +0,0 @@
-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 import AutoGraph
-
-# ==============================================================================
-# 1. Schema Definitions
-# ==============================================================================
-
-
-class BiologicalHazard(BaseModel):
- """
- A biological hazard that must be controlled in food production.
- """
-
- name: str = Field(
- description="Hazard pathogen name (e.g., 'Salmonella', 'Listeria monocytogenes', 'E. coli O157:H7')."
- )
- hazard_type: str = Field(
- description="Type: 'Bacterial', 'Viral', 'Parasitic', 'Fungal'."
- )
- health_consequence: Optional[str] = Field(
- None, description="Potential health effect (e.g., 'Severe gastroenteritis', 'Sepsis')."
- )
-
-
-class CriticalControlPoint(BaseModel):
- """
- A step or process in food production where a hazard can be controlled.
- """
-
- name: str = Field(
- description="CCP name (e.g., 'Pasteurization', 'Metal Detection', 'Cold Storage')."
- )
- process_stage: str = Field(
- description="Stage in production: 'Raw Material', 'Receiving', 'Processing', 'Cooking', 'Cooling', 'Packaging', 'Storage'."
- )
- description: Optional[str] = Field(
- None, description="Detailed description of the CCP."
- )
-
-
-class ControlMeasure(BaseModel):
- """
- A control measure linking a hazard to a CCP.
- """
-
- source: str = Field(description="The biological hazard name.")
- target: str = Field(description="The CCP name.")
- critical_limit: str = Field(
- description="Boundary between safe/unsafe (e.g. '>72C')."
- )
- monitoring: str = Field(
- description="Procedure and frequency of monitoring."
- )
- details: Optional[str] = Field(
- None, description="Corrective actions and verification methods."
- )
-
-
-# ==============================================================================
-# 2. Prompts
-# ==============================================================================
-
-_PROMPT = (
- "You are a food safety specialist. Extract hazards, CCPs, and controls.\n\n"
- "Rules:\n"
- "- Identify hazards and CCPs.\n"
- "- Link hazards to CCPs via control measures.\n"
- "- Extract **critical_limit** and **monitoring** details.\n"
- "- Capture corrective actions in **details**."
-)
-
-_NODE_PROMPT = (
- "You are a food safety specialist. Extract hazards and CCPs (Nodes).\n\n"
- "Rules:\n"
- "- Identify biological hazards and classify type.\n"
- "- Identify CCPs and production stage.\n"
-)
-
-_EDGE_PROMPT = (
- "You are a food safety specialist. Extract control measures (Edges).\n\n"
- "Rules:\n"
- "- Connect hazard to CCP.\n"
- "- **critical_limit**: Safety boundary.\n"
- "- **monitoring**: How and when to check.\n"
- "- **details**: Corrective actions and verification.\n"
- "- Only connect existing nodes."
-)
-
-# ==============================================================================
-# 3. Template Class
-# ==============================================================================
-
-
-class FoodSafetyHACCPGraph(AutoGraph[BiologicalHazard, ControlMeasure]):
- """
- Applicable to: HACCP Plans, Food Safety Plans (ISO 22000), SOP Manuals,
- FDA Guidance Documents, Food Company Quality Procedures, Supplier Audit Reports.
-
- Template for systematically extracting and structuring HACCP-based food safety
- controls. Enables compliance verification, supplier auditing, and continuous
- safety monitoring across food production operations.
-
- Example Usage:
- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
- >>> embedder = OpenAIEmbeddings()
- >>> haccp = FoodSafetyHACCPGraph(llm_client=llm, embedder=embedder)
- >>> plan = "Critical Control Point: Pasteurization. Hazard: Salmonella. Critical limit: 72°C for 15s..."
- >>> haccp.feed_text(plan)
- >>> haccp.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,
- ):
- """
- Initialize the Food Safety HACCP Graph template.
-
- Args:
- llm_client (BaseChatModel): The LLM for hazard and control extraction.
- embedder (Embeddings): Embedding model for deduplication.
- extraction_mode (str): "one_stage" or "two_stage".
- chunk_size (int): Max characters per chunk.
- chunk_overlap (int): Overlap between chunks.
- max_workers (int): Parallel processing workers.
- verbose (bool): Enable progress logging.
- **kwargs: Additional arguments for AutoGraph.
- """
- super().__init__(
- node_schema=BiologicalHazard,
- edge_schema=ControlMeasure,
- node_key_extractor=lambda x: x.name.strip().lower(),
- edge_key_extractor=lambda x: (
- f"{x.source.strip()}--({x.target.strip()}): {x.critical_limit.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 food safety control graph using OntoSight.
-
- Args:
- top_k_nodes_for_search (int): Number of hazards/CCPs to retrieve. Default 3.
- top_k_edges_for_search (int): Number of control measures to retrieve. Default 3.
- top_k_nodes_for_chat (int): Nodes for chat context. Default 3.
- top_k_edges_for_chat (int): Edges for chat context. Default 3.
- """
-
- def node_label_extractor(node: BiologicalHazard) -> str:
- if isinstance(node, BiologicalHazard):
- return f"{node.name} ({node.hazard_type})"
- return str(node)
-
- def edge_label_extractor(edge: ControlMeasure) -> str:
- return f"{edge.critical_limit}"
-
- 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/food/recipe_process.py b/hyperextract/templates/en/food/recipe_process.py
deleted file mode 100644
index 61ff5d8..0000000
--- a/hyperextract/templates/en/food/recipe_process.py
+++ /dev/null
@@ -1,178 +0,0 @@
-from typing import List, 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 import AutoTemporalGraph
-
-# ==============================================================================
-# 1. Schema Definitions
-# ==============================================================================
-
-
-class IngredientState(BaseModel):
- """
- The state of ingredients/materials at a particular stage in the recipe process.
- """
-
- name: str = Field(
- description="State descriptor (e.g., 'Blended Mixture', 'Heated Dough', 'Cooled Slurry')."
- )
- composition: str = Field(
- description="What's in this state (e.g., 'Eggs + Sugar', 'Flour + Water + Salt')."
- )
- physical_state: Optional[str] = Field(
- None, description="Physical form: 'Liquid', 'Solid', 'Powder', 'Dough', 'Emulsion', 'Foam'."
- )
-
-
-class ProcessingStep(BaseModel):
- """
- A transformation step connecting two ingredient states.
- """
-
- step_id: str = Field(description="Step identifier (e.g., 'Step 1', '1.1', 'Mixing').")
- source_state: str = Field(description="The starting ingredient state.")
- target_state: str = Field(description="The resulting ingredient state after processing.")
- action: str = Field(
- description="The processing action (e.g., 'Blend', 'Heat', 'Cool', 'Rest', 'Knead', 'Ferment')."
- )
- process_conditions: Optional[str] = Field(
- None, description="Combine duration, temp, equipment, and parameters."
- )
-
-
-# ==============================================================================
-# 2. Prompts
-# ==============================================================================
-
-_PROMPT = (
- "You are a food scientist. Extract recipe process steps.\n\n"
- "Rules:\n"
- "- Identify processing actions and transformations.\n"
- "- Extract ingredient states pre/post step.\n"
- "- Capture **process_conditions** (time, temp, equipment).\n"
- "- Maintain sequence order."
-)
-
-_NODE_PROMPT = (
- "You are a food scientist. Extract ingredient states (Nodes).\n\n"
- "Rules:\n"
- "- Identify distinct states (raw, mixed, cooked).\n"
- "- List ingredients present.\n"
- "- Note physical form."
-)
-
-_EDGE_PROMPT = (
- "You are a food scientist. Extract processing steps (Edges).\n\n"
- "Rules:\n"
- "- Connect source to target state via action.\n"
- "- **process_conditions**: Time, temperature, equipment.\n"
- "- Maintain exact step order.\n"
- "- Only connect existing nodes."
-)
-
-# ==============================================================================
-# 3. Template Class
-# ==============================================================================
-
-
-class RecipeProcessGraph(AutoTemporalGraph[IngredientState, ProcessingStep]):
- """
- Applicable to: Industrial Formulation Sheets, Recipe SOPs, Food Science Research,
- Production Batch Records, Chef's Recipes, Cooking Manuals, R&D Experimental Protocols.
-
- Template for extracting and mapping sequential food production processes with
- precise timing and parameters. Enables recipe standardization, process optimization,
- and knowledge transfer in culinary and industrial food settings.
-
- Example Usage:
- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
- >>> embedder = OpenAIEmbeddings()
- >>> recipe = RecipeProcessGraph(llm_client=llm, embedder=embedder)
- >>> process = "Step 1: Blend eggs and sugar for 5 mins. Step 2: Heat to 175°C..."
- >>> recipe.feed_text(process)
- >>> recipe.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,
- ):
- """
- Initialize the Recipe Process Graph template.
-
- Args:
- llm_client (BaseChatModel): The LLM for state and step extraction.
- embedder (Embeddings): Embedding model for deduplication.
- extraction_mode (str): "one_stage" or "two_stage".
- chunk_size (int): Max characters per chunk.
- chunk_overlap (int): Overlap between chunks.
- max_workers (int): Parallel processing workers.
- verbose (bool): Enable progress logging.
- **kwargs: Additional arguments for AutoTemporalGraph.
- """
- super().__init__(
- node_schema=IngredientState,
- edge_schema=ProcessingStep,
- node_key_extractor=lambda x: x.name.strip().lower(),
- edge_key_extractor=lambda x: x.step_id.strip(),
- nodes_in_edge_extractor=lambda x: (
- x.source_state.strip(),
- x.target_state.strip(),
- ),
- time_in_edge_extractor=lambda x: x.step_id.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 recipe process timeline using OntoSight.
-
- Args:
- top_k_nodes_for_search (int): Number of states to retrieve. Default 3.
- top_k_edges_for_search (int): Number of steps to retrieve. Default 3.
- top_k_nodes_for_chat (int): States for chat context. Default 3.
- top_k_edges_for_chat (int): Steps for chat context. Default 3.
- """
-
- def node_label_extractor(node: IngredientState) -> str:
- return f"{node.name} ({node.physical_state if node.physical_state else 'Unknown'})"
-
- def edge_label_extractor(edge: ProcessingStep) -> str:
- temp = f" ({edge.process_conditions})" if edge.process_conditions else ""
- return f"{edge.action}{temp}"
-
- 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/legal/__init__.py b/hyperextract/templates/en/legal/__init__.py
index 6fcca93..e69de29 100644
--- a/hyperextract/templates/en/legal/__init__.py
+++ b/hyperextract/templates/en/legal/__init__.py
@@ -1,11 +0,0 @@
-"""Legal domain templates for knowledge extraction."""
-
-from .contract_obligation_checklist import ContractObligationChecklist
-from .corporate_equity_graph import CorporateEquityGraph
-from .case_precedent_library import CasePrecedentLibrary
-
-__all__ = [
- "ContractObligationChecklist",
- "CorporateEquityGraph",
- "CasePrecedentLibrary",
-]
diff --git a/hyperextract/templates/en/legal/case_precedent_library.py b/hyperextract/templates/en/legal/case_precedent_library.py
deleted file mode 100644
index 741e909..0000000
--- a/hyperextract/templates/en/legal/case_precedent_library.py
+++ /dev/null
@@ -1,71 +0,0 @@
-"""Case Precedent Library - Extracts and indexes legal precedents.
-
-Builds a searchable legal precedent database by automatically merging information
-about the same case from multiple sources.
-"""
-
-from typing import Any, Optional
-from pydantic import BaseModel, Field
-from langchain_core.language_models import BaseChatModel
-from langchain_core.embeddings import Embeddings
-from hyperextract.types import AutoSet
-
-class PrecedentSchema(BaseModel):
- case_citation: str = Field(..., description="Official case citation/reference")
- court_name: Optional[str] = Field(None, description="Court that decided the case")
- judgment_year: Optional[str] = Field(None, description="Year of judgment")
- legal_issues: Optional[str] = Field(None, description="Legal questions raised")
- holding: Optional[str] = Field(None, description="Court's decision and legal principle")
- cited_statutes: Optional[str] = Field(None, description="Laws referenced in judgment")
- presiding_judges: Optional[str] = Field(None, description="Judge(s) who decided")
- impact_assessment: Optional[str] = Field(None, description="Impact on subsequent law")
-
-_PROMPT = """You are a legal research specialist.
-Extract precedent case information:
-1. case_citation: Official case name/citation
-2. court_name: Court that heard it
-3. judgment_year: Decision year
-4. legal_issues: Legal questions
-5. holding: Court's ruling and principle
-6. cited_statutes: Applicable laws
-7. presiding_judges: Deciding judges
-8. impact_assessment: Influence on future cases
-
-### Source Text:
-"""
-
-class CasePrecedentLibrary(AutoSet[PrecedentSchema]):
- """Applicable to: Court decisions, Legal databases, Case law reports
-
- Extracts and indexes legal precedents by automatically merging case information
- from multiple sources into a unified searchable library.
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- chunk_size: int = 2048,
- chunk_overlap: int = 256,
- **kwargs: Any,
- ):
- super().__init__(
- item_schema=PrecedentSchema,
- llm_client=llm_client,
- embedder=embedder,
- key_extractor=lambda x: x.case_citation.strip().lower(),
- prompt=_PROMPT,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- **kwargs,
- )
-
- def show(self, *, top_k_for_search: int = 3, top_k_for_chat: int = 3) -> None:
- def label_extractor(item: PrecedentSchema) -> str:
- year = f" ({item.judgment_year})" if item.judgment_year else ""
- return f"{item.case_citation}{year}"
- super().show(
- item_label_extractor=label_extractor,
- top_k_for_search=top_k_for_search,
- top_k_for_chat=top_k_for_chat,
- )
diff --git a/hyperextract/templates/en/legal/contract_obligation_checklist.py b/hyperextract/templates/en/legal/contract_obligation_checklist.py
deleted file mode 100644
index d7c57a3..0000000
--- a/hyperextract/templates/en/legal/contract_obligation_checklist.py
+++ /dev/null
@@ -1,67 +0,0 @@
-"""Contract Obligation Checklist - Extracts obligations and prohibitions from contracts.
-
-Builds a comprehensive compliance checklist by extracting all duties, responsibilities,
-and restrictions without deduplication to preserve complete audit trails.
-"""
-
-from typing import Any, Optional
-from pydantic import BaseModel, Field
-from langchain_core.language_models import BaseChatModel
-from langchain_core.embeddings import Embeddings
-from hyperextract.types import AutoList
-
-class ObligationSchema(BaseModel):
- obligated_party: str = Field(..., description="Party responsible for performance")
- obligation_type: str = Field(..., description="'MUST' (required) or 'MUST_NOT' (prohibited)")
- action_description: str = Field(..., description="Specific action or requirement")
- trigger_condition: Optional[str] = Field(None, description="When/if the obligation applies")
- breach_penalty: Optional[str] = Field(None, description="Consequences of non-performance")
- clause_reference: Optional[str] = Field(None, description="Original contract clause number")
-
-_PROMPT = """You are a contract lawyer and compliance auditor.
-Extract all obligations and restrictions from the contract:
-1. obligated_party: Who must perform
-2. obligation_type: MUST (required) or MUST_NOT (prohibited)
-3. action_description: Specific action/requirement
-4. trigger_condition: When obligation applies
-5. breach_penalty: Penalty for non-compliance
-6. clause_reference: Contract clause number
-
-Extract EVERY obligation independently. No merging.
-
-### Source Text:
-"""
-
-class ContractObligationChecklist(AutoList[ObligationSchema]):
- """Applicable to: Contracts, ToS, Agreements, Compliance documents
-
- Extracts a complete compliance checklist preserving every obligation separately
- for comprehensive audit and risk analysis.
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- chunk_size: int = 2048,
- chunk_overlap: int = 256,
- **kwargs: Any,
- ):
- super().__init__(
- item_schema=ObligationSchema,
- llm_client=llm_client,
- embedder=embedder,
- prompt=_PROMPT,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- **kwargs,
- )
-
- def show(self, *, top_k_for_search: int = 3, top_k_for_chat: int = 3) -> None:
- def label_extractor(item: ObligationSchema) -> str:
- return f"{item.obligation_type}: {item.action_description[:50]}"
- super().show(
- item_label_extractor=label_extractor,
- top_k_for_search=top_k_for_search,
- top_k_for_chat=top_k_for_chat,
- )
diff --git a/hyperextract/templates/en/legal/corporate_equity_graph.py b/hyperextract/templates/en/legal/corporate_equity_graph.py
deleted file mode 100644
index 38eb29d..0000000
--- a/hyperextract/templates/en/legal/corporate_equity_graph.py
+++ /dev/null
@@ -1,80 +0,0 @@
-"""Corporate Equity Graph - Extracts ownership and control relationships.
-
-Builds a shareholding graph showing investment relationships, control structures,
-and ultimate beneficial ownership through corporate pyramids.
-"""
-
-from typing import Any, Optional
-from pydantic import BaseModel, Field
-from langchain_core.language_models import BaseChatModel
-from langchain_core.embeddings import Embeddings
-from hyperextract.types import AutoGraph
-
-class EntitySchema(BaseModel):
- entity_id: str = Field(..., description="Unique identifier")
- entity_type: str = Field(..., description="'Company', 'Individual', or 'Fund'")
- entity_name: str = Field(..., description="Legal name")
- registration_number: Optional[str] = Field(None, description="Registration or ID number")
-
-class EquityRelationshipSchema(BaseModel):
- source_entity: str = Field(..., description="Shareholder/owner name")
- target_entity: str = Field(..., description="Company/entity name")
- relationship_type: str = Field(..., description="'Owns_Shares', 'Controls', 'Serves_As_Officer'")
- stake_percentage: Optional[str] = Field(None, description="Ownership percentage")
- context: Optional[str] = Field(None, description="Additional context")
-
-_PROMPT = """Extract corporate entities and their ownership/control relationships."""
-
-_NODE_PROMPT = """Extract all entities: companies, individuals, funds mentioned."""
-
-_EDGE_PROMPT = """Extract ownership and control relationships between entities.
-Only connect entities from the known entity list."""
-
-class CorporateEquityGraph(AutoGraph[EntitySchema, EquityRelationshipSchema]):
- """Applicable to: Due diligence reports, Prospectuses, Corporate filings
-
- Extracts corporate ownership structures and ultimate beneficial ownership through
- multi-level equity chains.
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- extraction_mode: str = "two_stage",
- chunk_size: int = 2048,
- chunk_overlap: int = 256,
- **kwargs: Any,
- ):
- super().__init__(
- node_schema=EntitySchema,
- edge_schema=EquityRelationshipSchema,
- node_key_extractor=lambda x: x.entity_name.strip().lower(),
- edge_key_extractor=lambda x: (
- f"{x.source_entity.lower()}|{x.relationship_type.lower()}|{x.target_entity.lower()}"
- ),
- nodes_in_edge_extractor=lambda x: (x.source_entity.lower(), x.target_entity.lower()),
- llm_client=llm_client,
- embedder=embedder,
- extraction_mode=extraction_mode,
- prompt=_PROMPT,
- prompt_for_node_extraction=_NODE_PROMPT,
- prompt_for_edge_extraction=_EDGE_PROMPT,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- **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:
- def node_label(node: EntitySchema) -> str:
- type_icon = {"Company": "🏢", "Individual": "👤", "Fund": "💼"}
- icon = type_icon.get(node.entity_type, "●")
- return f"{icon} {node.entity_name}"
- def edge_label(edge: EquityRelationshipSchema) -> str:
- pct = f" ({edge.stake_percentage})" if edge.stake_percentage else ""
- return f"{edge.relationship_type}{pct}"
- super().show(
- node_label_extractor=node_label,
- edge_label_extractor=edge_label,
- 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/__init__.py b/hyperextract/templates/en/literature/__init__.py
index 15ac04d..e69de29 100644
--- a/hyperextract/templates/en/literature/__init__.py
+++ b/hyperextract/templates/en/literature/__init__.py
@@ -1,9 +0,0 @@
-from .character_relationship_graph import CharacterRelationshipGraph
-from .narrative_timeline import NarrativeTimeline
-from .symbolism_set import SymbolismSet
-
-__all__ = [
- "CharacterRelationshipGraph",
- "NarrativeTimeline",
- "SymbolismSet",
-]
diff --git a/hyperextract/templates/en/literature/character_relationship_graph.py b/hyperextract/templates/en/literature/character_relationship_graph.py
deleted file mode 100644
index 89f965f..0000000
--- a/hyperextract/templates/en/literature/character_relationship_graph.py
+++ /dev/null
@@ -1,172 +0,0 @@
-from typing import List, Optional, Any, Tuple
-from pydantic import BaseModel, Field
-from langchain_core.language_models.chat_models import BaseChatModel
-from langchain_core.embeddings import Embeddings
-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."
- )
-
-
-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."
- )
-
-
-# ==============================================================================
-# 2. Prompts
-# ==============================================================================
-
-_PROMPT = (
- "You are a sophisticated literary critic and character analysis expert. "
- "Your task is to extract character entities and their relationship networks from the literary text.\n\n"
- "Extraction Guidelines:\n"
- "1. **Character Identification**: Identify all significant characters. Record their names, aliases, and core character traits.\n"
- "2. **Relationship Analysis**: Analyze dialogues, actions, and narrative descriptions to extract deep connections. "
- "Focus not only on kinship but also on emotional bonds, ideological conflicts, and shifting allegiances.\n"
- "3. **Evidence-Based**: Provide short textual evidence for each relationship.\n"
- "- 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."
-
-_EDGE_PROMPT = (
- "Based on the extracted characters, identify the social and emotional relationships between them. "
- "Specify the relationship type, emotional sentiment, and provide a brief justification based on the text."
-)
-
-# ==============================================================================
-# 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,
- supporting two-stage extraction for higher precision in complex narrative webs.
-
- Example:
- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
- >>> embedder = OpenAIEmbeddings()
- >>> # Initialize template
- >>> characters = CharacterRelationshipGraph(llm_client=llm, embedder=embedder)
- >>> # Feed text
- >>> text = "Elizabeth Bennet's initial prejudice against Mr. Darcy was challenged by his noble actions."
- >>> characters.feed_text(text)
- >>> characters.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,
- ):
- """
- Initialize CharacterRelationshipGraph template.
-
- Args:
- llm_client: The language model client.
- embedder: Embeddings model for deduplication and indexing.
- extraction_mode: "one_stage" (fast) or "two_stage" (accurate).
- chunk_size: Max characters per processing chunk.
- chunk_overlap: Overlap between chunks.
- max_workers: Number of parallel extraction workers.
- verbose: Enable detailed logging.
- **kwargs: Extra arguments for AutoGraph.
- """
- super().__init__(
- node_schema=Character,
- edge_schema=Relationship,
- node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source}-{x.relation_type}-{x.target}",
- nodes_in_edge_extractor=lambda x: (x.source, x.target),
- llm_client=llm_client,
- embedder=embedder,
- prompt=_PROMPT,
- prompt_for_node_extraction=_NODE_PROMPT,
- prompt_for_edge_extraction=_EDGE_PROMPT,
- extraction_mode=extraction_mode,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- max_workers=max_workers,
- verbose=verbose,
- **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 character relationship graph.
-
- Args:
- 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
-
- def edge_label_extractor(edge: Relationship) -> str:
- return f"{edge.relation_type} ({edge.sentiment})"
-
- 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/literature/narrative_timeline.py b/hyperextract/templates/en/literature/narrative_timeline.py
deleted file mode 100644
index 9f540e4..0000000
--- a/hyperextract/templates/en/literature/narrative_timeline.py
+++ /dev/null
@@ -1,163 +0,0 @@
-from typing import List, Optional, Any, Tuple
-from pydantic import BaseModel, Field
-from langchain_core.language_models.chat_models import BaseChatModel
-from langchain_core.embeddings import Embeddings
-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')."
- )
- 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."
- )
-
-
-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)."
- )
-
-
-# ==============================================================================
-# 2. Prompts
-# ==============================================================================
-
-_PROMPT = (
- "You are a narrative structure analyst. Your task is to reconstruct the temporal and logical blueprint of the story from the text.\n\n"
- "Extraction Requirements:\n"
- "1. **Event Identification**: Extract nodes with narrative significance, recording location and participants.\n"
- "2. **Timeline Construction**: Establish connections with temporal attributes. Pay close attention to time indicators and markers.\n"
- "3. **Logical Chains**: Beyond chronological order, identify the causal drivers between events.\n"
- "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."
-
-_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
- to visualize the 'Cause-Process-Effect' dynamic of a story.
-
- Example:
- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
- >>> embedder = OpenAIEmbeddings()
- >>> # Initialize template
- >>> timeline = NarrativeTimeline(llm_client=llm, embedder=embedder)
- >>> # Feed text with temporal shifts
- >>> text = "After the council, Frodo left the Shire. Months later, he reached the gates of Mordor."
- >>> timeline.feed_text(text)
- >>> timeline.show()
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- *,
- observation_time: Optional[str] = None,
- extraction_mode: str = "two_stage",
- chunk_size: int = 2048,
- chunk_overlap: int = 256,
- max_workers: int = 10,
- verbose: bool = False,
- **kwargs: Any,
- ):
- """
- Initialize NarrativeTimeline template.
-
- Args:
- llm_client: The language model client.
- embedder: Embeddings model for deduplication and indexing.
- observation_time: Base date for resolving relative time expressions like 'today' or 'yesterday'.
- extraction_mode: Defaults to 'two_stage' for higher temporal resolution accuracy.
- chunk_size: Max characters per processing chunk.
- chunk_overlap: Overlap between chunks.
- max_workers: Number of parallel extraction workers.
- verbose: Enable detailed logging.
- **kwargs: Extra arguments for AutoTemporalGraph.
- """
- super().__init__(
- node_schema=PlotPoint,
- edge_schema=TimeProgression,
- node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source}->{x.target}",
- time_in_edge_extractor=lambda x: x.time,
- nodes_in_edge_extractor=lambda x: (x.source, x.target),
- llm_client=llm_client,
- embedder=embedder,
- observation_time=observation_time,
- prompt=_PROMPT,
- prompt_for_node_extraction=_NODE_PROMPT,
- prompt_for_edge_extraction=_EDGE_PROMPT,
- extraction_mode=extraction_mode,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- max_workers=max_workers,
- verbose=verbose,
- **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 narrative timeline.
-
- Args:
- 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
-
- def edge_label_extractor(edge: TimeProgression) -> str:
- return f"[{edge.time}] {edge.logic}"
-
- 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/literature/symbolism_set.py b/hyperextract/templates/en/literature/symbolism_set.py
deleted file mode 100644
index c1aca73..0000000
--- a/hyperextract/templates/en/literature/symbolism_set.py
+++ /dev/null
@@ -1,112 +0,0 @@
-from typing import List, Optional, Any, Callable
-from pydantic import BaseModel, Field
-from langchain_core.language_models.chat_models import BaseChatModel
-from langchain_core.embeddings import Embeddings
-from hyperextract.types import AutoSet
-
-# ==============================================================================
-# 1. Schema Definitions
-# ==============================================================================
-
-class ImagerySymbol(BaseModel):
- """An image or symbol in a literary work."""
- symbol_name: str = Field(description="The name of the symbol/image (e.g., 'The Ocean', 'The Red Room', 'The Mockingbird').")
- literal_meanings: List[str] = Field(description="Literal references or descriptions of the image in the text.")
- metaphorical_meanings: List[str] = Field(description="Implicit symbolic meanings or deep metaphors associated with the image.")
- contexts: List[str] = Field(description="Key textual snippets or chapter summaries where the symbol appears.")
- thematic_connection: Optional[str] = Field(description="The connection between the symbol and the overall themes of the work.")
-
-# ==============================================================================
-# 2. Prompts
-# ==============================================================================
-
-_PROMPT = (
- "You are an expert literary critic. Your task is to identify and analyze recurring imagery and symbols within the text.\n\n"
- "Analysis Guidelines:\n"
- "1. **Normalization**: Ensure that variations of the same symbol (e.g., 'moonlight' and 'the moon') are grouped under a single standard symbol name to allow for information accumulation.\n"
- "2. **Layered Interpretation**: Distinguish between the literal description of the image and its symbolic significance.\n"
- "3. **Synthesis**: If a symbol appears in multiple parts of the text, continuously enrich its entry with new layers of meaning, context, and thematic significance.\n"
-)
-
-# ==============================================================================
-# 3. Template Class
-# ==============================================================================
-
-class SymbolismSet(AutoSet[ImagerySymbol]):
- """
- Applicable to: [Poetry, Modernist Novels, Literary Criticism, Essays]
-
- Knowledge pattern for aggregating and deeply analyzing literary imagery and symbols.
-
- Leveraging AutoSet's key-accumulation mechanism, this template automatically merges information
- about the same symbol (literal descriptions, metaphors, thematic links) from across the entire work into a single enriched entry.
-
- Example:
- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
- >>> embedder = OpenAIEmbeddings()
- >>> # Initialize template
- >>> symbolism = SymbolismSet(llm_client=llm, embedder=embedder)
- >>> # Feed text from different chapters
- >>> symbolism.feed_text("The green light at the end of the dock symbolizes Gatsby's hopes and dreams.")
- >>> symbolism.feed_text("Gatsby reached out towards the green light, representing the unattainable past.")
- >>> symbolism.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
- ):
- """
- Initialize SymbolismSet template.
-
- Args:
- llm_client: Language model client.
- embedder: Embeddings model for retrieval and visualization.
- chunk_size: Max characters per processing chunk.
- chunk_overlap: Overlap between chunks.
- max_workers: Parallel workers.
- verbose: Enable detailed logging.
- **kwargs: Extra arguments for AutoSet.
- """
- super().__init__(
- item_schema=ImagerySymbol,
- key_extractor=lambda x: x.symbol_name.strip().lower(), # Exact key match for normalization
- llm_client=llm_client,
- embedder=embedder,
- prompt=_PROMPT,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- max_workers=max_workers,
- verbose=verbose,
- **kwargs
- )
-
- def show(
- self,
- *,
- top_k_for_search: int = 3,
- top_k_for_chat: int = 3,
- ) -> None:
- """
- Visualize the symbolism and imagery repository.
-
- Args:
- top_k_for_search: Items to retrieve for search.
- top_k_for_chat: Items to retrieve for chat.
- """
- def item_label_extractor(item: ImagerySymbol) -> str:
- return item.symbol_name
-
- 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/news/__init__.py b/hyperextract/templates/en/news/__init__.py
index b33b750..e69de29 100644
--- a/hyperextract/templates/en/news/__init__.py
+++ b/hyperextract/templates/en/news/__init__.py
@@ -1,5 +0,0 @@
-from .breaking_event_graph import BreakingEventGraph
-from .topic_timeline import TopicTimeline
-from .opinion_set import OpinionSet
-
-__all__ = ["BreakingEventGraph", "TopicTimeline", "OpinionSet"]
diff --git a/hyperextract/templates/en/news/breaking_event_graph.py b/hyperextract/templates/en/news/breaking_event_graph.py
deleted file mode 100644
index 597e3bd..0000000
--- a/hyperextract/templates/en/news/breaking_event_graph.py
+++ /dev/null
@@ -1,84 +0,0 @@
-from typing import List, Optional, Any, Tuple
-from pydantic import BaseModel, Field
-from langchain_core.language_models.chat_models import BaseChatModel
-from langchain_core.embeddings import Embeddings
-from hyperextract.types import AutoGraph
-
-# ==============================================================================
-# 1. Schema Definition
-# ==============================================================================
-
-class NewsEntity(BaseModel):
- """Actors or objects involved in a breaking news event."""
- name: str = Field(description="Name of the person, organization, location, or country.")
- category: str = Field(description="Type (e.g., Politician, NGO, Media, Government Body).")
- attributes: List[str] = Field(description="Key descriptors or current status (e.g., 'Sanctioned', 'Reporting', 'Victim').")
-
-class NewsAction(BaseModel):
- """Actions, statements, or events linking two news entities."""
- source: str = Field(description="The initiator of the action.")
- target: str = Field(description="The recipient or object of the action.")
- action_type: str = Field(description="Nature of the action (e.g., Condemnation, Signing Agreement, Direct Strike).")
- details: str = Field(description="Specific context or key information about the interaction.")
- evidence: List[str] = Field(description="Source quotes or specific facts supporting this action.")
-
-# ==============================================================================
-# 2. Prompts
-# ==============================================================================
-
-_PROMPT = (
- "You are an expert geopolitical intelligence analyst. Your task is to extract the core structure of breaking events from news reports.\n\n"
- "Extraction Requirements:\n"
- "1. **Entity Identification**: Focus on main stakeholders (individuals, organizations, or nations).\n"
- "2. **Dynamic Interaction**: Capture the 'Who did What to Whom'.\n"
- "3. **Evidence Extraction**: Ensure specific actions are backed by verified statements or observable facts reported in the text.\n"
-)
-
-_NODE_PROMPT = "Identify all significant stakeholders in the breaking news. Categorize them and list their current roles or status mentioned."
-_EDGE_PROMPT = "Connect the stakeholders through their interactions. Define the nature of these actions and provide supporting evidence from the text."
-
-# ==============================================================================
-# 3. Template Class
-# ==============================================================================
-
-class BreakingEventGraph(AutoGraph[NewsEntity, NewsAction]):
- """
- Applicable to: [Breaking News, Flash Reports, International Incidents, Press Releases]
-
- A template designed for rapid mapping of key actors and their interactions in urgent news scenarios.
-
- It excels at clarifying complex multilateral relationships during sudden events or crises.
-
- Example:
- >>> graph = BreakingEventGraph(llm_client=llm, embedder=embedder)
- >>> text = "Country A imposed sanctions on Entity B, while Organization C called for a ceasefire."
- >>> graph.feed_text(text).show()
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- *,
- extraction_mode: str = "two_stage",
- **kwargs: Any
- ):
- super().__init__(
- node_schema=NewsEntity,
- edge_schema=NewsAction,
- node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source}->{x.action_type}->{x.target}",
- nodes_in_edge_extractor=lambda x: (x.source, x.target),
- llm_client=llm_client,
- embedder=embedder,
- prompt=_PROMPT,
- prompt_for_node_extraction=_NODE_PROMPT,
- prompt_for_edge_extraction=_EDGE_PROMPT,
- extraction_mode=extraction_mode,
- **kwargs
- )
-
- def show(self, **kwargs):
- def n_label(node: NewsEntity) -> str: return f"{node.name} ({node.category})"
- def e_label(edge: NewsAction) -> str: return f"{edge.action_type}"
- super().show(node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs)
diff --git a/hyperextract/templates/en/news/opinion_set.py b/hyperextract/templates/en/news/opinion_set.py
deleted file mode 100644
index bab2988..0000000
--- a/hyperextract/templates/en/news/opinion_set.py
+++ /dev/null
@@ -1,69 +0,0 @@
-from typing import List, 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 import AutoSet
-
-# ==============================================================================
-# 1. Schema Definition
-# ==============================================================================
-
-class OpinionStance(BaseModel):
- """The stance and viewpoint held by an entity on a specific topic."""
- entity: str = Field(description="The individual, organization, media outlet, or group expressing the view.")
- stance: str = Field(description="Core stance label (e.g., Support, Strong Opposition, Neutral, Questioning).")
- key_argument: str = Field(description="The central argument or demand supporting this stance.")
- evidence_provided: List[str] = Field(description="Supporting evidence, data, or facts provided by the entity.")
- potential_interest: Optional[str] = Field(description="Implicit interests or motivations behind this stance.")
-
-# ==============================================================================
-# 2. Prompts
-# ==============================================================================
-
-_PROMPT = (
- "You are a multi-dimensional public opinion analyst. Your task is to identify and summarize the viewpoints and stances of different stakeholders from reports or commentaries.\n\n"
- "Extraction Requirements:\n"
- "1. **Entity Definition**: Clearly identify who is speaking.\n"
- "2. **Stance Deconstruction**: Don't just record what was said; interpret the core attitude (stance) through tone and context.\n"
- "3. **Argument Mapping**: Extract persuasive evidence from their statements.\n"
- "4. **Horizontal Consolidation**: If multiple texts mention the same stance from the same entity, accumulate the new evidence into the existing entry.\n"
-)
-
-# ==============================================================================
-# 3. Template Class
-# ==============================================================================
-
-class OpinionSet(AutoSet[OpinionStance]):
- """
- Applicable to: [Public Opinion Analysis, Media Reviews, Debate Transcripts, Editorial Columns]
-
- A knowledge mining template for summarizing the distribution of viewpoints and evidence across different actors in news and discourse.
-
- Uses an AutoSet structure, accumulating knowledge based on the 'Entity + Stance' key, suitable for mapping complex debates.
-
- Example:
- >>> opinion_set = OpinionSet(llm_client=llm, embedder=embedder)
- >>> text = "Organization A opposed the project, citing wetland destruction. The government argued it creates jobs."
- >>> opinion_set.feed_text(text).show()
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- **kwargs: Any
- ):
- super().__init__(
- schema=OpinionStance,
- # Use combination of Entity and Stance as the key to accumulate similar views
- key_extractor=lambda x: f"{x.entity.strip()}:{x.stance.strip()}",
- llm_client=llm_client,
- embedder=embedder,
- prompt=_PROMPT,
- **kwargs
- )
-
- def show(self, **kwargs):
- def label_func(item: OpinionStance) -> str:
- return f"[{item.stance}] {item.entity}: {item.key_argument}"
- super().show(item_label_extractor=label_func, **kwargs)
diff --git a/hyperextract/templates/en/news/topic_timeline.py b/hyperextract/templates/en/news/topic_timeline.py
deleted file mode 100644
index 2802a1b..0000000
--- a/hyperextract/templates/en/news/topic_timeline.py
+++ /dev/null
@@ -1,85 +0,0 @@
-from typing import List, Optional, Any, Tuple
-from pydantic import BaseModel, Field
-from langchain_core.language_models.chat_models import BaseChatModel
-from langchain_core.embeddings import Embeddings
-from hyperextract.types import AutoTemporalGraph
-
-# ==============================================================================
-# 1. Schema Definition
-# ==============================================================================
-
-class NewsEventNode(BaseModel):
- """Core milestone nodes in a topical news story."""
- event_summary: str = Field(description="Short title or summary of the event.")
- location: Optional[str] = Field(description="Specific geographic location of the event.")
- key_participants: List[str] = Field(description="List of core people or organizations involved.")
-
-class NewsTimelineProgression(BaseModel):
- """The logic of event evolution over time."""
- source: str = Field(description="Summary of the preceding event.")
- target: str = Field(description="Summary of the subsequent event.")
- time: str = Field(description="Exact point in time. You MUST resolve relative expressions (e.g., 'two weeks later') into absolute dates based on the context.")
- evolution_type: str = Field(description="Nature of the development (e.g., Escalation, Turning Point, De-escalation, Chain Reaction).")
- description: str = Field(description="Detailed description of this specific stage of evolution.")
-
-# ==============================================================================
-# 2. Prompts
-# ==============================================================================
-
-_PROMPT = (
- "You are a senior investigative journalist. Your task is to organize scattered news reports into a coherent narrative thread of development.\n\n"
- "Extraction Requirements:\n"
- "1. **Event Extraction**: Identify single, milestone events.\n"
- "2. **Temporal Alignment**: Resolve all temporal markers into absolute formats and place them on the edges (Progression).\n"
- "3. **Dynamic Links**: Emphasize how events are logically triggered by time and causality.\n"
-)
-
-_NODE_PROMPT = "Identify key milestone events in the reporting. Provide concise titles, locations, and core participants for each."
-_EDGE_PROMPT = "Establish a chronological chain between milestone events. Resolve relative time based on the provided reference dates."
-
-# ==============================================================================
-# 3. Template Class
-# ==============================================================================
-
-class TopicTimeline(AutoTemporalGraph[NewsEventNode, NewsTimelineProgression]):
- """
- Applicable to: [Series Reports, Long-form Investigative Journalism, Dossiers, Historical Retrospectives]
-
- A template used to link disconnected news reports into a coherent topical evolution timeline.
-
- Focuses on the vertical development trajectory of an issue, suitable for tracking long-term social trends or policy changes.
-
- Example:
- >>> timeline = TopicTimeline(llm_client=llm, embedder=embedder)
- >>> text = "Bill proposed in 2023. Six months later, it passed after debate. Effective next month."
- >>> timeline.feed_text(text).show()
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- *,
- extraction_mode: str = "two_stage",
- **kwargs: Any
- ):
- super().__init__(
- node_schema=NewsEventNode,
- edge_schema=NewsTimelineProgression,
- node_key_extractor=lambda x: x.event_summary.strip(),
- edge_key_extractor=lambda x: f"{x.source}>>{x.target}",
- time_in_edge_extractor=lambda x: x.time,
- nodes_in_edge_extractor=lambda x: (x.source, x.target),
- llm_client=llm_client,
- embedder=embedder,
- prompt=_PROMPT,
- prompt_for_node_extraction=_NODE_PROMPT,
- prompt_for_edge_extraction=_EDGE_PROMPT,
- extraction_mode=extraction_mode,
- **kwargs
- )
-
- def show(self, **kwargs):
- def n_label(node: NewsEventNode) -> str: return node.event_summary
- def e_label(edge: NewsTimelineProgression) -> str: return f"[{edge.time}] {edge.evolution_type}"
- super().show(node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs)
diff --git a/hyperextract/templates/en/travel/__init__.py b/hyperextract/templates/en/travel/__init__.py
deleted file mode 100644
index d06326e..0000000
--- a/hyperextract/templates/en/travel/__init__.py
+++ /dev/null
@@ -1,7 +0,0 @@
-"""
-Travel & Geography Domain Templates
-
-This module provides knowledge extraction templates for the travel and geography domain,
-including travel guides, geographic encyclopedic content, and more.
-Supports extraction of geographic relationships, travel routes, and spatial features.
-"""
diff --git a/hyperextract/templates/zh/__init__.py b/hyperextract/templates/zh/__init__.py
index efc305d..75fedc0 100644
--- a/hyperextract/templates/zh/__init__.py
+++ b/hyperextract/templates/zh/__init__.py
@@ -19,7 +19,6 @@ from .general import (
PenaltyMapping,
ComplianceLogic,
)
-from .agriculture import CropCycleGraph, LivestockGraph, AgriPestControl
from .biology import (
# 生物学专著
SpeciesInteractionWeb,
@@ -59,7 +58,6 @@ from .finance import (
MultiSourceSentimentHypergraph,
MarketNarrativeTimeline,
)
-from .literature import CharacterRelationshipGraph, NarrativeTimeline, SymbolismSet
from .medicine import (
# 医学教科书与专著
PathologyHypergraph,
@@ -84,7 +82,6 @@ from .medicine import (
AdverseReactionStats,
)
-from .news import BreakingEventGraph, TopicTimeline, OpinionSet
from .history import (
# 历史专著
@@ -214,12 +211,4 @@ __all__ = [
"BiochemicalReactionHypergraph",
"RegulatoryNetwork",
"BiodiversityRegistry",
- # Agriculture
- "CropCycleGraph",
- "LivestockGraph",
- "AgriPestControl",
- # Literature
- "CharacterRelationshipGraph",
- "NarrativeTimeline",
- "SymbolismSet",
]
diff --git a/hyperextract/templates/zh/agriculture/__init__.py b/hyperextract/templates/zh/agriculture/__init__.py
index 556a0eb..5f28270 100644
--- a/hyperextract/templates/zh/agriculture/__init__.py
+++ b/hyperextract/templates/zh/agriculture/__init__.py
@@ -1,15 +1 @@
-from .crop_cycle import CropCycleGraph, AgriEntity, AgriRelation
-from .livestock import LivestockGraph, AnimalNode, BreedingRelation
-from .pest_control import AgriPestControl, AgriPestEntity, AgriPestRelation
-
-__all__ = [
- "CropCycleGraph",
- "AgriEntity",
- "AgriRelation",
- "LivestockGraph",
- "AnimalNode",
- "BreedingRelation",
- "AgriPestControl",
- "AgriPestEntity",
- "AgriPestRelation"
-]
+
\ No newline at end of file
diff --git a/hyperextract/templates/zh/agriculture/crop_cycle.py b/hyperextract/templates/zh/agriculture/crop_cycle.py
deleted file mode 100644
index af6b983..0000000
--- a/hyperextract/templates/zh/agriculture/crop_cycle.py
+++ /dev/null
@@ -1,152 +0,0 @@
-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 import AutoGraph
-
-# ==============================================================================
-# 1. Schema 定义 (Schema Definitions)
-# ==============================================================================
-
-class AgriEntity(BaseModel):
- """农业领域实体(如作物、土壤、病虫害、防治措施、农机具)。"""
- name: str = Field(description="农业实体的名称。")
- category: str = Field(
- description="类别:'作物', '生长阶段', '土壤/气候条件', '农事活动', '逆境/病虫害', '农资/肥料'。"
- )
- description: Optional[str] = Field(description="实体的具体特征或状态描述。")
-
-class AgriRelation(BaseModel):
- """农业实体间的关系(如'需求'、'受...影响'、'继...之后')。"""
- source: str = Field(description="源实体名称。")
- target: str = Field(description="目标实体名称。")
- relation_type: str = Field(
- description="类型:'处于阶段', '影响', '需要操作', '施用于', '进入下一阶段'。"
- )
- specification: Optional[str] = Field(description="具体的用量、时机或影响细节。")
-
-# ==============================================================================
-# 2. 提示词 (Prompts)
-# ==============================================================================
-
-_PROMPT = (
- "你是一位资深农艺师。请从文本中提取作物生长与管理图谱。\n\n"
- "提取指南:\n"
- "- 识别作物及其具体的生长阶段(如:播种、开花、成熟)。\n"
- "- 将土壤条件、天气要求以及必要的农事活动(灌溉、施肥)关联到具体的阶段。\n"
- "- 记录任何提及的威胁因素(如病虫害)及其对作物的影响。"
-)
-
-_NODE_PROMPT = (
- "你是一位资深农艺师。你的任务是从文本中识别并提取所有关键农业实体(节点)。\n\n"
- "提取规则:\n"
- "- 识别作物类型、具体生长阶段、环境因子(如 pH 值、温度)以及农事任务。\n"
- "- 捕捉生物逆境,如具体的病虫害、真菌或疾病。\n"
- "- 将每个节点归入适当的类别:'作物'、'生长阶段'、'农事活动'等。\n"
- "- 在此阶段请勿识别这些实体之间的逻辑顺序或依赖关系。"
-)
-
-_EDGE_PROMPT = (
- "你是一位资深农艺师。根据农业实体清单,映射其中的逻辑链路和周期关系(边)。\n\n"
- "提取规则:\n"
- "- 在生长阶段之间建立顺序链接。\n"
- "- 将农事任务关联到必须执行它们的具体生长阶段上。\n"
- "- 映射环境条件和病虫害如何影响作物及其生长阶段。\n"
- "- 使用特定的关系类型,如 '处于阶段'、'需要操作'、'抑制' 或 '施用于'。\n"
- "- 仅连接提供的农业实体清单中存在的实体。"
-)
-
-# ==============================================================================
-# 3. 模板类 (Template Class)
-# ==============================================================================
-
-class CropCycleGraph(AutoGraph[AgriEntity, AgriRelation]):
- """
- 用于映射作物生长阶段、环境要求和农事活动的模板。
-
- 适用于精准农业、作物管理指南以及季节性种植规划。
-
- 示例:
- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
- >>> embedder = OpenAIEmbeddings()
- >>> graph = CropCycleGraph(llm_client=llm, embedder=embedder)
- >>> text = "玉米在营养生长阶段需要大量的氮肥。"
- >>> graph.feed_text(text)
- >>> print(graph.nodes) # 提取出:玉米、氮肥、营养生长阶段
- """
- 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
- ):
- """
- 初始化 CropCycleGraph 模板。
-
- Args:
- llm_client: 用于提取的语言模型客户端。
- embedder: 用于去重的嵌入模型。
- extraction_mode: "one_stage" 或 "two_stage"。
- chunk_size: 每个分块的最大字符数。
- chunk_overlap: 分块间的重叠字符数。
- max_workers: 并行处理的最大 worker 数量。
- verbose: 是否开启进度日志。
- **kwargs: 传递给 AutoGraph 的其他参数。
- """
- super().__init__(
- node_schema=AgriEntity,
- edge_schema=AgriRelation,
- node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation_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 graph using OntoSight.
-
- Args:
- top_k_nodes_for_search (int): Number of nodes to retrieve for search context. Default 3.
- top_k_edges_for_search (int): Number of edges to retrieve for search context. Default 3.
- top_k_nodes_for_chat (int): Number of nodes to retrieve for chat context. Default 3.
- top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
- """
- def node_label_extractor(node: AgriEntity) -> str:
- info = f" ({node.category})" if getattr(node, "category", None) else ""
- return f"{node.name}{info}"
-
- def edge_label_extractor(edge: AgriRelation) -> str:
- return f"{edge.relation_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/agriculture/livestock.py b/hyperextract/templates/zh/agriculture/livestock.py
deleted file mode 100644
index 1063900..0000000
--- a/hyperextract/templates/zh/agriculture/livestock.py
+++ /dev/null
@@ -1,148 +0,0 @@
-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 import AutoGraph
-
-# ==============================================================================
-# 1. Schema 定义 (Schema Definitions)
-# ==============================================================================
-
-
-class AnimalNode(BaseModel):
- """畜牧管理中的实体(如个体动物、品种、群体、健康状况)。"""
-
- name: str = Field(description="动物个体或群体的名称/ID。")
- category: str = Field(
- description="类别:'个体', '品种', '品系', '健康状况', '营养/饲料', '设施'。"
- )
- traits: Optional[str] = Field(description="关键体貌特征、基因标记或健康指标。")
-
-
-class BreedingRelation(BaseModel):
- """育种与健康管理中的关系。"""
-
- source: str = Field(description="源畜牧实体。")
- target: str = Field(description="目标畜牧实体。")
- relation_type: str = Field(
- description="类型:'父代/母代', '与...交配', '属于', '诊断为', '饲喂'。"
- )
- details: Optional[str] = Field(description="继承特征、剂量或具体的健康观察。")
-
-
-# ==============================================================================
-# 2. 提示词 (Prompts)
-# ==============================================================================
-
-_PROMPT = (
- "你是一位畜牧专家和遗传学家。请从文本中提取育种与健康管理图谱。\n\n"
- "提取指南:\n"
- "- 识别动物个体及其品种。\n"
- "- 映射家谱关系(亲子关系)和育种配对。\n"
- "- 将动物与其健康状况、疫苗接种和营养记录关联起来。"
-)
-
-_NODE_PROMPT = "请提取畜牧实体:识别特定动物(通过ID或名称)、品种、健康状况、疫苗类型以及特定的饲料。为每一项提供相关的特征或指标。"
-
-_EDGE_PROMPT = "逻辑化地连接畜牧实体。映射家族树(亲缘链接)、育种历史以及医疗/营养事件。确保准确使用'与...交配'或'饲喂'等关系类型。"
-
-# ==============================================================================
-# 3. 模板类 (Template Class)
-# ==============================================================================
-
-
-class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):
- """
- 用于管理畜牧系谱、健康记录和育种计划的模板。
-
- 适用于牧场管理软件、兽医记录和基因追踪。
-
- 示例:
- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
- >>> embedder = OpenAIEmbeddings()
- >>> graph = LivestockGraph(llm_client=llm, embedder=embedder)
- >>> text = "402号母牛(安格斯)与09号公牛配种以提高肉质。"
- >>> graph.feed_text(text)
- >>> print(graph.edges) # 提取育种关系
- """
-
- 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,
- ):
- """
- 初始化 LivestockGraph 模板。
-
- Args:
- llm_client: 用于提取的语言模型客户端。
- embedder: 用于去重的嵌入模型。
- extraction_mode: "one_stage" 或 "two_stage"。
- chunk_size: 每个分块的最大字符数。
- chunk_overlap: 分块间的重叠字符数。
- max_workers: 并行处理的最大 worker 数量。
- verbose: 是否开启进度日志。
- **kwargs: 传递给 AutoGraph 的其他参数。
- """
- super().__init__(
- node_schema=AnimalNode,
- edge_schema=BreedingRelation,
- node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: (
- f"{x.source.strip()}--({x.relation_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 graph using OntoSight.
-
- Args:
- top_k_nodes_for_search (int): Number of nodes to retrieve for search context. Default 3.
- top_k_edges_for_search (int): Number of edges to retrieve for search context. Default 3.
- top_k_nodes_for_chat (int): Number of nodes to retrieve for chat context. Default 3.
- top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
- """
-
- def node_label_extractor(node: AnimalNode) -> str:
- info = f" ({node.category})" if getattr(node, "category", None) else ""
- return f"{node.name}{info}"
-
- def edge_label_extractor(edge: BreedingRelation) -> str:
- return f"{edge.relation_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/agriculture/pest_control.py b/hyperextract/templates/zh/agriculture/pest_control.py
deleted file mode 100644
index 744b15d..0000000
--- a/hyperextract/templates/zh/agriculture/pest_control.py
+++ /dev/null
@@ -1,117 +0,0 @@
-from typing import Optional, Any, Callable
-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 AgriPestEntity(BaseModel):
- """农业病虫害防治领域的实体(如害虫、病害、作物、症状、防治方法)。"""
-
- name: str = Field(description="病虫害、作物、病原体或药剂的名称。")
- category: str = Field(
- description="类别:'害虫', '病害', '寄主作物', '受害症状', '防治方法', '化学药剂'。"
- )
- description: Optional[str] = Field(
- None, description="详细描述、生物学特征或发生规律。"
- )
-
-
-class AgriPestRelation(BaseModel):
- """农业实体之间的关系(如'危害'、'导致'、'防治手段')。"""
-
- source: str = Field(description="源实体名称。")
- target: str = Field(description="目标实体名称。")
- relation_type: str = Field(
- description="类型:'危害', '寄生', '导致症状', '防治手段', '对...敏感', '发生于'。"
- )
- detail: Optional[str] = Field(
- None, description="具体的发生环境、用药剂量或危害程度。"
- )
-
-
-# ==============================================================================
-# 2. 提示词 (Prompt)
-# ==============================================================================
-
-_PROMPT = """
-你是一位资深农艺师和植物保护专家。
-你的任务是从文本中提取详尽的农作物病虫害及其防治知识图谱。
-
-指南:
-1. 识别生物威胁:包括害虫、真菌、细菌、病毒或杂草。
-2. 建立威胁与寄主作物、具体受害症状(如:叶斑、秆腐、卷叶)之间的链接。
-3. 映射病虫害综合防治 (IPM) 策略,包括生物防治、物理防治和化学防治方法。
-4. 提取文本中提到的具体农药名称、施用剂量及最佳施药时期。
-"""
-
-# ==============================================================================
-# 3. 模板类
-# ==============================================================================
-
-
-class AgriPestControl(AutoGraph[AgriPestEntity, AgriPestRelation]):
- """
- 农业病虫害防治知识图谱模板。
-
- 将技术手册和防治指南转化为结构化的防治策略。
- """
-
- 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,
- ):
- """初始化 AgriPestControl 模板。"""
- super().__init__(
- node_schema=AgriPestEntity,
- edge_schema=AgriPestRelation,
- node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation_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,
- **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:
- """可视化病虫害防治知识图谱。"""
-
- def node_label_extractor(node: AgriPestEntity) -> str:
- return f"{node.name} ({node.category})"
-
- def edge_label_extractor(edge: AgriPestRelation) -> str:
- return f"{edge.relation_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/finance/analyst_qa_graph.py b/hyperextract/templates/zh/finance/analyst_qa_graph.py
index 7b6cc89..81540fd 100644
--- a/hyperextract/templates/zh/finance/analyst_qa_graph.py
+++ b/hyperextract/templates/zh/finance/analyst_qa_graph.py
@@ -102,7 +102,7 @@ class AnalystQAGraph(AutoGraph[QAParticipant, QAInteraction]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> qa = AnalystQAGraph(llm_client=llm, embedder=embedder)
>>> transcript = "分析师:能否讨论一下利润率展望?CEO:我们预计利润率将..."
diff --git a/hyperextract/templates/zh/finance/call_sentiment_hypergraph.py b/hyperextract/templates/zh/finance/call_sentiment_hypergraph.py
index b322e79..0e1970a 100644
--- a/hyperextract/templates/zh/finance/call_sentiment_hypergraph.py
+++ b/hyperextract/templates/zh/finance/call_sentiment_hypergraph.py
@@ -103,7 +103,7 @@ class CallSentimentHypergraph(AutoHypergraph[CallTopic, SentimentCluster]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> sentiment = CallSentimentHypergraph(llm_client=llm, embedder=embedder)
>>> transcript = "CEO:我们对 AI 收入增长感到非常兴奋..."
diff --git a/hyperextract/templates/zh/finance/company_history_timeline.py b/hyperextract/templates/zh/finance/company_history_timeline.py
index e7c1e6f..f630d82 100644
--- a/hyperextract/templates/zh/finance/company_history_timeline.py
+++ b/hyperextract/templates/zh/finance/company_history_timeline.py
@@ -102,7 +102,7 @@ class CompanyHistoryTimeline(
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> history = CompanyHistoryTimeline(llm_client=llm, embedder=embedder)
>>> text = "公司于 2015 年由张三创立。2017 年完成 1000 万美元 A 轮融资..."
diff --git a/hyperextract/templates/zh/finance/earnings_call_summary.py b/hyperextract/templates/zh/finance/earnings_call_summary.py
index 94299f1..9849d92 100644
--- a/hyperextract/templates/zh/finance/earnings_call_summary.py
+++ b/hyperextract/templates/zh/finance/earnings_call_summary.py
@@ -102,7 +102,7 @@ class EarningsCallSummary(AutoModel[EarningsCallSummarySchema]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> summary = EarningsCallSummary(llm_client=llm, embedder=embedder)
>>> transcript = "下午好。第三季度收入为 948 亿美元,超出一致预期..."
diff --git a/hyperextract/templates/zh/finance/factor_influence_hypergraph.py b/hyperextract/templates/zh/finance/factor_influence_hypergraph.py
index c9d5cea..e9d2993 100644
--- a/hyperextract/templates/zh/finance/factor_influence_hypergraph.py
+++ b/hyperextract/templates/zh/finance/factor_influence_hypergraph.py
@@ -108,7 +108,7 @@ class FactorInfluenceHypergraph(AutoHypergraph[InvestmentFactor, FactorInteracti
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> factors = FactorInfluenceHypergraph(llm_client=llm, embedder=embedder)
>>> report = "利率上升叠加强劲 GDP 和 AI 资本支出,推动向优质成长股轮动..."
diff --git a/hyperextract/templates/zh/finance/filing_financial_snapshot.py b/hyperextract/templates/zh/finance/filing_financial_snapshot.py
index ce5f6df..c48644a 100644
--- a/hyperextract/templates/zh/finance/filing_financial_snapshot.py
+++ b/hyperextract/templates/zh/finance/filing_financial_snapshot.py
@@ -117,7 +117,7 @@ class FilingFinancialSnapshot(AutoModel[FilingFinancialSnapshotSchema]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> snapshot = FilingFinancialSnapshot(llm_client=llm, embedder=embedder)
>>> filing_text = "第8项 财务报表:营收为3943亿美元..."
diff --git a/hyperextract/templates/zh/finance/filing_risk_factor_set.py b/hyperextract/templates/zh/finance/filing_risk_factor_set.py
index ec80f58..1e4b47a 100644
--- a/hyperextract/templates/zh/finance/filing_risk_factor_set.py
+++ b/hyperextract/templates/zh/finance/filing_risk_factor_set.py
@@ -77,7 +77,7 @@ class FilingRiskFactorSet(AutoSet[RiskFactorItem]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> risk_set = FilingRiskFactorSet(llm_client=llm, embedder=embedder)
>>> filing = "第1A项 风险因素:我们面临重大网络安全风险..."
diff --git a/hyperextract/templates/zh/finance/financial_data_temporal_graph.py b/hyperextract/templates/zh/finance/financial_data_temporal_graph.py
index 1440272..a71d683 100644
--- a/hyperextract/templates/zh/finance/financial_data_temporal_graph.py
+++ b/hyperextract/templates/zh/finance/financial_data_temporal_graph.py
@@ -134,7 +134,7 @@ class FinancialDataTemporalGraph(
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> graph = FinancialDataTemporalGraph(llm_client=llm, embedder=embedder)
>>> filing = "FY2024年度,苹果公司报告营收3943亿美元,较FY2023年的3658亿美元增长7.8%..."
diff --git a/hyperextract/templates/zh/finance/financial_event_causal_graph.py b/hyperextract/templates/zh/finance/financial_event_causal_graph.py
index 66ede64..bc74f80 100644
--- a/hyperextract/templates/zh/finance/financial_event_causal_graph.py
+++ b/hyperextract/templates/zh/finance/financial_event_causal_graph.py
@@ -108,7 +108,7 @@ class FinancialEventCausalGraph(AutoGraph[FinancialEventNode, EventCausalEdge]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> causal = FinancialEventCausalGraph(llm_client=llm, embedder=embedder)
>>> news = "美联储加息 25 个基点,推动银行股上涨,同时科技股遭到抛售..."
diff --git a/hyperextract/templates/zh/finance/financial_forecast.py b/hyperextract/templates/zh/finance/financial_forecast.py
index 7a90089..6817fde 100644
--- a/hyperextract/templates/zh/finance/financial_forecast.py
+++ b/hyperextract/templates/zh/finance/financial_forecast.py
@@ -77,7 +77,7 @@ class FinancialForecast(AutoList[ForecastItem]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> forecast = FinancialForecast(llm_client=llm, embedder=embedder)
>>> report = "我们将 FY2025 收入预测上调至 1205 亿美元(此前为 1150 亿美元)..."
diff --git a/hyperextract/templates/zh/finance/management_guidance_list.py b/hyperextract/templates/zh/finance/management_guidance_list.py
index 8b82c0e..715715f 100644
--- a/hyperextract/templates/zh/finance/management_guidance_list.py
+++ b/hyperextract/templates/zh/finance/management_guidance_list.py
@@ -78,7 +78,7 @@ class ManagementGuidanceList(AutoList[GuidanceItem]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> guidance = ManagementGuidanceList(llm_client=llm, embedder=embedder)
>>> transcript = "对于第四季度,我们预计收入在 950 至 970 亿美元之间..."
diff --git a/hyperextract/templates/zh/finance/market_narrative_timeline.py b/hyperextract/templates/zh/finance/market_narrative_timeline.py
index 739a184..e752ce6 100644
--- a/hyperextract/templates/zh/finance/market_narrative_timeline.py
+++ b/hyperextract/templates/zh/finance/market_narrative_timeline.py
@@ -113,7 +113,7 @@ class MarketNarrativeTimeline(
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> narrative = MarketNarrativeTimeline(llm_client=llm, embedder=embedder)
>>> commentary = "市场在 2024 年第二季度从通胀恐惧转向软着陆希望..."
diff --git a/hyperextract/templates/zh/finance/market_sentiment_model.py b/hyperextract/templates/zh/finance/market_sentiment_model.py
index ee55b30..9aa9028 100644
--- a/hyperextract/templates/zh/finance/market_sentiment_model.py
+++ b/hyperextract/templates/zh/finance/market_sentiment_model.py
@@ -93,7 +93,7 @@ class MarketSentimentModel(AutoModel[MarketSentimentSnapshot]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> sentiment = MarketSentimentModel(llm_client=llm, embedder=embedder)
>>> news = "科技股在 NVDA 公布创纪录财报后大幅上涨..."
diff --git a/hyperextract/templates/zh/finance/material_event_timeline.py b/hyperextract/templates/zh/finance/material_event_timeline.py
index 065b483..ff08986 100644
--- a/hyperextract/templates/zh/finance/material_event_timeline.py
+++ b/hyperextract/templates/zh/finance/material_event_timeline.py
@@ -110,7 +110,7 @@ class MaterialEventTimeline(AutoTemporalGraph[MaterialEventEntity, MaterialEvent
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> timeline = MaterialEventTimeline(llm_client=llm, embedder=embedder)
>>> filing = "Item 5.02:2024年3月15日,董事会任命张三为首席执行官..."
diff --git a/hyperextract/templates/zh/finance/mda_narrative_graph.py b/hyperextract/templates/zh/finance/mda_narrative_graph.py
index af5f2c4..f8f0f2c 100644
--- a/hyperextract/templates/zh/finance/mda_narrative_graph.py
+++ b/hyperextract/templates/zh/finance/mda_narrative_graph.py
@@ -100,7 +100,7 @@ class MDANarrativeGraph(AutoGraph[MDAFactor, MDANarrativeEdge]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> mda = MDANarrativeGraph(llm_client=llm, embedder=embedder)
>>> text = "营收增长12%,主要受益于云计算业务的强劲需求..."
diff --git a/hyperextract/templates/zh/finance/multi_source_sentiment_hypergraph.py b/hyperextract/templates/zh/finance/multi_source_sentiment_hypergraph.py
index 6ea5a1c..161313f 100644
--- a/hyperextract/templates/zh/finance/multi_source_sentiment_hypergraph.py
+++ b/hyperextract/templates/zh/finance/multi_source_sentiment_hypergraph.py
@@ -117,7 +117,7 @@ class MultiSourceSentimentHypergraph(
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> fusion = MultiSourceSentimentHypergraph(llm_client=llm, embedder=embedder)
>>> text = "彭博社报道科技股上涨。同时高盛上调 AAPL 评级。推特情绪看涨。"
diff --git a/hyperextract/templates/zh/finance/proceeds_usage.py b/hyperextract/templates/zh/finance/proceeds_usage.py
index 4e1e3c1..3b68b9e 100644
--- a/hyperextract/templates/zh/finance/proceeds_usage.py
+++ b/hyperextract/templates/zh/finance/proceeds_usage.py
@@ -70,7 +70,7 @@ class ProceedsUsage(AutoList[ProceedsItem]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> proceeds = ProceedsUsage(llm_client=llm, embedder=embedder)
>>> prospectus = "我们拟将约 1.5 亿美元用于研发,1 亿美元用于偿还债务..."
diff --git a/hyperextract/templates/zh/finance/research_note_summary.py b/hyperextract/templates/zh/finance/research_note_summary.py
index b5704b8..0698c00 100644
--- a/hyperextract/templates/zh/finance/research_note_summary.py
+++ b/hyperextract/templates/zh/finance/research_note_summary.py
@@ -101,7 +101,7 @@ class ResearchNoteSummary(AutoModel[ResearchNoteSummarySchema]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> summary = ResearchNoteSummary(llm_client=llm, embedder=embedder)
>>> report = "我们将 AAPL 评级上调为买入,目标价 200 美元..."
diff --git a/hyperextract/templates/zh/finance/risk_assessment.py b/hyperextract/templates/zh/finance/risk_assessment.py
index c5e2127..3ede275 100644
--- a/hyperextract/templates/zh/finance/risk_assessment.py
+++ b/hyperextract/templates/zh/finance/risk_assessment.py
@@ -104,7 +104,7 @@ class RiskAssessmentGraph(AutoGraph[RiskFactor, RiskTransmissionEdge]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> risk_graph = RiskAssessmentGraph(llm_client=llm, embedder=embedder)
>>> filing_text = "Item 1A. 风险因子:汇率波动可能对利润率造成重大不利影响..."
diff --git a/hyperextract/templates/zh/finance/risk_factor_list.py b/hyperextract/templates/zh/finance/risk_factor_list.py
index 1ff6a19..1b5fed8 100644
--- a/hyperextract/templates/zh/finance/risk_factor_list.py
+++ b/hyperextract/templates/zh/finance/risk_factor_list.py
@@ -73,7 +73,7 @@ class RiskFactorList(AutoList[RiskItem]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> risks = RiskFactorList(llm_client=llm, embedder=embedder)
>>> report = "主要风险包括:1) 欧盟数字市场法合规成本..."
diff --git a/hyperextract/templates/zh/finance/segment_performance_list.py b/hyperextract/templates/zh/finance/segment_performance_list.py
index 5fef776..976a078 100644
--- a/hyperextract/templates/zh/finance/segment_performance_list.py
+++ b/hyperextract/templates/zh/finance/segment_performance_list.py
@@ -77,7 +77,7 @@ class SegmentPerformanceList(AutoList[SegmentPerformanceItem]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> segments = SegmentPerformanceList(llm_client=llm, embedder=embedder)
>>> filing = "美洲地区板块营收为482亿美元,同比增长12%..."
diff --git a/hyperextract/templates/zh/finance/shareholder_structure.py b/hyperextract/templates/zh/finance/shareholder_structure.py
index 9726478..17997b0 100644
--- a/hyperextract/templates/zh/finance/shareholder_structure.py
+++ b/hyperextract/templates/zh/finance/shareholder_structure.py
@@ -109,7 +109,7 @@ class ShareholderStructure(AutoGraph[OwnershipEntity, OwnershipEdge]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> ownership = ShareholderStructure(llm_client=llm, embedder=embedder)
>>> prospectus = "下表列示实益所有权情况:CEO 持有 15.3%..."
diff --git a/hyperextract/templates/zh/finance/supply_chain.py b/hyperextract/templates/zh/finance/supply_chain.py
index 01019f3..bdfffc4 100644
--- a/hyperextract/templates/zh/finance/supply_chain.py
+++ b/hyperextract/templates/zh/finance/supply_chain.py
@@ -82,7 +82,7 @@ class SupplyChainGraph(AutoGraph[SupplyEntity, SupplyTransaction]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> supply_chain = SupplyChainGraph(llm_client=llm, embedder=embedder)
>>> filing = "供应商 XYZ 提供我们 70% 的零部件。我们还依赖于..."
diff --git a/hyperextract/templates/zh/finance/valuation_logic_map.py b/hyperextract/templates/zh/finance/valuation_logic_map.py
index 82feaf4..3e57859 100644
--- a/hyperextract/templates/zh/finance/valuation_logic_map.py
+++ b/hyperextract/templates/zh/finance/valuation_logic_map.py
@@ -101,7 +101,7 @@ class ValuationLogicMap(AutoGraph[ValuationDriver, ValuationEdge]):
使用示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
+ >>> llm = ChatOpenAI(model="gpt-4o-mini")
>>> embedder = OpenAIEmbeddings()
>>> valuation = ValuationLogicMap(llm_client=llm, embedder=embedder)
>>> report = "云计算采用推动经常性收入,支撑 30 倍前瞻市盈率..."
diff --git a/hyperextract/templates/zh/food/__init__.py b/hyperextract/templates/zh/food/__init__.py
index 5f864b4..e69de29 100644
--- a/hyperextract/templates/zh/food/__init__.py
+++ b/hyperextract/templates/zh/food/__init__.py
@@ -1,15 +0,0 @@
-"""
-食品与农业领域模板,用于从食品工业文档中提取结构化知识。
-
-包含 HACCP 安全、食谱流程、风味配对和烹饪菜谱集等模板。
-"""
-
-from .haccp_safety import FoodSafetyHACCPGraph
-from .recipe_process import RecipeProcessGraph
-from .culinary_dish import CulinaryDishSet
-
-__all__ = [
- "FoodSafetyHACCPGraph",
- "RecipeProcessGraph",
- "CulinaryDishSet",
-]
diff --git a/hyperextract/templates/zh/food/culinary_dish.py b/hyperextract/templates/zh/food/culinary_dish.py
deleted file mode 100644
index f11e5ee..0000000
--- a/hyperextract/templates/zh/food/culinary_dish.py
+++ /dev/null
@@ -1,101 +0,0 @@
-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 import AutoSet
-
-# ==============================================================================
-# 1. Schema 定义
-# ==============================================================================
-
-
-class CulinaryDish(BaseModel):
- """
- 菜肴知识条目。
- """
-
- name: str = Field(description="菜肴的标准名称,例如宫保鸡丁。")
- origin: Optional[str] = Field(
- None, description="菜系、地理原产地及适应季节(如:四川/夏季)。"
- )
- ingredients: Optional[str] = Field(
- None,
- description="主要食材、蛋白质类型及核心酱料。"
- )
- profile: Optional[str] = Field(
- None,
- description="风味特征(酸甜苦辣)、口感及烹饪方法(蒸炒炸)。"
- )
- description: Optional[str] = Field(
- None,
- description="其它描述,包括饮食宜忌、配菜建议及历史背景。"
- )
-
-
-# ==============================================================================
-# 2. 提示词 (Prompts)
-# ==============================================================================
-
-_PROMPT = (
- "你是美食知识库管理员。从文本中提取菜肴信息。\n\n"
- "提取规则:\n"
- "- 识别菜肴标准名称。\n"
- "- **origin**: 整合菜系、城市及季节信息。\n"
- "- **ingredients**: 列出核心食材和配料。\n"
- "- **profile**: 描述味道、质地及烹饪工艺。\n"
- "- **description**: 包含文化背景、饮食特征等补充信息。\n"
-)
-
-# ==============================================================================
-# 3. 模板类
-# ==============================================================================
-
-
-class CulinaryDishSet(AutoSet[CulinaryDish]):
- """
- 适用文档: 菜单、食谱、美食博客。
-
- 模板用于构建标准化的菜肴知识库。
- """
-
- 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,
- ):
- super().__init__(
- item_schema=CulinaryDish,
- 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 = 10,
- top_k_for_chat: int = 10,
- ) -> None:
- def item_label_extractor(item: CulinaryDish) -> str:
- parts = [item.name]
- if item.origin:
- parts.append(f"({item.origin})")
- return " ".join(parts)
-
- 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/food/haccp_safety.py b/hyperextract/templates/zh/food/haccp_safety.py
deleted file mode 100644
index f85f78b..0000000
--- a/hyperextract/templates/zh/food/haccp_safety.py
+++ /dev/null
@@ -1,192 +0,0 @@
-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 import AutoGraph
-
-# ==============================================================================
-# 1. Schema 定义
-# ==============================================================================
-
-
-class BiologicalHazard(BaseModel):
- """
- 在食品生产中必须控制的生物学危害。
- """
-
- name: str = Field(
- description='危害病原体名称,例如"沙门氏菌"、"单核细胞增生李斯特菌"、"O157:H7 大肠杆菌"等。'
- )
- hazard_type: str = Field(
- description='类型:"细菌"、"病毒"、"寄生虫"、"真菌"。'
- )
- health_consequence: Optional[str] = Field(
- None, description='潜在健康影响,例如"严重肠胃炎"、"败血症"等。'
- )
-
-
-class CriticalControlPoint(BaseModel):
- """
- 食品生产中可以控制危害的步骤或工序。
- """
-
- name: str = Field(
- description='CCP 名称,例如"巴氏杀菌"、"金属检测"、"冷藏"等。'
- )
- process_stage: str = Field(
- description='生产阶段:"原料"、"收货"、"加工"、"烹饪"、"冷却"、"包装"、"储存"。'
- )
- description: Optional[str] = Field(
- None, description="CCP 的详细描述。"
- )
-
-
-class ControlMeasure(BaseModel):
- """
- 连接危害和 CCP 的控制措施。
- """
-
- source: str = Field(description="生物学危害名称。")
- target: str = Field(description="CCP 名称。")
- critical_limit: str = Field(
- description='定义安全/不安全分界线的关键限值(如">=72°C 持续 >=15 秒")。'
- )
- monitoring: str = Field(
- description="监测程序与频率(如何监测以及多久监测一次)。"
- )
- details: Optional[str] = Field(
- None, description="纠偏行动及验证有效性的方法。"
- )
-
-
-# ==============================================================================
-# 2. 提示词 (Prompts)
-# ==============================================================================
-
-_PROMPT = (
- "你是食品安全专家。提取危害、关键控制点(CCP)及其控制措施。\n\n"
- "规则:\n"
- "- 识别所有提及的危害与 CCP。\n"
- "- 将危害连接到对应的 CCP。\n"
- "- 提取 **关键限值 (critical_limit)** 与 **监测 (monitoring)** 指标。\n"
- "- 将纠偏行动与验证方法归入 **详情 (details)**。"
-)
-
-_NODE_PROMPT = (
- "你是食品安全专家。从文件中提取危害和 CCP(节点)。\n\n"
- "提取规则:\n"
- "- 识别生物学危害并分类。\n"
- "- 识别 CCP 及其生产阶段。\n"
-)
-
-_EDGE_PROMPT = (
- "你是食品安全专家。提取控制措施(边)。\n\n"
- "提取规则:\n"
- "- 将危害连接到 CCP。\n"
- "- **critical_limit**: 安全分界线。\n"
- "- **monitoring**: 如何及何时监测。\n"
- "- **details**: 纠偏行动及验证方法。\n"
- "- 仅连接存在的节点。"
-)
-
-# ==============================================================================
-# 3. 模板类
-# ==============================================================================
-
-
-class FoodSafetyHACCPGraph(AutoGraph[BiologicalHazard, ControlMeasure]):
- """
- 适用文档: HACCP 计划、食品安全计划(ISO 22000)、SOP 手册、FDA 指导文件、食品公司质量规程、供应商审计报告。
-
- 模板用于系统地从基于 HACCP 的食品安全控制中提取和结构化信息。支持合规验证、供应商审计和整个食品生产运营中的持续安全监测。
-
- 使用示例:
- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
- >>> embedder = OpenAIEmbeddings()
- >>> haccp = FoodSafetyHACCPGraph(llm_client=llm, embedder=embedder)
- >>> plan = "关键控制点:巴氏杀菌。危害:沙门氏菌。关键限值:72°C 持续 15 秒..."
- >>> haccp.feed_text(plan)
- >>> haccp.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,
- ):
- """
- 初始化食品安全 HACCP 图谱模板。
-
- Args:
- llm_client (BaseChatModel): 用于危害和控制提取的 LLM。
- embedder (Embeddings): 用于去重的嵌入模型。
- extraction_mode (str): "one_stage" 或 "two_stage"。
- chunk_size (int): 每个分块的最大字符数。
- chunk_overlap (int): 分块之间的重叠。
- max_workers (int): 并行处理工作线程数。
- verbose (bool): 是否启用进度日志。
- **kwargs: AutoGraph 的其他参数。
- """
- super().__init__(
- node_schema=BiologicalHazard,
- edge_schema=ControlMeasure,
- node_key_extractor=lambda x: x.name.strip().lower(),
- edge_key_extractor=lambda x: (
- f"{x.source.strip()}--({x.target.strip()}): {x.critical_limit.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): 检索的危害/CCP 数。默认 3。
- top_k_edges_for_search (int): 检索的控制措施数。默认 3。
- top_k_nodes_for_chat (int): 对话上下文中的节点数。默认 3。
- top_k_edges_for_chat (int): 对话上下文中的边数。默认 3。
- """
-
- def node_label_extractor(node: BiologicalHazard) -> str:
- if isinstance(node, BiologicalHazard):
- return f"{node.name} ({node.hazard_type})"
- return str(node)
-
- def edge_label_extractor(edge: ControlMeasure) -> str:
- return f"{edge.critical_limit}"
-
- 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/food/recipe_process.py b/hyperextract/templates/zh/food/recipe_process.py
deleted file mode 100644
index 891a1ab..0000000
--- a/hyperextract/templates/zh/food/recipe_process.py
+++ /dev/null
@@ -1,175 +0,0 @@
-from typing import List, 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 import AutoTemporalGraph
-
-# ==============================================================================
-# 1. Schema 定义
-# ==============================================================================
-
-
-class IngredientState(BaseModel):
- """
- 食材/材料在食谱工序特定阶段的状态。
- """
-
- name: str = Field(
- description="状态描述符,例如混合液、加热面团、冷却浆液。"
- )
- composition: str = Field(
- description="这个状态中的物质,例如蛋+糖、面粉+水+盐。"
- )
- physical_state: Optional[str] = Field(
- None, description="物理形态:液体、固体、粉末、面团、乳液、泡沫。"
- )
-
-
-class ProcessingStep(BaseModel):
- """
- 连接两个食材状态的转换步骤。
- """
-
- step_id: str = Field(description="步骤标识符,例如步骤 1、1.1、混合。")
- source_state: str = Field(description="开始时的食材状态。")
- target_state: str = Field(description="加工后的食材状态。")
- action: str = Field(
- description="加工动作,例如混合、加热、冷却、静置、揉搓、发酵。"
- )
- process_conditions: Optional[str] = Field(
- None, description="综述持续时间、温度、设备及工艺参数。"
- )
-
-
-# ==============================================================================
-# 2. 提示词 (Prompts)
-# ==============================================================================
-
-_PROMPT = (
- "你是食品科学家。提取配方工序步骤。\n\n"
- "规则:\n"
- "- 识别加工动作及能量转换。\n"
- "- 提取步骤前后的食材状态。\n"
- "- 捕捉 **工艺条件 (process_conditions)**(时间、温度、设备等)。\n"
- "- 保持严格的先后顺序。"
-)
-
-_NODE_PROMPT = (
- "你是食品科学家。提取食材状态(节点)。\n\n"
- "提取规则:\n"
- "- 识别不同阶段的状态(原始、混合、熟制)。\n"
- "- 列出存在的组成物质。\n"
- "- 记录其物理形态。"
-)
-
-_EDGE_PROMPT = (
- "你是食品科学家。提取加工步骤(边)。\n\n"
- "提取规则:\n"
- "- 通过动作连接源状态与目标状态。\n"
- "- **process_conditions**: 合并记录时间、温度、设备等参数。\n"
- "- 保持精确的步骤顺序。\n"
- "- 仅连接存在的节点。"
-)
-
-# ==============================================================================
-# 3. 模板类
-# ==============================================================================
-
-
-class RecipeProcessGraph(AutoTemporalGraph[IngredientState, ProcessingStep]):
- """
- 适用文档: 工业配方单、食谱 SOP、食品科学研究、生产批记录、厨师食谱、烹饪手册、R&D 实验规程。
-
- 模板用于提取和映射具有精确时间和参数的顺序食品生产工序。支持食谱标准化、工序优化以及烹饪和工业食品环境中的知识转移。
-
- 使用示例:
- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
- >>> embedder = OpenAIEmbeddings()
- >>> recipe = RecipeProcessGraph(llm_client=llm, embedder=embedder)
- >>> process = "步骤 1:将蛋和糖混合 5 分钟。步骤 2:加热至 175°C"
- >>> recipe.feed_text(process)
- >>> recipe.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): 用于状态和步骤提取的 LLM。
- embedder (Embeddings): 用于去重的嵌入模型。
- extraction_mode (str): "one_stage" 或 "two_stage"。
- chunk_size (int): 每个分块的最大字符数。
- chunk_overlap (int): 分块之间的重叠。
- max_workers (int): 并行处理工作线程数。
- verbose (bool): 是否启用进度日志。
- **kwargs: AutoTemporalGraph 的其他参数。
- """
- super().__init__(
- node_schema=IngredientState,
- edge_schema=ProcessingStep,
- node_key_extractor=lambda x: x.name.strip().lower(),
- edge_key_extractor=lambda x: x.step_id.strip(),
- nodes_in_edge_extractor=lambda x: (
- x.source_state.strip(),
- x.target_state.strip(),
- ),
- time_in_edge_extractor=lambda x: x.step_id.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): 检索的状态数。默认 3。
- top_k_edges_for_search (int): 检索的步骤数。默认 3。
- top_k_nodes_for_chat (int): 对话上下文中的状态数。默认 3。
- top_k_edges_for_chat (int): 对话上下文中的步骤数。默认 3。
- """
-
- def node_label_extractor(node: IngredientState) -> str:
- return f"{node.name} ({node.physical_state if node.physical_state else '未知'})"
-
- def edge_label_extractor(edge: ProcessingStep) -> str:
- temp = f" {edge.temperature}" if edge.temperature else ""
- return f"{edge.action} ({edge.duration}){temp}"
-
- 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/history/memory_flashback_list.py b/hyperextract/templates/zh/history/memory_flashback_list.py
index 2b0586a..e434d1a 100644
--- a/hyperextract/templates/zh/history/memory_flashback_list.py
+++ b/hyperextract/templates/zh/history/memory_flashback_list.py
@@ -91,21 +91,21 @@ class MemoryFlashbackList(AutoList[MemoryFragment]):
def show(
self,
*,
- top_k_items_for_search: int = 5,
- top_k_items_for_chat: int = 5,
+ top_k_for_search: int = 5,
+ top_k_for_chat: int = 5,
):
"""
展示回忆片段清单。
Args:
- top_k_items_for_search: 语义检索返回的条目数量,默认为 5
- top_k_items_for_chat: 问答使用的条目数量,默认为 5
+ top_k_for_search: 语义检索返回的条目数量,默认为 5
+ top_k_for_chat: 问答使用的条目数量,默认为 5
"""
def item_label_extractor(item: MemoryFragment) -> str:
return f"[{item.type}] {item.content[:30]}..."
super().show(
item_label_extractor=item_label_extractor,
- top_k_items_for_search=top_k_items_for_search,
- top_k_items_for_chat=top_k_items_for_chat,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
)
diff --git a/hyperextract/templates/zh/legal/__init__.py b/hyperextract/templates/zh/legal/__init__.py
index 6fcca93..e69de29 100644
--- a/hyperextract/templates/zh/legal/__init__.py
+++ b/hyperextract/templates/zh/legal/__init__.py
@@ -1,11 +0,0 @@
-"""Legal domain templates for knowledge extraction."""
-
-from .contract_obligation_checklist import ContractObligationChecklist
-from .corporate_equity_graph import CorporateEquityGraph
-from .case_precedent_library import CasePrecedentLibrary
-
-__all__ = [
- "ContractObligationChecklist",
- "CorporateEquityGraph",
- "CasePrecedentLibrary",
-]
diff --git a/hyperextract/templates/zh/legal/case_precedent_library.py b/hyperextract/templates/zh/legal/case_precedent_library.py
deleted file mode 100644
index 6e2c4e2..0000000
--- a/hyperextract/templates/zh/legal/case_precedent_library.py
+++ /dev/null
@@ -1,70 +0,0 @@
-"""判例法要旨库 - 提取和索引法律判例。
-
-通过自动合并来自多个来源关于同一案件的信息来构建可搜索的法律判例数据库。
-"""
-
-from typing import Any, Optional
-from pydantic import BaseModel, Field
-from langchain_core.language_models import BaseChatModel
-from langchain_core.embeddings import Embeddings
-from hyperextract.types import AutoSet
-
-class PrecedentSchema(BaseModel):
- case_citation: str = Field(..., description="官方案号/引用")
- court_name: Optional[str] = Field(None, description="做出决定的法院")
- judgment_year: Optional[str] = Field(None, description="判决年份")
- legal_issues: Optional[str] = Field(None, description="提出的法律问题")
- holding: Optional[str] = Field(None, description="法院的判决和法律原则")
- cited_statutes: Optional[str] = Field(None, description="判决中引用的法律")
- presiding_judges: Optional[str] = Field(None, description="做出决定的法官")
- impact_assessment: Optional[str] = Field(None, description="对后续法律的影响")
-
-_PROMPT = """你是一位法律研究专家。
-提取判例案件信息:
-1. case_citation:官方案名/案号
-2. court_name:审理的法院
-3. judgment_year:判决年份
-4. legal_issues:法律问题
-5. holding:法院的判决和原则
-6. cited_statutes:适用法律
-7. presiding_judges:做出裁定的法官
-8. impact_assessment:对未来案件的影响
-
-### 源文本:
-"""
-
-class CasePrecedentLibrary(AutoSet[PrecedentSchema]):
- """适用于:法院判决、法律数据库、案例法报告
-
- 通过自动合并来自多个来源的案件信息来提取和索引法律判例,
- 成为统一的可搜索库。
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- chunk_size: int = 2048,
- chunk_overlap: int = 256,
- **kwargs: Any,
- ):
- super().__init__(
- item_schema=PrecedentSchema,
- llm_client=llm_client,
- embedder=embedder,
- key_extractor=lambda x: x.case_citation.strip().lower(),
- prompt=_PROMPT,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- **kwargs,
- )
-
- def show(self, *, top_k_for_search: int = 3, top_k_for_chat: int = 3) -> None:
- def label_extractor(item: PrecedentSchema) -> str:
- year = f" ({item.judgment_year})" if item.judgment_year else ""
- return f"{item.case_citation}{year}"
- super().show(
- item_label_extractor=label_extractor,
- top_k_for_search=top_k_for_search,
- top_k_for_chat=top_k_for_chat,
- )
diff --git a/hyperextract/templates/zh/legal/contract_obligation_checklist.py b/hyperextract/templates/zh/legal/contract_obligation_checklist.py
deleted file mode 100644
index 2268aad..0000000
--- a/hyperextract/templates/zh/legal/contract_obligation_checklist.py
+++ /dev/null
@@ -1,65 +0,0 @@
-"""法定义务审查 - 从合同中提取义务和禁止条款。
-
-通过提取所有义务、责任和限制而无去重来构建全面的合规清单,保留完整的审计记录。
-"""
-
-from typing import Any, Optional
-from pydantic import BaseModel, Field
-from langchain_core.language_models import BaseChatModel
-from langchain_core.embeddings import Embeddings
-from hyperextract.types import AutoList
-
-class ObligationSchema(BaseModel):
- obligated_party: str = Field(..., description="负责履行的当事人")
- obligation_type: str = Field(..., description="'必须'(要求)或'不得'(禁止)")
- action_description: str = Field(..., description="具体行动或要求")
- trigger_condition: Optional[str] = Field(None, description="何时/何种情况下义务适用")
- breach_penalty: Optional[str] = Field(None, description="不履行的后果")
- clause_reference: Optional[str] = Field(None, description="原合同条款号")
-
-_PROMPT = """你是一位合同律师和合规审计员。
-从合同中提取所有义务和限制:
-1. obligated_party:谁必须履行
-2. obligation_type:必须(要求)或不得(禁止)
-3. action_description:具体行动/要求
-4. trigger_condition:义务何时适用
-5. breach_penalty:不合规罚款
-6. clause_reference:合同条款号
-
-独立提取每个义务。无合并。
-
-### 源文本:
-"""
-
-class ContractObligationChecklist(AutoList[ObligationSchema]):
- """适用于:合同、服务条款、协议、合规文件
-
- 提取完整的合规清单,保留每个义务单独存在,用于全面的审计和风险分析。
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- chunk_size: int = 2048,
- chunk_overlap: int = 256,
- **kwargs: Any,
- ):
- super().__init__(
- item_schema=ObligationSchema,
- llm_client=llm_client,
- embedder=embedder,
- prompt=_PROMPT,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- **kwargs,
- )
-
- def show(self, *, top_k_for_search: int = 3, top_k_for_chat: int = 3) -> None:
- def label_extractor(item: ObligationSchema) -> str:
- return f"{item.obligation_type}:{item.action_description[:50]}"
- super().show(
- item_label_extractor=label_extractor,
- top_k_for_search=top_k_for_search,
- top_k_for_chat=top_k_for_chat,
- )
diff --git a/hyperextract/templates/zh/legal/corporate_equity_graph.py b/hyperextract/templates/zh/legal/corporate_equity_graph.py
deleted file mode 100644
index db43ade..0000000
--- a/hyperextract/templates/zh/legal/corporate_equity_graph.py
+++ /dev/null
@@ -1,77 +0,0 @@
-"""股权结构穿透 - 提取所有权和控制关系。
-
-构建股权图显示投资关系、控制结构和通过企业金字塔的最终实益所有权。
-"""
-
-from typing import Any, Optional
-from pydantic import BaseModel, Field
-from langchain_core.language_models import BaseChatModel
-from langchain_core.embeddings import Embeddings
-from hyperextract.types import AutoGraph
-
-class EntitySchema(BaseModel):
- entity_id: str = Field(..., description="唯一标识符")
- entity_type: str = Field(..., description="'公司'、'个人'或'基金'")
- entity_name: str = Field(..., description="法人名称")
- registration_number: Optional[str] = Field(None, description="登记号或身份证号")
-
-class EquityRelationshipSchema(BaseModel):
- source_entity: str = Field(..., description="股东/所有者名称")
- target_entity: str = Field(..., description="公司/实体名称")
- relationship_type: str = Field(..., description="'持股'、'控制'、'任职为'")
- stake_percentage: Optional[str] = Field(None, description="所有权百分比")
- context: Optional[str] = Field(None, description="附加背景信息")
-
-_PROMPT = """提取企业实体及其所有权/控制关系。"""
-
-_NODE_PROMPT = """提取所有实体:公司、个人、基金。"""
-
-_EDGE_PROMPT = """提取实体之间的所有权和控制关系。仅连接已知实体列表中的实体。"""
-
-class CorporateEquityGraph(AutoGraph[EntitySchema, EquityRelationshipSchema]):
- """适用于:尽职调查报告、招股说明书、企业备案
-
- 通过多级股权链提取企业所有权结构和最终实益所有权。
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- extraction_mode: str = "two_stage",
- chunk_size: int = 2048,
- chunk_overlap: int = 256,
- **kwargs: Any,
- ):
- super().__init__(
- node_schema=EntitySchema,
- edge_schema=EquityRelationshipSchema,
- node_key_extractor=lambda x: x.entity_name.strip().lower(),
- edge_key_extractor=lambda x: (
- f"{x.source_entity.lower()}|{x.relationship_type.lower()}|{x.target_entity.lower()}"
- ),
- nodes_in_edge_extractor=lambda x: (x.source_entity.lower(), x.target_entity.lower()),
- llm_client=llm_client,
- embedder=embedder,
- extraction_mode=extraction_mode,
- prompt=_PROMPT,
- prompt_for_node_extraction=_NODE_PROMPT,
- prompt_for_edge_extraction=_EDGE_PROMPT,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- **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:
- def node_label(node: EntitySchema) -> str:
- type_icon = {"公司": "🏢", "个人": "👤", "基金": "💼"}
- icon = type_icon.get(node.entity_type, "●")
- return f"{icon} {node.entity_name}"
- def edge_label(edge: EquityRelationshipSchema) -> str:
- pct = f" ({edge.stake_percentage})" if edge.stake_percentage else ""
- return f"{edge.relationship_type}{pct}"
- super().show(
- node_label_extractor=node_label,
- edge_label_extractor=edge_label,
- 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/__init__.py b/hyperextract/templates/zh/literature/__init__.py
index 15ac04d..e69de29 100644
--- a/hyperextract/templates/zh/literature/__init__.py
+++ b/hyperextract/templates/zh/literature/__init__.py
@@ -1,9 +0,0 @@
-from .character_relationship_graph import CharacterRelationshipGraph
-from .narrative_timeline import NarrativeTimeline
-from .symbolism_set import SymbolismSet
-
-__all__ = [
- "CharacterRelationshipGraph",
- "NarrativeTimeline",
- "SymbolismSet",
-]
diff --git a/hyperextract/templates/zh/literature/character_relationship_graph.py b/hyperextract/templates/zh/literature/character_relationship_graph.py
deleted file mode 100644
index 7207a0f..0000000
--- a/hyperextract/templates/zh/literature/character_relationship_graph.py
+++ /dev/null
@@ -1,156 +0,0 @@
-from typing import List, Optional, Any, Tuple
-from pydantic import BaseModel, Field
-from langchain_core.language_models.chat_models import BaseChatModel
-from langchain_core.embeddings import Embeddings
-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="关于人物在作品中地位及核心情节的简要描述。"
- )
-
-
-class Relationship(BaseModel):
- """人物之间的互动与联系。"""
-
- source: str = Field(description="发起关系的或关系的第一个人物名称。")
- target: str = Field(description="关系指向的或关系的第二个人物名称。")
- relation_type: str = Field(
- description="关系的性质(如:亲属、爱慕、仇恨、师徒、盟友)。"
- )
- sentiment: str = Field(description="关系的情感倾向(如:正面、负面、中立、复杂)。")
- evidence: str = Field(description="支持该关系的文本证据或关键情节简述。")
-
-
-# ==============================================================================
-# 2. 提示词 (Prompts)
-# ==============================================================================
-
-_PROMPT = (
- "你是一位资深的文学评论家和角色分析专家。你的任务是从文学文本中提取人物及其关系网络。\n\n"
- "提取指南:\n"
- "1. **人物识别**:准确识别文本中出现的所有重要人物。记录他们的姓名、绰号及核心特征。\n"
- "2. **关系识别**:分析人物间的对话、行为互动及旁白,提取他们之间的深层联系。不仅仅限于亲属关系,也要捕捉情感纽带和利益冲突。\n"
- "3. **证据至上**:为每个关系提供简短的文本依据。\n"
- "- 确保边连接的两个人物都已在节点列表中列出。"
-)
-
-_NODE_PROMPT = "作为文学分析专家,请从文本中提取所有关键人物。记录其姓名、所有已知的别称、核心性格标签以及简要的生平或地位描述。"
-
-_EDGE_PROMPT = "基于已提取的人物列表,识别他们之间的社交与情感关系。请说明关系的类型(如‘宿敌’)、情感色彩(如‘强烈恨意’)并提供证据。"
-
-# ==============================================================================
-# 3. 模板类 (Template Class)
-# ==============================================================================
-
-
-class CharacterRelationshipGraph(AutoGraph[Character, Relationship]):
- """
- 适用于:[小说, 剧本, 传记, 戏剧]
-
- 用于提取文学作品中复杂人物关系的图谱模板。
-
- 该模板旨在捕捉人物间的动态互动、情感倾向和结构化联系,支持多阶段提取以确保深度关系的准确性。
-
- 示例:
- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
- >>> embedder = OpenAIEmbeddings()
- >>> # 初始化模板
- >>> characters = CharacterRelationshipGraph(llm_client=llm, embedder=embedder)
- >>> # 输入文本块
- >>> text = "贾宝玉是贾政之子,与林黛玉青梅竹马,彼此情深意切。"
- >>> characters.feed_text(text)
- >>> characters.show()
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- *,
- extraction_mode: str = "two_stage",
- chunk_size: int = 2048,
- chunk_overlap: int = 256,
- max_workers: int = 10,
- verbose: bool = False,
- **kwargs: Any,
- ):
- """
- 初始化 CharacterRelationshipGraph 模板。
-
- Args:
- llm_client: 用于提取的语言模型客户端。
- embedder: 用于实体去重和索引的嵌入模型。
- extraction_mode: 提取模式,支持 "one_stage" 和 "two_stage"。
- chunk_size: 文本块大小。
- chunk_overlap: 文本块重叠大小。
- max_workers: 最大并行工作线程数。
- verbose: 是否开启详细日志。
- **kwargs: 其他传给 AutoGraph 的参数。
- """
- super().__init__(
- node_schema=Character,
- edge_schema=Relationship,
- node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source}-{x.relation_type}-{x.target}",
- nodes_in_edge_extractor=lambda x: (x.source, x.target),
- llm_client=llm_client,
- embedder=embedder,
- prompt=_PROMPT,
- prompt_for_node_extraction=_NODE_PROMPT,
- prompt_for_edge_extraction=_EDGE_PROMPT,
- extraction_mode=extraction_mode,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- max_workers=max_workers,
- verbose=verbose,
- **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:
- """
- 可视化人物关系图谱。
-
- Args:
- 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
-
- def edge_label_extractor(edge: Relationship) -> str:
- return f"{edge.relation_type} ({edge.sentiment})"
-
- 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/literature/narrative_timeline.py b/hyperextract/templates/zh/literature/narrative_timeline.py
deleted file mode 100644
index b7dd436..0000000
--- a/hyperextract/templates/zh/literature/narrative_timeline.py
+++ /dev/null
@@ -1,155 +0,0 @@
-from typing import List, Optional, Any, Tuple
-from pydantic import BaseModel, Field
-from langchain_core.language_models.chat_models import BaseChatModel
-from langchain_core.embeddings import Embeddings
-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="参与该事件的人物名单。"
- )
- description: str = Field(description="对情节内容的具体描述,包括核心动作和转折。")
-
-
-class TimeTransition(BaseModel):
- """情节节点之间的时间演变与逻辑关联。"""
-
- source: str = Field(description="起始情节名称。")
- target: str = Field(description="后续情节名称。")
- time: str = Field(
- description="事实发生的时间。你必须结合上下文和观察日期,将相对时间(如‘三天后’、‘次日’)解析并转换为绝对日期(如‘2024-01-15’)或具体年份。"
- )
- logic: str = Field(description="事件间的逻辑关系(如:因果、递进、意外转折)。")
-
-
-# ==============================================================================
-# 2. 提示词 (Prompts)
-# ==============================================================================
-
-_PROMPT = (
- "你是一位资深的叙事学家。你的任务是从文本中还原情节发展的时空蓝图。\n\n"
- "提取要求:\n"
- "1. **情节识别**:提取具有独立叙事意义的节点,记录其发生的地点及参与者。\n"
- "2. **时间轴构建**:在情节间建立带时间属性的连线。特别注意文本中的时间指示词(如‘过了半晌’、‘数月无话’)。\n"
- "3. **逻辑链条**:除了时间先后,还要识别事件间的因果驱动力。\n"
- "注意:时间必须提取在边(Transition)上,不要作为独立的节点。"
-)
-
-_NODE_PROMPT = "请识别并提取文本中所有的关键情节节点(Plot Points)。为每个节点命名,并提供地点描述及涉及的人物。"
-
-_EDGE_PROMPT = "在给定的情节节点之间建立联系。请精确提取文本中提及的时间线索,并描述这些事件是如何在叙事逻辑上相互连接的。"
-
-# ==============================================================================
-# 3. 模板类 (Template Class)
-# ==============================================================================
-
-
-class NarrativeTimeline(AutoTemporalGraph[NarrativePoint, TimeTransition]):
- """
- 适用于:[编年史, 史诗文学, 侦探小说, 史书]
-
- 用于还原文学或历史叙述中情节演变的时间线图谱模板。
-
- 该模板利用 AutoTemporalGraph 的时序特性,将时间信息嵌入关系中,专注于呈现“起因-经过-结果”的动态过程。
-
- 示例:
- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
- >>> embedder = OpenAIEmbeddings()
- >>> # 初始化模板
- >>> timeline = NarrativeTimeline(llm_client=llm, embedder=embedder)
- >>> # 输入包含时间跨度的文本
- >>> text = "隆中对之后,刘备三顾茅庐请出诸葛亮。数年后,曹操南下,引发了赤壁之战。"
- >>> timeline.feed_text(text)
- >>> timeline.show()
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- *,
- observation_time: Optional[str] = None,
- extraction_mode: str = "two_stage",
- chunk_size: int = 2048,
- chunk_overlap: int = 256,
- max_workers: int = 10,
- verbose: bool = False,
- **kwargs: Any,
- ):
- """
- 初始化 NarrativeTimeline 模板。
-
- Args:
- llm_client: 用于提取的语言模型客户端。
- embedder: 用于实体去重和索引的嵌入模型。
- observation_time: 设定的基准参考日期,用于解析相对时间(如‘今天’)。
- extraction_mode: 默认使用 two_stage 以保证时间解析的精准度。
- chunk_size: 文本块大小。
- chunk_overlap: 文本块重叠大小。
- max_workers: 最大并行工作线程数。
- verbose: 是否开启详细日志。
- **kwargs: 其他传给 AutoTemporalGraph 的参数。
- """
- super().__init__(
- node_schema=NarrativePoint,
- edge_schema=TimeTransition,
- node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source}->{x.target}",
- time_in_edge_extractor=lambda x: x.time,
- nodes_in_edge_extractor=lambda x: (x.source, x.target),
- llm_client=llm_client,
- embedder=embedder,
- observation_time=observation_time,
- prompt=_PROMPT,
- prompt_for_node_extraction=_NODE_PROMPT,
- prompt_for_edge_extraction=_EDGE_PROMPT,
- extraction_mode=extraction_mode,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- max_workers=max_workers,
- verbose=verbose,
- **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:
- """
- 可视化叙事时间线。
-
- Args:
- 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
-
- def edge_label_extractor(edge: TimeTransition) -> str:
- return f"[{edge.time}] {edge.logic}"
-
- 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/literature/symbolism_set.py b/hyperextract/templates/zh/literature/symbolism_set.py
deleted file mode 100644
index 2cc65d4..0000000
--- a/hyperextract/templates/zh/literature/symbolism_set.py
+++ /dev/null
@@ -1,110 +0,0 @@
-from typing import List, Optional, Any, Callable
-from pydantic import BaseModel, Field
-from langchain_core.language_models.chat_models import BaseChatModel
-from langchain_core.embeddings import Embeddings
-from hyperextract.types import AutoSet
-
-# ==============================================================================
-# 1. Schema 定义 (Schema Definitions)
-# ==============================================================================
-
-class ImagerySymbol(BaseModel):
- """文学作品中的意象或符号。"""
- symbol_name: str = Field(description="意象的名称(如‘月亮’、‘荒原’、‘白鲸’)。")
- literal_meanings: List[str] = Field(description="该意象在文中的字面指代或描述。")
- metaphorical_meanings: List[str] = Field(description="该意象隐含的象征意义或深层隐喻。")
- contexts: List[str] = Field(description="提取该意象的关键原文片段或章节摘要。")
- thematic_connection: Optional[str] = Field(description="该意象与作品主题(如‘孤独’、‘命运’)的关联。")
-
-# ==============================================================================
-# 2. 提示词 (Prompts)
-# ==============================================================================
-
-_PROMPT = (
- "你是一位资深的文学批评家。你的任务是从文本中识别并分析反复出现的关键意象与符号。\n\n"
- "分析指南:\n"
- "1. **意象标准化**:请确保同一个意象(如‘月色’与‘月亮’)被归类到同一个标准的意象名称下,以便信息累加。\n"
- "2. **分层解读**:区分意象的字面描写(它是什么)与其象征意义(它代表了什么)。\n"
- "3. **信息聚合**:如果你在多处文本中发现了同一个意象,请持续丰富该意象的内涵、上下文和它对主题的贡献。\n"
-)
-
-# ==============================================================================
-# 3. 模板类 (Template Class)
-# ==============================================================================
-
-class SymbolismSet(AutoSet[ImagerySymbol]):
- """
- 适用于:[诗歌, 现代主义小说, 文学评论, 散文]
-
- 用于从文学作品中聚合与深度分析意象隐喻的集合模板。
-
- 该模板利用 AutoSet 的键值累加特性,能够将散落在全书各处的关于同一个符号的信息(字面描写、深层隐喻、主题关联)自动合并为一个富集的词条。
-
- 示例:
- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
- >>> llm = ChatOpenAI(model="gpt-5-mini")
- >>> embedder = OpenAIEmbeddings()
- >>> # 初始化模板
- >>> symbolism = SymbolismSet(llm_client=llm, embedder=embedder)
- >>> # 多次喂入不同章节的文本
- >>> symbolism.feed_text("海明威笔下的大海是永恒的荒原,象征着不可战胜的自然。").feed_text("在大海深处,老人与马林鱼的搏斗体现了尊严。")
- >>> symbolism.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
- ):
- """
- 初始化 SymbolismSet 模板。
-
- Args:
- llm_client: 用于提取的语言模型客户端。
- embedder: 用于语义检索和可视化的嵌入模型。
- chunk_size: 文本块大小。
- chunk_overlap: 文本块重叠大小。
- max_workers: 最大并行工作线程数。
- verbose: 是否开启详细日志。
- **kwargs: 其他传给 AutoSet 的参数。
- """
- super().__init__(
- item_schema=ImagerySymbol,
- key_extractor=lambda x: x.symbol_name.strip().lower(), # 精确键值匹配
- llm_client=llm_client,
- embedder=embedder,
- prompt=_PROMPT,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- max_workers=max_workers,
- verbose=verbose,
- **kwargs
- )
-
- def show(
- self,
- *,
- top_k_for_search: int = 3,
- top_k_for_chat: int = 3,
- ) -> None:
- """
- 可视化意象与隐喻库。
-
- Args:
- top_k_for_search: 搜索时找回的相关条目数量。
- top_k_for_chat: 聊天时找回的相关条目数量。
- """
- def item_label_extractor(item: ImagerySymbol) -> str:
- return item.symbol_name
-
- 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/news/__init__.py b/hyperextract/templates/zh/news/__init__.py
index b33b750..e69de29 100644
--- a/hyperextract/templates/zh/news/__init__.py
+++ b/hyperextract/templates/zh/news/__init__.py
@@ -1,5 +0,0 @@
-from .breaking_event_graph import BreakingEventGraph
-from .topic_timeline import TopicTimeline
-from .opinion_set import OpinionSet
-
-__all__ = ["BreakingEventGraph", "TopicTimeline", "OpinionSet"]
diff --git a/hyperextract/templates/zh/news/breaking_event_graph.py b/hyperextract/templates/zh/news/breaking_event_graph.py
deleted file mode 100644
index ed99e4e..0000000
--- a/hyperextract/templates/zh/news/breaking_event_graph.py
+++ /dev/null
@@ -1,106 +0,0 @@
-from typing import List, Optional, Any, Tuple
-from pydantic import BaseModel, Field
-from langchain_core.language_models.chat_models import BaseChatModel
-from langchain_core.embeddings import Embeddings
-from hyperextract.types import AutoGraph
-
-# ==============================================================================
-# 1. Schema 定义
-# ==============================================================================
-
-
-class NewsEntity(BaseModel):
- """新闻事件中的关键实体(人物、组织、国家、核心物件)。"""
-
- name: str = Field(description="实体的全称或最常用名。")
- category: str = Field(
- description="实体类别(如:政治人物、国际组织、政府机构、抗议团体)。"
- )
- role: str = Field(
- description="该实体在当前新闻事件中扮演的角色或立场(如:发起者、受害者、调停方)。"
- )
-
-
-class NewsAction(BaseModel):
- """实体间的具体动作、行为或声明。"""
-
- source: str = Field(description="动作的发起方。")
- target: str = Field(description="动作的对象或接收方。")
- action_type: str = Field(
- description="动作类型(如:谴责、签署协议、发起进攻、发布声明)。"
- )
- impact: str = Field(description="该动作产生的直接影响、结果或背景动机。")
- evidence: str = Field(description="对应的原文核心表述片段。")
-
-
-# ==============================================================================
-# 2. 提示词 (Prompts)
-# ==============================================================================
-
-_PROMPT = (
- "你是一位资深的新闻编辑和地缘政治分析师。你的任务是从新闻报道中快速提取突发事件的全景图。\n\n"
- "提取要求:\n"
- "1. **实体定位**:提取所有关键参与方,并明确其在事件中的角色。\n"
- "2. **互动追踪**:分析各方之间的实体动作(Action),区分言语声明与实际行为。\n"
- "3. **影响评估**:捕捉动作背后的影响和核心动机。\n"
-)
-
-_NODE_PROMPT = (
- "提取新闻中提及的所有关键人物、组织和国家。请注明其所属类别及在事件中的主要角色。"
-)
-_EDGE_PROMPT = (
- "识别各方之间的具体行为与互动逻辑。请描述动作的性质、影响,并附带原文证据。"
-)
-
-# ==============================================================================
-# 3. 模板类
-# ==============================================================================
-
-
-class BreakingEventGraph(AutoGraph[NewsEntity, NewsAction]):
- """
- 适用于:[突发新闻报道, 地缘政治简报, 新闻稿, 情报摘要]
-
- 用于快速解析突发新闻中“谁对谁做了什么”的全景图谱模板。
-
- 该模板适合快速梳理复杂国际事件、经济纠纷或突发社会事件中各方的互动网。
-
- 示例:
- >>> news = BreakingEventGraph(llm_client=llm, embedder=embedder)
- >>> text = "联合国秘书长今日公开谴责某国的军事行动,并呼吁立即停火。"
- >>> news.feed_text(text).show()
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- *,
- extraction_mode: str = "one_stage",
- **kwargs: Any,
- ):
- super().__init__(
- node_schema=NewsEntity,
- edge_schema=NewsAction,
- node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source}-{x.action_type}-{x.target}",
- nodes_in_edge_extractor=lambda x: (x.source, x.target),
- llm_client=llm_client,
- embedder=embedder,
- prompt=_PROMPT,
- prompt_for_node_extraction=_NODE_PROMPT,
- prompt_for_edge_extraction=_EDGE_PROMPT,
- extraction_mode=extraction_mode,
- **kwargs,
- )
-
- def show(self, **kwargs):
- def n_label(node: NewsEntity) -> str:
- return f"{node.name} ({node.role})"
-
- def e_label(edge: NewsAction) -> str:
- return edge.action_type
-
- super().show(
- node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs
- )
diff --git a/hyperextract/templates/zh/news/opinion_set.py b/hyperextract/templates/zh/news/opinion_set.py
deleted file mode 100644
index 32d1b88..0000000
--- a/hyperextract/templates/zh/news/opinion_set.py
+++ /dev/null
@@ -1,69 +0,0 @@
-from typing import List, 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 import AutoSet
-
-# ==============================================================================
-# 1. Schema 定义
-# ==============================================================================
-
-class OpinionStance(BaseModel):
- """在该话题下,某个主体持有的观点与立场。"""
- entity: str = Field(description="表达观点的个人、组织、媒体或团体。")
- stance: str = Field(description="核心立场标签(如:支持、强烈反对、中立、质疑)。")
- key_argument: str = Field(description="支撑该立场的核心论点或诉求。")
- evidence_provided: List[str] = Field(description="主体提供的论据、数据或事实支撑。")
- potential_interest: Optional[str] = Field(description="该立场背后可能隐含的利益诉求或动机。")
-
-# ==============================================================================
-# 2. 提示词 (Prompts)
-# ==============================================================================
-
-_PROMPT = (
- "你是一位多维舆情分析师。你的任务是从新闻报道、杂谈或评论中识别并归纳不同利益相关方的观点立场。\n\n"
- "提取要求:\n"
- "1. **主体识别**:清晰界定发声的主体。\n"
- "2. **立场解构**:不仅要记录‘说了什么’,还要通过细微的语调判断其核心态度(立场)。\n"
- "3. **论证梳理**:提取其陈述中具有说服力的事实依据。\n"
- "4. **横向沉淀**:如果多个文本提到了同一个主体的相同立场,请将新的论据补充到该主体条目中。\n"
-)
-
-# ==============================================================================
-# 3. 模板类
-# ==============================================================================
-
-class OpinionSet(AutoSet[OpinionStance]):
- """
- 适用于:[舆情分析, 媒体评论, 辩论实录, 社论专栏]
-
- 用于从新闻和评论中归纳不同主体观点分布及论据的知识挖掘模板。
-
- 该模板使用 AutoSet 结构,根据“主体+立场”作为主键进行知识沉淀,适合梳理复杂议题下的舆论博弈格局。
-
- 示例:
- >>> opinion_set = OpinionSet(llm_client=llm, embedder=embedder)
- >>> text = "环保组织A发表声明反对该项目,称其会破坏湿地。当地政府则表示项目能带动就业。"
- >>> opinion_set.feed_text(text).show()
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- **kwargs: Any
- ):
- super().__init__(
- schema=OpinionStance,
- # 以 实体 和 立场 的组合作为主键,沉淀同类观点
- key_extractor=lambda x: f"{x.entity.strip()}:{x.stance.strip()}",
- llm_client=llm_client,
- embedder=embedder,
- prompt=_PROMPT,
- **kwargs
- )
-
- def show(self, **kwargs):
- def label_func(item: OpinionStance) -> str:
- return f"【{item.stance}】{item.entity}: {item.key_argument}"
- super().show(item_label_extractor=label_func, **kwargs)
diff --git a/hyperextract/templates/zh/news/topic_timeline.py b/hyperextract/templates/zh/news/topic_timeline.py
deleted file mode 100644
index 261f488..0000000
--- a/hyperextract/templates/zh/news/topic_timeline.py
+++ /dev/null
@@ -1,103 +0,0 @@
-from typing import List, Optional, Any, Tuple
-from pydantic import BaseModel, Field
-from langchain_core.language_models.chat_models import BaseChatModel
-from langchain_core.embeddings import Embeddings
-from hyperextract.types import AutoTemporalGraph
-
-# ==============================================================================
-# 1. Schema 定义
-# ==============================================================================
-
-
-class NewsEventNode(BaseModel):
- """专题新闻中的核心事件节点。"""
-
- event_summary: str = Field(description="事件的简短标题或摘要。")
- location: Optional[str] = Field(description="事件发生的具体地理位置。")
- key_participants: List[str] = Field(description="涉及的核心人物或组织列表。")
-
-
-class NewsTimelineProgression(BaseModel):
- """事件随时间的演进逻辑。"""
-
- source: str = Field(description="前导事件摘要。")
- target: str = Field(description="后续事件摘要。")
- time: str = Field(
- description="事件发生的具体时间节点。你必须解析文本中的模糊表达(如‘两周后’)为绝对日期。"
- )
- evolution_type: str = Field(
- description="事态演变性质(如:升级、转折、平息、连锁反应)。"
- )
- description: str = Field(description="这一阶段演进的具体内容描述。")
-
-
-# ==============================================================================
-# 2. 提示词 (Prompts)
-# ==============================================================================
-
-_PROMPT = (
- "你是一位资深的时政调查记者。你的任务是从深度报道或系列新闻中梳理事件发展的脉络。\n\n"
- "提取要求:\n"
- "1. **节点提取**:识别具有里程碑意义的单一事件节点。\n"
- "2. **时间对齐**:根据基准日期解析出的所有时间信息,并将其体现在边(Progression)上。\n"
- "3. **动态关联**:侧重描述事件之间是如何由时间驱动并产生因果联系的。\n"
-)
-
-_NODE_PROMPT = (
- "识别新闻报道中的关键里程碑事件。为每个事件提供简明标题、地点及核心参与者。"
-)
-_EDGE_PROMPT = "在里程碑事件间建立时序链。请基于提供的观察日期解析相对时间词,并说明事态是如何演变或连锁触发的。"
-
-# ==============================================================================
-# 3. 模板类
-# ==============================================================================
-
-
-class TopicTimeline(AutoTemporalGraph[NewsEventNode, NewsTimelineProgression]):
- """
- 适用于:[系列报道, 长篇调查新闻, 专题档案, 历史回顾]
-
- 用于将零散新闻报道串联成连贯主题演化时间轴的模板。
-
- 该模板专注于呈现事态的纵向发展轨迹,适合追踪长期社会热点或政策演变。
-
- 示例:
- >>> timeline = TopicTimeline(llm_client=llm, embedder=embedder)
- >>> text = "2023年法案提出。半年后,经过激烈辩论获得通过。次月正式生效。"
- >>> timeline.feed_text(text).show()
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- *,
- extraction_mode: str = "two_stage",
- **kwargs: Any,
- ):
- super().__init__(
- node_schema=NewsEventNode,
- edge_schema=NewsTimelineProgression,
- node_key_extractor=lambda x: x.event_summary.strip(),
- edge_key_extractor=lambda x: f"{x.source}>>{x.target}",
- time_in_edge_extractor=lambda x: x.time,
- nodes_in_edge_extractor=lambda x: (x.source, x.target),
- llm_client=llm_client,
- embedder=embedder,
- prompt=_PROMPT,
- prompt_for_node_extraction=_NODE_PROMPT,
- prompt_for_edge_extraction=_EDGE_PROMPT,
- extraction_mode=extraction_mode,
- **kwargs,
- )
-
- def show(self, **kwargs):
- def n_label(node: NewsEventNode) -> str:
- return node.event_summary
-
- def e_label(edge: NewsTimelineProgression) -> str:
- return f"[{edge.time}] {edge.evolution_type}"
-
- super().show(
- node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs
- )
diff --git a/tests/conftest.py b/tests/conftest.py
index 210aece..6eb0a63 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -48,7 +48,7 @@ def llm_client(is_real_env):
try:
from langchain_openai import ChatOpenAI
- return ChatOpenAI(model="gpt-5-mini", temperature=0)
+ return ChatOpenAI(model="gpt-4o-mini", temperature=0)
except ImportError:
pytest.fail(
"OPENAI_API_KEY detected but 'langchain-openai' package not installed. "