Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.
feat: 添加教育领域的先修图谱、跨学科超图和学术词汇模板,支持多语言
yifanfeng97d7ecf74b816d
diff --git a/hyperextract/templates/en/education/__init__.py b/hyperextract/templates/en/education/__init__.pyindex e69de29..7aee758 100644--- a/hyperextract/templates/en/education/__init__.py+++ b/hyperextract/templates/en/education/__init__.py@@ -0,0 +1,9 @@+from .prerequisite_map import PrerequisiteMapGraph+from .academic_lexicon import AcademicLexiconSet+from .interdisciplinary_nexus import InterdisciplinaryNexusHypergraph++__all__ = [+ "PrerequisiteMapGraph",+ "AcademicLexiconSet",+ "InterdisciplinaryNexusHypergraph",+]diff --git a/hyperextract/templates/en/education/academic_lexicon.py b/hyperextract/templates/en/education/academic_lexicon.pynew file mode 100644index 0000000..c016360--- /dev/null+++ b/hyperextract/templates/en/education/academic_lexicon.py@@ -0,0 +1,99 @@+from typing import Optional, List, 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 AcademicTerm(BaseModel):+ """+ A standardized academic term, concept, or definition aggregated from multiple sources.+ """+ term: str = Field(+ description="The primary name of the academic term/concept. Acts as the unique identifier."+ )+ domain: str = Field(+ description="Field of study or academic domain (e.g., 'Thermodynamics', 'Linguistics')."+ )+ definition: str = Field(+ description="A comprehensive, synthesized definition of the term."+ )+ synonyms: List[str] = Field(+ default_factory=list,+ description="Alternative names or closely related terms."+ )+ key_expression: Optional[str] = Field(+ None, description="A formula, notation, or iconic expression associated with this term."+ )++# ==============================================================================+# 2. Prompts+# ==============================================================================++ACADEMIC_LEXICON_PROMPT = (+ "You are a Lexicographer and Academic Encyclopedia Editor. Your goal is to extract standardize academic definitions.\n\n"+ "Extraction Rules:\n"+ "- Identify unique academic terms and their highly precise definitions.\n"+ "- Search for alternative names or synonyms within the text.\n"+ "- If multiple descriptions of the same term exist, prioritize the one that is most mathematically or logically rigorous."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class AcademicLexiconSet(AutoSet[AcademicTerm]):+ """+ Educational template for building a deduplicated, synthesized dictionary of academic terms.+ Leverages AutoSet to merge conflicting or complementary definitions from multiple text sources.++ Example Usage:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> from hyperextract.templates.en.education.academic_lexicon import AcademicLexiconSet+ >>> lexicon = AcademicLexiconSet(llm_client, embedder)+ >>> lexicon.feed_text("Source 1: Photosynthesis is a process used by plants...")+ >>> lexicon.feed_text("Source 2: Photosynthesis converts light energy into chemical energy...")+ >>> lexicon.extract() # Will merge definitions of "Photosynthesis"+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "one_stage", # For AutoSet, this is standard+ chunk_size: int = 2048,+ chunk_overlap: int = 256,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ Initialize the Academic Lexicon Template.++ Args:+ llm_client (BaseChatModel): The LLM used for extraction.+ embedder (Embeddings): The embedding model for entity deduplication and merging.+ extraction_mode (str): Mode of extraction.+ chunk_size (int): Size of text chunks for processing large documents.+ chunk_overlap (int): Overlap between chunks.+ max_workers (int): Parallel processing workers.+ verbose (bool): Enable verbose logging.+ **kwargs: Additional parameters for AutoSet.+ """+ super().__init__(+ item_schema=AcademicTerm,+ key_extractor=lambda x: x.term.strip().lower(),+ 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=ACADEMIC_LEXICON_PROMPT,+ **kwargs,+ )diff --git a/hyperextract/templates/en/education/interdisciplinary_nexus.py b/hyperextract/templates/en/education/interdisciplinary_nexus.pynew file mode 100644index 0000000..714d87e--- /dev/null+++ b/hyperextract/templates/en/education/interdisciplinary_nexus.py@@ -0,0 +1,118 @@+from typing import List, 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 AutoHypergraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class ConceptNode(BaseModel):+ """+ A fundamental academic concept that might belong to multiple disciplines.+ """+ name: str = Field(description="Standard name of the concept.")+ primary_field: str = Field(description="The primary discipline this concept originates from.")++class InterdisciplinaryEdge(BaseModel):+ """+ A hyperedge representing a connection between multiple concepts across different fields.+ """+ participants: List[str] = Field(+ description="List of nodes (concept names) participating in this interdisciplinary nexus."+ )+ unifying_theme: str = Field(+ description="The overarching theme or problem that connects these concepts (e.g., 'Complexity Theory', 'Universal Design')."+ )+ connectivity_insight: str = Field(+ description="The scientific or pedagogical value of connecting these specific dots."+ )++# ==============================================================================+# 2. Prompts+# ==============================================================================++NEXUS_CONSOLIDATED_PROMPT = (+ "You are a Polymath and Interdisciplinary Researcher. Identify deep connections between concepts across different academic fields.\n\n"+ "Extraction Rules:\n"+ "- Identify core concepts as Nodes.\n"+ "- Create Hyperedges that group multiple concepts under a unifying interdisciplinary theme.\n"+ "- Focus on finding surprising but scientifically valid bridges (e.g., connecting Biology and Economics through Game Theory)."+)++NEXUS_NODE_PROMPT = (+ "Identify fundamental academic concepts that carry cross-disciplinary potential.\n\n"+ "Rules:\n"+ "- Extract nouns/concepts that are central to their respective fields.\n"+ "- Identify the field of origin."+)++NEXUS_EDGE_PROMPT = (+ "Identify the 'Nexuses' or Hyperedges that unify a group of concepts.\n\n"+ "Rules:\n"+ "- A hyperedge must involve more than two nodes whenever possible.\n"+ "- Describe the unifying theme and the insight gained by this connection."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class InterdisciplinaryNexusHypergraph(AutoHypergraph[ConceptNode, InterdisciplinaryEdge]):+ """+ Educational template for mapping non-binary, multi-point academic connections.+ Ideal for research synthesis, curriculum cross-linking, and holistic knowledge management.++ Example Usage:+ >>> nexus = InterdisciplinaryNexusHypergraph(llm, embedder)+ >>> nexus.feed_text("The concept of Entropy applies to Heat (Physics) and Information (Information Theory).")+ >>> nexus.extract()+ >>> # Result will contain a Hyperedge connecting 'Heat' and 'Information' via 'Entropy'.+ """++ 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 Interdisciplinary Nexus Template.++ Args:+ llm_client (BaseChatModel): The LLM used for extraction.+ embedder (Embeddings): The embedding model for deduplication.+ extraction_mode (str): 'one_stage' or 'two_stage'.+ chunk_size (int): Size of chunks.+ chunk_overlap (int): Overlap.+ max_workers (int): Workers.+ verbose (bool): Logs.+ **kwargs: Args for AutoHypergraph.+ """+ super().__init__(+ node_schema=ConceptNode,+ edge_schema=InterdisciplinaryEdge,+ node_key_extractor=lambda x: x.name.strip().lower(),+ edge_key_extractor=lambda x: (+ f"{x.unifying_theme.strip().lower()}_linking_{sorted(x.participants)}"+ ),+ nodes_in_edge_extractor=lambda x: [p.strip().lower() for p in x.participants],+ 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=NEXUS_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=NEXUS_NODE_PROMPT,+ prompt_for_edge_extraction=NEXUS_EDGE_PROMPT,+ **kwargs,+ )diff --git a/hyperextract/templates/en/education/prerequisite_map.py b/hyperextract/templates/en/education/prerequisite_map.pynew file mode 100644index 0000000..2e1da13--- /dev/null+++ b/hyperextract/templates/en/education/prerequisite_map.py@@ -0,0 +1,134 @@+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 KnowledgePointNode(BaseModel):+ """+ A discrete unit of knowledge, concept, or skill within a specific curriculum.+ """+ name: str = Field(+ description="Standardized name of the knowledge point or concept."+ )+ level: str = Field(+ description="Difficulty level: 'Primary', 'Intermediate', 'Advanced', 'Expert'."+ )+ concept_type: str = Field(+ description="Pedagogical type: 'Definition', 'Theorem', 'Formula', 'Method', 'Application'."+ )+ description: Optional[str] = Field(+ None, description="A brief pedagogical summary of what this concept entails."+ )++class PrerequisiteRelation(BaseModel):+ """+ Directional dependency indicating that one concept must be learned before another.+ """+ source: str = Field(description="The prerequisite knowledge point (must be learned first).")+ target: str = Field(description="The successor knowledge point (learned after).")+ dependency_type: str = Field(+ "Prerequisite",+ description="Nature of link: 'Prerequisite' (strict), 'Corequisite' (together), 'Recommended' (helpful)."+ )+ weight: float = Field(+ 1.0, description="Strength of dependency from 0.0 to 1.0."+ )++# ==============================================================================+# 2. Prompts+# ==============================================================================++EDUCATION_CONSOLIDATED_PROMPT = (+ "You are a Senior Curriculum Architect and Educational Psychologist. Extract the logical structure of knowledge points from the text.\n\n"+ "Rules:\n"+ "- Identify atomic concepts that constitute the learning path.\n"+ "- Establish clear directional dependencies (prerequisites).\n"+ "- Ensure that the resulting graph reflects a sound pedagogical sequence."+)++EDUCATION_NODE_PROMPT = (+ "You are an Educational Psychologist specializing in knowledge decomposition. Your task is to identify all discrete Knowledge Points (Nodes).\n\n"+ "Extraction Rules:\n"+ "- Focus on nouns or noun phrases that represent specific academic concepts, formulas, or methods.\n"+ "- Assign a difficulty level and concept type based on the context.\n"+ "- DO NOT identify relationships or dependencies at this stage."+)++EDUCATION_EDGE_PROMPT = (+ "You are a Curriculum Designer. Given the identified knowledge points, map the Prerequisite Relations (Edges).\n\n"+ "Extraction Rules:\n"+ "- Determine if Concept A is a necessary precursor to Concept B.\n"+ "- Classify the dependency as Prerequisite, Corequisite, or Recommended.\n"+ "- Only create relationships between concepts identified in the provided list."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class PrerequisiteMapGraph(AutoGraph[KnowledgePointNode, PrerequisiteRelation]):+ """+ Educational template for building Directed Acyclic Graphs (DAG) of knowledge dependencies.+ Useful for syllabus analysis, learning path generation, and student assessment planning.++ Example Usage:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> from hyperextract.templates.en.education.prerequisite_map import PrerequisiteMapGraph+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> graph = PrerequisiteMapGraph(llm, embedder)+ >>> graph.feed_text("To understand Calculus, one must first master Algebra and Functions.")+ >>> graph.extract()+ >>> 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,+ ):+ """+ Initialize the Prerequisite Map Template.++ Args:+ llm_client (BaseChatModel): The LLM used for extraction.+ embedder (Embeddings): The embedding model for node/edge deduplication.+ extraction_mode (str): 'one_stage' for consolidated extraction, 'two_stage' for separate node/edge passes.+ chunk_size (int): Size of text chunks for processing large documents.+ chunk_overlap (int): Overlap between chunks to preserve context.+ max_workers (int): Number of parallel workers for processing.+ verbose (bool): Whether to print detailed logs during execution.+ **kwargs: Additional parameters passed to the AutoGraph base class.+ """+ super().__init__(+ node_schema=KnowledgePointNode,+ edge_schema=PrerequisiteRelation,+ node_key_extractor=lambda x: x.name.strip().lower(),+ edge_key_extractor=lambda x: (+ f"{x.source.strip().lower()}->{x.target.strip().lower()}"+ ),+ nodes_in_edge_extractor=lambda x: (x.source.strip().lower(), x.target.strip().lower()),+ 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=EDUCATION_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=EDUCATION_NODE_PROMPT,+ prompt_for_edge_extraction=EDUCATION_EDGE_PROMPT,+ **kwargs,+ )diff --git a/hyperextract/templates/zh/education/__init__.py b/hyperextract/templates/zh/education/__init__.pyindex e69de29..7aee758 100644--- a/hyperextract/templates/zh/education/__init__.py+++ b/hyperextract/templates/zh/education/__init__.py@@ -0,0 +1,9 @@+from .prerequisite_map import PrerequisiteMapGraph+from .academic_lexicon import AcademicLexiconSet+from .interdisciplinary_nexus import InterdisciplinaryNexusHypergraph++__all__ = [+ "PrerequisiteMapGraph",+ "AcademicLexiconSet",+ "InterdisciplinaryNexusHypergraph",+]diff --git a/hyperextract/templates/zh/education/academic_lexicon.py b/hyperextract/templates/zh/education/academic_lexicon.pynew file mode 100644index 0000000..68b80cd--- /dev/null+++ b/hyperextract/templates/zh/education/academic_lexicon.py@@ -0,0 +1,97 @@+from typing import Optional, List, 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 AcademicTerm(BaseModel):+ """+ 从多个来源聚合的标准学术词条、概念或定义。+ """+ term: str = Field(+ description="学术词条/概念的主名称。作为唯一标识符。"+ )+ domain: str = Field(+ description="研究领域或学科(如:'热力学'、'语言学')。"+ )+ definition: str = Field(+ description="综合多个来源后形成的权威、详细的定义描述。"+ )+ synonyms: List[str] = Field(+ default_factory=list,+ description="同义词或高度相关的别称列表。"+ )+ key_expression: Optional[str] = Field(+ None, description="与该词条相关的核心公式、符号或标志性表达。"+ )++# ==============================================================================+# 2. Prompts 提示词+# ==============================================================================++ACADEMIC_LEXICON_PROMPT = (+ "你是一位学术百科全书编辑和词典编纂者。你的目标是提取并标准化学术定义。\n\n"+ "提取规则:\n"+ "- 识别唯一的学术术语及其高度精确的定义。\n"+ "- 寻找文本中出现的同义词、简称或别称。\n"+ "- 如果存在对同一术语的多个描述,优先选择数学上或逻辑上更严谨的描述,并尝试进行信息互补。"+)++# ==============================================================================+# 3. 模板类+# ==============================================================================++class AcademicLexiconSet(AutoSet[AcademicTerm]):+ """+ 用于构建去重且合成的学术名词百科集的教育模版。+ 利用 AutoSet 的合并策略,将来自不同教材或文献的定义融合成唯一的、信息最全的条目。++ 用法示例:+ >>> lexicon = AcademicLexiconSet(llm_client, embedder)+ >>> lexicon.feed_text("来源A:光合作用是植物利用光能...")+ >>> lexicon.feed_text("来源B:光合作用涉及叶绿素吸收光子...")+ >>> lexicon.extract() # 自动通过“项合并”功能将关于“光合作用”的不同侧重定义合并+ """++ 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,+ ):+ """+ 初始化学术名词百科模板。++ 参数描述:+ llm_client (BaseChatModel): 用于提取的语言模型客户端。+ embedder (Embeddings): 用于实体合并和去重的嵌入模型(AutoSet 的核心)。+ extraction_mode (str): 提取模式策略。+ chunk_size (int): 文本分片大小。+ chunk_overlap (int): 分片重叠大小。+ max_workers (int): 并行处理进程数。+ verbose (bool): 是否开启详细日志。+ **kwargs: 透传给 AutoSet 基类的其他参数(如自定义 merge_strategy)。+ """+ super().__init__(+ item_schema=AcademicTerm,+ key_extractor=lambda x: x.term.strip().lower(),+ 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=ACADEMIC_LEXICON_PROMPT,+ **kwargs,+ )diff --git a/hyperextract/templates/zh/education/interdisciplinary_nexus.py b/hyperextract/templates/zh/education/interdisciplinary_nexus.pynew file mode 100644index 0000000..cd2086f--- /dev/null+++ b/hyperextract/templates/zh/education/interdisciplinary_nexus.py@@ -0,0 +1,118 @@+from typing import List, 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 AutoHypergraph++# ==============================================================================+# 1. Schema 定义+# ==============================================================================++class ConceptNode(BaseModel):+ """+ 可能属于多个学科的基础学术概念。+ """+ name: str = Field(description="概念的标准名称。")+ primary_field: str = Field(description="该概念原生所属的主要学科。")++class InterdisciplinaryEdge(BaseModel):+ """+ 表示不同领域多个概念之间复杂联系的超边。+ """+ participants: List[str] = Field(+ description="参与该跨学科连接的所有节点名称列表。"+ )+ unifying_theme: str = Field(+ description="将这些概念连接在一起的跨学科主题(例如:'复杂性理论'、'通用设计')。"+ )+ connectivity_insight: str = Field(+ description="将这些特定知识点连接起来所产生的科学或教学价值。"+ )++# ==============================================================================+# 2. Prompts 提示词+# ==============================================================================++NEXUS_CONSOLIDATED_PROMPT = (+ "你是一位通才和跨学科研究专家。请识别不同学术领域概念之间的深层联系。\n\n"+ "提取规则:\n"+ "- 识别核心概念作为节点。\n"+ "- 创建超边,将多个概念归纳在一个统一的跨学科主题下。\n"+ "- 专注于发现令人惊讶但科学有效的桥梁连接(例如:通过博弈论连接生物学和经济学)。"+)++NEXUS_NODE_PROMPT = (+ "识别具有跨学科潜力的基础学术概念。\n\n"+ "提取规则:\n"+ "- 提取对各自领域至关重要的名词/概念。\n"+ "- 标注其学科来源。"+)++NEXUS_EDGE_PROMPT = (+ "识别连接一组概念的“纽带”或称之为超边。\n\n"+ "提取规则:\n"+ "- 只要可能,一个超边应涉及两个以上的节点。\n"+ "- 描述统一这些概念的主题以及这种连接提供的洞察力。"+)++# ==============================================================================+# 3. 模板类+# ==============================================================================++class InterdisciplinaryNexusHypergraph(AutoHypergraph[ConceptNode, InterdisciplinaryEdge]):+ """+ 用于映射多点、非二元学术联系的教育领域模板。+ 理想用于研究综述、课程跨学科设计以及跨学科知识管理。++ 用法示例:+ >>> nexus = InterdisciplinaryNexusHypergraph(llm, embedder)+ >>> nexus.feed_text("‘熵’这一概念同时适用于热力学中的‘热’和信息论中的‘信息’。")+ >>> nexus.extract()+ >>> # 结果将包含一个通过“熵”这一主题连接“热”与“信息”的超边。+ """++ 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,+ ):+ """+ 初始化跨学科纽带超图模板。++ 参数描述:+ llm_client (BaseChatModel): 用于提取的语言模型客户端。+ embedder (Embeddings): 用于节点去重的嵌入模型。+ extraction_mode (str): 提取模式。+ chunk_size (int): 文本分片大小。+ chunk_overlap (int): 分片重叠大小。+ max_workers (int): 并行处理进程数。+ verbose (bool): 是否打印日志。+ **kwargs: 透传给 AutoHypergraph 基类的其他参数(如一致性检查开关)。+ """+ super().__init__(+ node_schema=ConceptNode,+ edge_schema=InterdisciplinaryEdge,+ node_key_extractor=lambda x: x.name.strip().lower(),+ edge_key_extractor=lambda x: (+ f"{x.unifying_theme.strip().lower()}_linking_{sorted(x.participants)}"+ ),+ nodes_in_edge_extractor=lambda x: [p.strip().lower() for p in x.participants],+ 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=NEXUS_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=NEXUS_NODE_PROMPT,+ prompt_for_edge_extraction=NEXUS_EDGE_PROMPT,+ **kwargs,+ )diff --git a/hyperextract/templates/zh/education/prerequisite_map.py b/hyperextract/templates/zh/education/prerequisite_map.pynew file mode 100644index 0000000..19fca73--- /dev/null+++ b/hyperextract/templates/zh/education/prerequisite_map.py@@ -0,0 +1,132 @@+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 KnowledgePointNode(BaseModel):+ """+ 学科大纲中的原子知识单位、概念或技能。+ """+ name: str = Field(+ description="知识点或概念的标准名称。"+ )+ level: str = Field(+ description="难度等级:'入门'、'中级'、'高级'、'专家'。"+ )+ concept_type: str = Field(+ description="教学类型:'定义'、'定理'、'公式'、'方法'、'应用'。"+ )+ description: Optional[str] = Field(+ None, description="该概念的核心教学内涵简述。"+ )++class PrerequisiteRelation(BaseModel):+ """+ 有向依赖关系,表示一个概念必须在另一个概念之前学习。+ """+ source: str = Field(description="先修知识点(必须先学)。")+ target: str = Field(description="后续知识点(后学)。")+ dependency_type: str = Field(+ "Prerequisite",+ description="依赖性质:'必要' (必须先学), '同步' (建议同时学), '辅助' (有助于学习)。"+ )+ weight: float = Field(+ 1.0, description="依赖强度,范围从 0.0 到 1.0。"+ )++# ==============================================================================+# 2. Prompts 提示词+# ==============================================================================++EDUCATION_CONSOLIDATED_PROMPT = (+ "你是一位资深课程架构师和教育心理学家。请从文本中提取知识点的逻辑结构。\n\n"+ "提取规则:\n"+ "- 识别构成学习路径的原子化概念。\n"+ "- 建立清晰的有向依赖关系(先修要求)。\n"+ "- 确保生成的图谱符合科学的教学演进逻辑。"+)++EDUCATION_NODE_PROMPT = (+ "你是一位擅长知识拆解的教育心理学家。你的任务是识别所有离散的知识点(节点)。\n\n"+ "提取规则:\n"+ "- 关注代表特定学术概念、公式或方法的名词或名词短语。\n"+ "- 根据上下文分配难度等级和概念类型。\n"+ "- 此阶段不要识别关系或依赖。"+)++EDUCATION_EDGE_PROMPT = (+ "你是一位课程设计师。根据已识别的知识点,映射先修关系(边)。\n\n"+ "提取规则:\n"+ "- 确定概念 A 是否是学习概念 B 的必要前提。\n"+ "- 将依赖关系分类为必要、同步或辅助。\n"+ "- 仅在提供的概念列表之间建立关系。"+)++# ==============================================================================+# 3. 模板类+# ==============================================================================++class PrerequisiteMapGraph(AutoGraph[KnowledgePointNode, PrerequisiteRelation]):+ """+ 用于构建知识依赖有向无环图 (DAG) 的教育领域模板。+ 适用于教学大纲分析、自动化学习路径生成和学生测评规划。++ 用法示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> from hyperextract.templates.zh.education.prerequisite_map import PrerequisiteMapGraph+ >>> graph = PrerequisiteMapGraph(llm, embedder)+ >>> graph.feed_text("在理解微积分之前,必须先掌握代数和函数。")+ >>> graph.extract()+ >>> 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,+ ):+ """+ 初始化先修图谱模板。++ 参数描述:+ llm_client (BaseChatModel): 用于提取的语言模型客户端。+ 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=KnowledgePointNode,+ edge_schema=PrerequisiteRelation,+ node_key_extractor=lambda x: x.name.strip().lower(),+ edge_key_extractor=lambda x: (+ f"{x.source.strip().lower()}->{x.target.strip().lower()}"+ ),+ nodes_in_edge_extractor=lambda x: (x.source.strip().lower(), x.target.strip().lower()),+ 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=EDUCATION_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=EDUCATION_NODE_PROMPT,+ prompt_for_edge_extraction=EDUCATION_EDGE_PROMPT,+ **kwargs,+ )