Skip to content

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

Refactor various templates to improve code readability and consistency

yifanfeng97bb5e53cd599c
diff --git a/hyperextract/templates/en/agriculture/crop_cycle.py b/hyperextract/templates/en/agriculture/crop_cycle.py
index f8c5310..97ab79c 100644
--- a/hyperextract/templates/en/agriculture/crop_cycle.py
+++ b/hyperextract/templates/en/agriculture/crop_cycle.py
@@ -8,22 +8,31 @@ 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.")
+ 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.")
+ specification: Optional[str] = Field(
+ description="Dosage, timing, or specific impact details."
+ )
+
# ==============================================================================
# 2. Prompts
@@ -60,12 +69,13 @@ CROP_CYCLE_EDGE_PROMPT = (
# 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-4o")
@@ -75,6 +85,7 @@ class CropCycleGraph(AutoGraph[AgriEntity, AgriRelation]):
>>> graph.feed_text(text)
>>> print(graph.nodes) # Extracted Corn, Nitrogen, Vegetative Stage
"""
+
def __init__(
self,
llm_client: BaseChatModel,
@@ -85,7 +96,7 @@ class CropCycleGraph(AutoGraph[AgriEntity, AgriRelation]):
chunk_overlap: int = 256,
max_workers: int = 10,
verbose: bool = False,
- **kwargs: Any
+ **kwargs: Any,
):
"""
Initialize the CropCycleGraph template.
@@ -104,7 +115,9 @@ class CropCycleGraph(AutoGraph[AgriEntity, AgriRelation]):
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()}",
+ 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,
@@ -116,8 +129,9 @@ class CropCycleGraph(AutoGraph[AgriEntity, AgriRelation]):
prompt=CROP_CYCLE_PROMPT,
prompt_for_node_extraction=CROP_CYCLE_NODE_PROMPT,
prompt_for_edge_extraction=CROP_CYCLE_EDGE_PROMPT,
- **kwargs
+ **kwargs,
)
+
def show(
self,
*,
@@ -128,21 +142,21 @@ class CropCycleGraph(AutoGraph[AgriEntity, AgriRelation]):
) -> 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}"
-
+ info = f" ({node.category})" if getattr(node, "category", None) else ""
+ return f"{node.name}{info}"
+
def edge_label_extractor(edge: AgriRelation) -> str:
- info = f" ({ edge.specification })" if getattr(edge, "specification", None) else ""
- return f"{ edge.source }{info}"
-
+ return f"{edge.relation_type}"
+
super().show(
node_label_extractor=node_label_extractor,
edge_label_extractor=edge_label_extractor,
diff --git a/hyperextract/templates/en/agriculture/livestock.py b/hyperextract/templates/en/agriculture/livestock.py
index 399d99b..f4285df 100644
--- a/hyperextract/templates/en/agriculture/livestock.py
+++ b/hyperextract/templates/en/agriculture/livestock.py
@@ -8,22 +8,31 @@ 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.")
+ 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.")
+ details: Optional[str] = Field(
+ description="Inherited traits, dosage, or specific health observations."
+ )
+
# ==============================================================================
# 2. Prompts
@@ -51,12 +60,13 @@ LIVESTOCK_EDGE_PROMPT = (
# 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-4o")
@@ -66,6 +76,7 @@ class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):
>>> graph.feed_text(text)
>>> print(graph.edges) # Extracted breeding relationship
"""
+
def __init__(
self,
llm_client: BaseChatModel,
@@ -76,7 +87,7 @@ class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):
chunk_overlap: int = 256,
max_workers: int = 10,
verbose: bool = False,
- **kwargs: Any
+ **kwargs: Any,
):
"""
Initialize the LivestockGraph template.
@@ -95,7 +106,9 @@ class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):
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()}",
+ 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,
@@ -107,8 +120,9 @@ class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):
prompt=LIVESTOCK_GRAPH_PROMPT,
prompt_for_node_extraction=LIVESTOCK_NODE_PROMPT,
prompt_for_edge_extraction=LIVESTOCK_EDGE_PROMPT,
- **kwargs
+ **kwargs,
)
+
def show(
self,
*,
@@ -119,20 +133,21 @@ class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):
) -> 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}"
-
+ 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.source }"
-
+ return f"{edge.relation_type}"
+
super().show(
node_label_extractor=node_label_extractor,
edge_label_extractor=edge_label_extractor,
diff --git a/hyperextract/templates/en/agriculture/supply_chain.py b/hyperextract/templates/en/agriculture/supply_chain.py
index 2d4f2eb..70e5989 100644
--- a/hyperextract/templates/en/agriculture/supply_chain.py
+++ b/hyperextract/templates/en/agriculture/supply_chain.py
@@ -8,22 +8,31 @@ from hyperextract.types import AutoGraph
# 1. Schema Definitions
# ==============================================================================
+
class SupplyEntity(BaseModel):
"""An actor or asset in the agri-supply chain (e.g., Farm, Warehouse, Processor, Logistics, Retailer)."""
+
name: str = Field(description="Name of the organization, facility, or batch ID.")
category: str = Field(
description="Category: 'Producer/Farm', 'Processor', 'Distributor', 'Logistics Provider', 'Retailer', 'Batch/Product'."
)
- location_or_cert: Optional[str] = Field(description="Geographic location or quality certification (e.g., Organic, ISO).")
+ location_or_cert: Optional[str] = Field(
+ description="Geographic location or quality certification (e.g., Organic, ISO)."
+ )
+
class SupplyFlow(BaseModel):
"""The flow of products or information between supply chain actors."""
+
source: str = Field(description="The starting entity (sender/producer).")
target: str = Field(description="The receiving entity (buyer/processor).")
flow_type: str = Field(
description="Type: 'Ships to', 'Processes', 'Sells to', 'Tests', 'Certifies'."
)
- specification: Optional[str] = Field(description="Quantity, transportation mode, or quality check result.")
+ specification: Optional[str] = Field(
+ description="Quantity, transportation mode, or quality check result."
+ )
+
# ==============================================================================
# 2. Prompts
@@ -51,12 +60,13 @@ AGRI_SUPPLY_CHAIN_EDGE_PROMPT = (
# 3. Template Class
# ==============================================================================
+
class AgriSupplyChain(AutoGraph[SupplyEntity, SupplyFlow]):
"""
Template for agricultural traceability, logistics mapping, and supply chain transparency.
-
+
Ideal for food safety tracking, logistics optimization, and trade analysis.
-
+
Example:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
>>> llm = ChatOpenAI(model="gpt-4o")
@@ -66,6 +76,7 @@ class AgriSupplyChain(AutoGraph[SupplyEntity, SupplyFlow]):
>>> graph.feed_text(text)
>>> print(graph.edges) # Extracted logistics flow
"""
+
def __init__(
self,
llm_client: BaseChatModel,
@@ -76,7 +87,7 @@ class AgriSupplyChain(AutoGraph[SupplyEntity, SupplyFlow]):
chunk_overlap: int = 256,
max_workers: int = 10,
verbose: bool = False,
- **kwargs: Any
+ **kwargs: Any,
):
"""
Initialize the AgriSupplyChain template.
@@ -95,7 +106,9 @@ class AgriSupplyChain(AutoGraph[SupplyEntity, SupplyFlow]):
node_schema=SupplyEntity,
edge_schema=SupplyFlow,
node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source.strip()}--({x.flow_type.lower()})-->{x.target.strip()}",
+ edge_key_extractor=lambda x: (
+ f"{x.source.strip()}--({x.flow_type.lower()})-->{x.target.strip()}"
+ ),
nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),
llm_client=llm_client,
embedder=embedder,
@@ -107,8 +120,9 @@ class AgriSupplyChain(AutoGraph[SupplyEntity, SupplyFlow]):
prompt=AGRI_SUPPLY_CHAIN_PROMPT,
prompt_for_node_extraction=AGRI_SUPPLY_CHAIN_NODE_PROMPT,
prompt_for_edge_extraction=AGRI_SUPPLY_CHAIN_EDGE_PROMPT,
- **kwargs
+ **kwargs,
)
+
def show(
self,
*,
@@ -119,21 +133,21 @@ class AgriSupplyChain(AutoGraph[SupplyEntity, SupplyFlow]):
) -> 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: SupplyEntity) -> str:
- info = f" ({ node.category })" if getattr(node, "category", None) else ""
- return f"{ node.name }{info}"
-
+ info = f" ({node.category})" if getattr(node, "category", None) else ""
+ return f"{node.name}{info}"
+
def edge_label_extractor(edge: SupplyFlow) -> str:
- info = f" ({ edge.specification })" if getattr(edge, "specification", None) else ""
- return f"{ edge.source }{info}"
-
+ return f"{edge.flow_type}"
+
super().show(
node_label_extractor=node_label_extractor,
edge_label_extractor=edge_label_extractor,
diff --git a/hyperextract/templates/en/art/exhibition.py b/hyperextract/templates/en/art/exhibition.py
index 65ffe83..1ac4a8c 100644
--- a/hyperextract/templates/en/art/exhibition.py
+++ b/hyperextract/templates/en/art/exhibition.py
@@ -8,22 +8,31 @@ from hyperextract.types import AutoGraph
# 1. Schema Definitions
# ==============================================================================
+
class ExhibitionEntity(BaseModel):
"""An element of an art exhibition (Curator, Theme, Work, Venue, Sponsor)."""
+
name: str = Field(description="Name of the exhibition, artist, or curator.")
type: str = Field(
description="Type: 'Exhibition', 'Theme', 'Artwork', 'Curator', 'Venue', 'Partner'."
)
- details: Optional[str] = Field(description="Exhibition dates, conceptual notes, or location.")
+ details: Optional[str] = Field(
+ description="Exhibition dates, conceptual notes, or location."
+ )
+
class ExhibitionRelation(BaseModel):
"""Connectivity within an exhibition's planning and execution."""
+
source: str = Field(description="The organizing or controlling entity.")
target: str = Field(description="The related work or participant.")
relation_type: str = Field(
description="Type: 'Curated by', 'Featured in', 'Hosted at', 'Sponsored by', 'Thematically linked to'."
)
- context: Optional[str] = Field(description="Specific room, loan conditions, or thematic sub-group.")
+ context: Optional[str] = Field(
+ description="Specific room, loan conditions, or thematic sub-group."
+ )
+
# ==============================================================================
# 2. Prompts
@@ -37,24 +46,21 @@ EXHIBITION_GRAPH_PROMPT = (
"- Capture logistics like venues and sponsors."
)
-EXHIBITION_NODE_PROMPT = (
- "Extract exhibition components: titles, venues, themes, specific artworks, and key personnel (curators, designers)."
-)
+EXHIBITION_NODE_PROMPT = "Extract exhibition components: titles, venues, themes, specific artworks, and key personnel (curators, designers)."
-EXHIBITION_EDGE_PROMPT = (
- "Link items within the exhibition. Show which artworks belong to which theme and identify the hosting venue and sponsors."
-)
+EXHIBITION_EDGE_PROMPT = "Link items within the exhibition. Show which artworks belong to which theme and identify the hosting venue and sponsors."
# ==============================================================================
# 3. Template Class
# ==============================================================================
+
class ExhibitionGraph(AutoGraph[ExhibitionEntity, ExhibitionRelation]):
"""
Template for curatorial planning and exhibition analysis.
-
+
Tracks the relationships between artworks, themes, curators, and venues.
-
+
Example:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
>>> llm = ChatOpenAI()
@@ -64,6 +70,7 @@ class ExhibitionGraph(AutoGraph[ExhibitionEntity, ExhibitionRelation]):
>>> graph.feed_text(text)
>>> print(graph.edges) # Exhibition connections
"""
+
def __init__(
self,
llm_client: BaseChatModel,
@@ -74,7 +81,7 @@ class ExhibitionGraph(AutoGraph[ExhibitionEntity, ExhibitionRelation]):
chunk_overlap: int = 256,
max_workers: int = 10,
verbose: bool = False,
- **kwargs: Any
+ **kwargs: Any,
):
"""
Initialize the ExhibitionGraph template.
@@ -93,7 +100,9 @@ class ExhibitionGraph(AutoGraph[ExhibitionEntity, ExhibitionRelation]):
node_schema=ExhibitionEntity,
edge_schema=ExhibitionRelation,
node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation_type.lower()})-->{x.target.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,
@@ -105,8 +114,9 @@ class ExhibitionGraph(AutoGraph[ExhibitionEntity, ExhibitionRelation]):
prompt=EXHIBITION_GRAPH_PROMPT,
prompt_for_node_extraction=EXHIBITION_NODE_PROMPT,
prompt_for_edge_extraction=EXHIBITION_EDGE_PROMPT,
- **kwargs
+ **kwargs,
)
+
def show(
self,
*,
@@ -117,20 +127,21 @@ class ExhibitionGraph(AutoGraph[ExhibitionEntity, ExhibitionRelation]):
) -> 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: ExhibitionEntity) -> str:
- info = f" ({ node.type })" if getattr(node, "type", None) else ""
- return f"{ node.name }{info}"
-
+ info = f" ({node.type})" if getattr(node, "type", None) else ""
+ return f"{node.name}{info}"
+
def edge_label_extractor(edge: ExhibitionRelation) -> str:
- return f"{ edge.source }"
-
+ return f"{edge.relation_type}"
+
super().show(
node_label_extractor=node_label_extractor,
edge_label_extractor=edge_label_extractor,
diff --git a/hyperextract/templates/en/art/movement.py b/hyperextract/templates/en/art/movement.py
index 063997a..1558901 100644
--- a/hyperextract/templates/en/art/movement.py
+++ b/hyperextract/templates/en/art/movement.py
@@ -8,22 +8,33 @@ from hyperextract.types import AutoGraph
# 1. Schema Definitions
# ==============================================================================
+
class MovementEntity(BaseModel):
"""An art movement, style, artist, or influential work."""
- name: str = Field(description="Name of the movement (e.g., Impressionism) or Artist.")
+
+ name: str = Field(
+ description="Name of the movement (e.g., Impressionism) or Artist."
+ )
category: str = Field(
description="Category: 'Movement', 'Style', 'Artist', 'Manifesto', 'Masterpiece'."
)
- attributes: Optional[str] = Field(description="Key characteristics, materials, or timeframe.")
+ attributes: Optional[str] = Field(
+ description="Key characteristics, materials, or timeframe."
+ )
+
class ArtInfluenceEdge(BaseModel):
"""Influence, derivation, or membership relations in art history."""
+
source: str = Field(description="The precursor or movement.")
target: str = Field(description="The follower or specific work/artist.")
relation: str = Field(
description="Relation: 'Influenced', 'Founder of', 'Member of', 'Reaction against', 'Derived from'."
)
- details: Optional[str] = Field(description="Specific stylistic techniques or historical events.")
+ details: Optional[str] = Field(
+ description="Specific stylistic techniques or historical events."
+ )
+
# ==============================================================================
# 2. Prompts
@@ -37,9 +48,7 @@ MOVEMENT_GRAPH_PROMPT = (
"- Capture the core philosophies and visual characteristics defined in manifestos or works."
)
-MOVEMENT_NODE_PROMPT = (
- "Extract art movements, styles, associated artists, and pivotal artworks. Describe their visual language and key theories."
-)
+MOVEMENT_NODE_PROMPT = "Extract art movements, styles, associated artists, and pivotal artworks. Describe their visual language and key theories."
MOVEMENT_EDGE_PROMPT = (
"Define connections between movements and individuals. Use relations like 'Reaction against' or 'Influenced'. "
@@ -50,12 +59,13 @@ MOVEMENT_EDGE_PROMPT = (
# 3. Template Class
# ==============================================================================
+
class ArtMovementGraph(AutoGraph[MovementEntity, ArtInfluenceEdge]):
"""
Template for mapping art movements, stylistic influences, and artist school affiliations.
-
+
Useful for educational applications and art historical analysis.
-
+
Example:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
>>> llm = ChatOpenAI()
@@ -65,6 +75,7 @@ class ArtMovementGraph(AutoGraph[MovementEntity, ArtInfluenceEdge]):
>>> graph.feed_text(text)
>>> print(graph.nodes) # Movement and Artist details
"""
+
def __init__(
self,
llm_client: BaseChatModel,
@@ -75,7 +86,7 @@ class ArtMovementGraph(AutoGraph[MovementEntity, ArtInfluenceEdge]):
chunk_overlap: int = 256,
max_workers: int = 10,
verbose: bool = False,
- **kwargs: Any
+ **kwargs: Any,
):
"""
Initialize the ArtMovementGraph template.
@@ -94,7 +105,9 @@ class ArtMovementGraph(AutoGraph[MovementEntity, ArtInfluenceEdge]):
node_schema=MovementEntity,
edge_schema=ArtInfluenceEdge,
node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation.lower()})-->{x.target.strip()}",
+ edge_key_extractor=lambda x: (
+ f"{x.source.strip()}--({x.relation.lower()})-->{x.target.strip()}"
+ ),
nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),
llm_client=llm_client,
embedder=embedder,
@@ -106,8 +119,9 @@ class ArtMovementGraph(AutoGraph[MovementEntity, ArtInfluenceEdge]):
prompt=MOVEMENT_GRAPH_PROMPT,
prompt_for_node_extraction=MOVEMENT_NODE_PROMPT,
prompt_for_edge_extraction=MOVEMENT_EDGE_PROMPT,
- **kwargs
+ **kwargs,
)
+
def show(
self,
*,
@@ -118,20 +132,21 @@ class ArtMovementGraph(AutoGraph[MovementEntity, ArtInfluenceEdge]):
) -> 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: MovementEntity) -> str:
- info = f" ({ node.category })" if getattr(node, "category", None) else ""
- return f"{ node.name }{info}"
-
+ info = f" ({node.category})" if getattr(node, "category", None) else ""
+ return f"{node.name}{info}"
+
def edge_label_extractor(edge: ArtInfluenceEdge) -> str:
- return f"{ edge.source }"
-
+ return f"{edge.relation}"
+
super().show(
node_label_extractor=node_label_extractor,
edge_label_extractor=edge_label_extractor,
diff --git a/hyperextract/templates/en/art/provenance.py b/hyperextract/templates/en/art/provenance.py
index 8c65bf4..584c3fc 100644
--- a/hyperextract/templates/en/art/provenance.py
+++ b/hyperextract/templates/en/art/provenance.py
@@ -8,22 +8,31 @@ from hyperextract.types import AutoGraph
# 1. Schema Definitions
# ==============================================================================
+
class ArtEntity(BaseModel):
"""An entity in the art world (e.g., Artwork, Artist, Museum, Collector, Auction House)."""
+
name: str = Field(description="Name of the artwork, person, or organization.")
category: str = Field(
description="Category: 'Artwork', 'Artist', 'Collector', 'Institution', 'Location'."
)
- description: Optional[str] = Field(description="Medium, creation date, or historical status.")
+ description: Optional[str] = Field(
+ description="Medium, creation date, or historical status."
+ )
+
class ProvenanceEdge(BaseModel):
"""The transfer of ownership or location of an artwork."""
+
source: str = Field(description="Previous owner or starting location.")
target: str = Field(description="New owner or destination.")
transfer_type: str = Field(
description="Type: 'Acquired by', 'Sold to', 'Donated to', 'Lent to', 'Commissioned by'."
)
- specification: Optional[str] = Field(description="Date of transfer, sale price, or auction details.")
+ specification: Optional[str] = Field(
+ description="Date of transfer, sale price, or auction details."
+ )
+
# ==============================================================================
# 2. Prompts
@@ -51,12 +60,13 @@ PROVENANCE_EDGE_PROMPT = (
# 3. Template Class
# ==============================================================================
+
class ProvenanceGraph(AutoGraph[ArtEntity, ProvenanceEdge]):
"""
Template for tracking the ownership history (provenance) of artworks and artifacts.
-
+
Essential for art authentication, museum archives, and historical research.
-
+
Example:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
>>> llm = ChatOpenAI(model="gpt-4o")
@@ -66,6 +76,7 @@ class ProvenanceGraph(AutoGraph[ArtEntity, ProvenanceEdge]):
>>> graph.feed_text(text)
>>> print(graph.edges) # Extracted ownership transfer
"""
+
def __init__(
self,
llm_client: BaseChatModel,
@@ -76,7 +87,7 @@ class ProvenanceGraph(AutoGraph[ArtEntity, ProvenanceEdge]):
chunk_overlap: int = 256,
max_workers: int = 10,
verbose: bool = False,
- **kwargs: Any
+ **kwargs: Any,
):
"""
Initialize the ProvenanceGraph template.
@@ -95,7 +106,9 @@ class ProvenanceGraph(AutoGraph[ArtEntity, ProvenanceEdge]):
node_schema=ArtEntity,
edge_schema=ProvenanceEdge,
node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source.strip()}--({x.transfer_type.lower()})-->{x.target.strip()}",
+ edge_key_extractor=lambda x: (
+ f"{x.source.strip()}--({x.transfer_type.lower()})-->{x.target.strip()}"
+ ),
nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),
llm_client=llm_client,
embedder=embedder,
@@ -107,8 +120,9 @@ class ProvenanceGraph(AutoGraph[ArtEntity, ProvenanceEdge]):
prompt=PROVENANCE_GRAPH_PROMPT,
prompt_for_node_extraction=PROVENANCE_NODE_PROMPT,
prompt_for_edge_extraction=PROVENANCE_EDGE_PROMPT,
- **kwargs
+ **kwargs,
)
+
def show(
self,
*,
@@ -119,21 +133,21 @@ class ProvenanceGraph(AutoGraph[ArtEntity, ProvenanceEdge]):
) -> 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: ArtEntity) -> str:
- info = f" ({ node.category })" if getattr(node, "category", None) else ""
- return f"{ node.name }{info}"
-
+ info = f" ({node.category})" if getattr(node, "category", None) else ""
+ return f"{node.name}{info}"
+
def edge_label_extractor(edge: ProvenanceEdge) -> str:
- info = f" ({ edge.specification })" if getattr(edge, "specification", None) else ""
- return f"{ edge.source }{info}"
-
+ return f"{edge.transfer_type}"
+
super().show(
node_label_extractor=node_label_extractor,
edge_label_extractor=edge_label_extractor,
diff --git a/hyperextract/templates/zh/agriculture/crop_cycle.py b/hyperextract/templates/zh/agriculture/crop_cycle.py
index 4087181..04ee2d2 100644
--- a/hyperextract/templates/zh/agriculture/crop_cycle.py
+++ b/hyperextract/templates/zh/agriculture/crop_cycle.py
@@ -136,12 +136,11 @@ class CropCycleGraph(AutoGraph[AgriEntity, AgriRelation]):
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}"
+ info = f" ({node.category})" if getattr(node, "category", None) else ""
+ return f"{node.name}{info}"
def edge_label_extractor(edge: AgriRelation) -> str:
- info = f" ({ edge.specification })" if getattr(edge, "specification", None) else ""
- return f"{ edge.source }{info}"
+ return f"{edge.relation_type}"
super().show(
node_label_extractor=node_label_extractor,
diff --git a/hyperextract/templates/zh/agriculture/livestock.py b/hyperextract/templates/zh/agriculture/livestock.py
index 2e1499c..8a0d8fd 100644
--- a/hyperextract/templates/zh/agriculture/livestock.py
+++ b/hyperextract/templates/zh/agriculture/livestock.py
@@ -8,16 +8,20 @@ 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(
@@ -25,6 +29,7 @@ class BreedingRelation(BaseModel):
)
details: Optional[str] = Field(description="继承特征、剂量或具体的健康观察。")
+
# ==============================================================================
# 2. 提示词 (Prompts)
# ==============================================================================
@@ -37,24 +42,21 @@ LIVESTOCK_GRAPH_PROMPT = (
"- 将动物与其健康状况、疫苗接种和营养记录关联起来。"
)
-LIVESTOCK_NODE_PROMPT = (
- "请提取畜牧实体:识别特定动物(通过ID或名称)、品种、健康状况、疫苗类型以及特定的饲料。为每一项提供相关的特征或指标。"
-)
+LIVESTOCK_NODE_PROMPT = "请提取畜牧实体:识别特定动物(通过ID或名称)、品种、健康状况、疫苗类型以及特定的饲料。为每一项提供相关的特征或指标。"
-LIVESTOCK_EDGE_PROMPT = (
- "逻辑化地连接畜牧实体。映射家族树(亲缘链接)、育种历史以及医疗/营养事件。确保准确使用'与...交配'或'饲喂'等关系类型。"
-)
+LIVESTOCK_EDGE_PROMPT = "逻辑化地连接畜牧实体。映射家族树(亲缘链接)、育种历史以及医疗/营养事件。确保准确使用'与...交配'或'饲喂'等关系类型。"
# ==============================================================================
# 3. 模板类 (Template Class)
# ==============================================================================
+
class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):
"""
用于管理畜牧系谱、健康记录和育种计划的模板。
-
+
适用于牧场管理软件、兽医记录和基因追踪。
-
+
示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
>>> llm = ChatOpenAI(model="gpt-4o")
@@ -64,6 +66,7 @@ class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):
>>> graph.feed_text(text)
>>> print(graph.edges) # 提取育种关系
"""
+
def __init__(
self,
llm_client: BaseChatModel,
@@ -74,7 +77,7 @@ class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):
chunk_overlap: int = 256,
max_workers: int = 10,
verbose: bool = False,
- **kwargs: Any
+ **kwargs: Any,
):
"""
初始化 LivestockGraph 模板。
@@ -93,7 +96,9 @@ class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):
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()}",
+ 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,
@@ -105,8 +110,9 @@ class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):
prompt=LIVESTOCK_GRAPH_PROMPT,
prompt_for_node_extraction=LIVESTOCK_NODE_PROMPT,
prompt_for_edge_extraction=LIVESTOCK_EDGE_PROMPT,
- **kwargs
+ **kwargs,
)
+
def show(
self,
*,
@@ -117,20 +123,21 @@ class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):
) -> 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}"
-
+ 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.source }"
-
+ return f"{edge.relation_type}"
+
super().show(
node_label_extractor=node_label_extractor,
edge_label_extractor=edge_label_extractor,
diff --git a/hyperextract/templates/zh/agriculture/supply_chain.py b/hyperextract/templates/zh/agriculture/supply_chain.py
index a3cbe83..0590415 100644
--- a/hyperextract/templates/zh/agriculture/supply_chain.py
+++ b/hyperextract/templates/zh/agriculture/supply_chain.py
@@ -8,16 +8,22 @@ from hyperextract.types import AutoGraph
# 1. Schema 定义 (Schema Definitions)
# ==============================================================================
+
class SupplyEntity(BaseModel):
"""农产品供应链中的参与者或资产(如农场、仓库、加工商、物流商、零售商)。"""
+
name: str = Field(description="机构、设施的名称或批次ID。")
category: str = Field(
description="类别:'生产者/农场', '加工商', '分销商', '物流商', '零售商', '批次/产品'。"
)
- location_or_cert: Optional[str] = Field(description="地理位置或质量认证(如:有机认证、ISO)。")
+ location_or_cert: Optional[str] = Field(
+ description="地理位置或质量认证(如:有机认证、ISO)。"
+ )
+
class SupplyFlow(BaseModel):
"""供应链参与者之间的产品或信息流。"""
+
source: str = Field(description="起始实体(发送方/生产者)。")
target: str = Field(description="接收实体(购买方/加工商)。")
flow_type: str = Field(
@@ -25,6 +31,7 @@ class SupplyFlow(BaseModel):
)
specification: Optional[str] = Field(description="数量、运输方式或质量检测结果。")
+
# ==============================================================================
# 2. 提示词 (Prompts)
# ==============================================================================
@@ -37,24 +44,21 @@ AGRI_SUPPLY_CHAIN_PROMPT = (
"- 捕获文本中提到的质量检测、认证和运输方式。"
)
-AGRI_SUPPLY_CHAIN_NODE_PROMPT = (
- "请提取供应链实体:识别特定的农场、工厂、物流枢纽和零售商。记录它们的角色、位置以及提及的任何质量认证。"
-)
+AGRI_SUPPLY_CHAIN_NODE_PROMPT = "请提取供应链实体:识别特定的农场、工厂、物流枢纽和零售商。记录它们的角色、位置以及提及的任何质量认证。"
-AGRI_SUPPLY_CHAIN_EDGE_PROMPT = (
- "建立货物与信息的流动。连接生产者到加工商,以及加工商到零售商。使用'发货至'或'加工'等具体的关系类型,并包含运输方式或数量等细节。"
-)
+AGRI_SUPPLY_CHAIN_EDGE_PROMPT = "建立货物与信息的流动。连接生产者到加工商,以及加工商到零售商。使用'发货至'或'加工'等具体的关系类型,并包含运输方式或数量等细节。"
# ==============================================================================
# 3. 模板类 (Template Class)
# ==============================================================================
+
class AgriSupplyChain(AutoGraph[SupplyEntity, SupplyFlow]):
"""
用于农产品溯源、物流映射和供应链透明化的模板。
-
+
适用于食品安全追踪、物流优化和贸易分析。
-
+
示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
>>> llm = ChatOpenAI(model="gpt-4o")
@@ -64,6 +68,7 @@ class AgriSupplyChain(AutoGraph[SupplyEntity, SupplyFlow]):
>>> graph.feed_text(text)
>>> print(graph.edges) # 提取物流流向
"""
+
def __init__(
self,
llm_client: BaseChatModel,
@@ -74,7 +79,7 @@ class AgriSupplyChain(AutoGraph[SupplyEntity, SupplyFlow]):
chunk_overlap: int = 256,
max_workers: int = 10,
verbose: bool = False,
- **kwargs: Any
+ **kwargs: Any,
):
"""
初始化 AgriSupplyChain 模板。
@@ -93,7 +98,9 @@ class AgriSupplyChain(AutoGraph[SupplyEntity, SupplyFlow]):
node_schema=SupplyEntity,
edge_schema=SupplyFlow,
node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source.strip()}--({x.flow_type.lower()})-->{x.target.strip()}",
+ edge_key_extractor=lambda x: (
+ f"{x.source.strip()}--({x.flow_type.lower()})-->{x.target.strip()}"
+ ),
nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),
llm_client=llm_client,
embedder=embedder,
@@ -105,8 +112,9 @@ class AgriSupplyChain(AutoGraph[SupplyEntity, SupplyFlow]):
prompt=AGRI_SUPPLY_CHAIN_PROMPT,
prompt_for_node_extraction=AGRI_SUPPLY_CHAIN_NODE_PROMPT,
prompt_for_edge_extraction=AGRI_SUPPLY_CHAIN_EDGE_PROMPT,
- **kwargs
+ **kwargs,
)
+
def show(
self,
*,
@@ -117,21 +125,21 @@ class AgriSupplyChain(AutoGraph[SupplyEntity, SupplyFlow]):
) -> 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: SupplyEntity) -> str:
- info = f" ({ node.category })" if getattr(node, "category", None) else ""
- return f"{ node.name }{info}"
-
+ info = f" ({node.category})" if getattr(node, "category", None) else ""
+ return f"{node.name}{info}"
+
def edge_label_extractor(edge: SupplyFlow) -> str:
- info = f" ({ edge.specification })" if getattr(edge, "specification", None) else ""
- return f"{ edge.source }{info}"
-
+ return f"{edge.flow_type}"
+
super().show(
node_label_extractor=node_label_extractor,
edge_label_extractor=edge_label_extractor,
diff --git a/hyperextract/templates/zh/art/exhibition.py b/hyperextract/templates/zh/art/exhibition.py
index 09523b6..6000d8c 100644
--- a/hyperextract/templates/zh/art/exhibition.py
+++ b/hyperextract/templates/zh/art/exhibition.py
@@ -8,16 +8,20 @@ from hyperextract.types import AutoGraph
# 1. 模式定义 (Schema)
# ==============================================================================
+
class ExhibitionEntity(BaseModel):
"""艺术展览的组成要素(策展人、主题、作品、场馆、赞助商)。"""
+
name: str = Field(description="展览名称、艺术家姓名或策展人姓名。")
type: str = Field(
description="类型:'展览'、'主题'、'艺术品'、'策展人'、'场馆'、'合作伙伴'。"
)
details: Optional[str] = Field(description="展览日期、理念说明或地理位置。")
+
class ExhibitionRelation(BaseModel):
"""展览策划与执行中的连接关系。"""
+
source: str = Field(description="组织或控制实体。")
target: str = Field(description="相关的作品 or 参与者。")
relation_type: str = Field(
@@ -25,6 +29,7 @@ class ExhibitionRelation(BaseModel):
)
context: Optional[str] = Field(description="具体展厅、借展条件或主题子组。")
+
# ==============================================================================
# 2. 提示词 (Prompts)
# ==============================================================================
@@ -49,12 +54,13 @@ EXHIBITION_EDGE_PROMPT = (
# 3. 模板类
# ==============================================================================
+
class ExhibitionGraph(AutoGraph[ExhibitionEntity, ExhibitionRelation]):
"""
展览策划图谱模板,用于策划筹备和展览分析。
-
+
追踪艺术品、主题、策展人和场馆之间的关系。
-
+
示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
>>> llm = ChatOpenAI()
@@ -64,6 +70,7 @@ class ExhibitionGraph(AutoGraph[ExhibitionEntity, ExhibitionRelation]):
>>> graph.feed_text(text)
>>> print(graph.edges) # 展览关联信息
"""
+
def __init__(
self,
llm_client: BaseChatModel,
@@ -74,7 +81,7 @@ class ExhibitionGraph(AutoGraph[ExhibitionEntity, ExhibitionRelation]):
chunk_overlap: int = 256,
max_workers: int = 10,
verbose: bool = False,
- **kwargs: Any
+ **kwargs: Any,
):
"""
初始化展览策划图谱模板。
@@ -93,7 +100,9 @@ class ExhibitionGraph(AutoGraph[ExhibitionEntity, ExhibitionRelation]):
node_schema=ExhibitionEntity,
edge_schema=ExhibitionRelation,
node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation_type.lower()})-->{x.target.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,
@@ -105,8 +114,9 @@ class ExhibitionGraph(AutoGraph[ExhibitionEntity, ExhibitionRelation]):
prompt=EXHIBITION_GRAPH_PROMPT,
prompt_for_node_extraction=EXHIBITION_NODE_PROMPT,
prompt_for_edge_extraction=EXHIBITION_EDGE_PROMPT,
- **kwargs
+ **kwargs,
)
+
def show(
self,
*,
@@ -117,20 +127,21 @@ class ExhibitionGraph(AutoGraph[ExhibitionEntity, ExhibitionRelation]):
) -> 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: ExhibitionEntity) -> str:
- info = f" ({ node.type })" if getattr(node, "type", None) else ""
- return f"{ node.name }{info}"
-
+ info = f" ({node.type})" if getattr(node, "type", None) else ""
+ return f"{node.name}{info}"
+
def edge_label_extractor(edge: ExhibitionRelation) -> str:
- return f"{ edge.source }"
-
+ return f"{edge.relation_type}"
+
super().show(
node_label_extractor=node_label_extractor,
edge_label_extractor=edge_label_extractor,
diff --git a/hyperextract/templates/zh/art/movement.py b/hyperextract/templates/zh/art/movement.py
index 149af30..8def0cd 100644
--- a/hyperextract/templates/zh/art/movement.py
+++ b/hyperextract/templates/zh/art/movement.py
@@ -8,16 +8,20 @@ from hyperextract.types import AutoGraph
# 1. 模式定义 (Schema)
# ==============================================================================
+
class MovementEntity(BaseModel):
"""艺术流派、风格、艺术家或具有影响力的作品。"""
+
name: str = Field(description="流派名称(如:印象派)或艺术家姓名。")
category: str = Field(
description="类别:'流派'、'风格'、'艺术家'、'宣言'、'代表作'。"
)
attributes: Optional[str] = Field(description="核心特征、常用媒介或流行时期。")
+
class ArtInfluenceEdge(BaseModel):
"""艺术史中的影响、衍生或成员关系。"""
+
source: str = Field(description="前驱流派 or 影响源。")
target: str = Field(description="后继流派、具体作品或艺术家。")
relation: str = Field(
@@ -25,6 +29,7 @@ class ArtInfluenceEdge(BaseModel):
)
details: Optional[str] = Field(description="具体的风格技巧传承或历史事件。")
+
# ==============================================================================
# 2. 提示词 (Prompts)
# ==============================================================================
@@ -41,20 +46,19 @@ MOVEMENT_NODE_PROMPT = (
"提取艺术流派、风格、相关艺术家及关键作品。描述其视觉语言和核心理论。"
)
-MOVEMENT_EDGE_PROMPT = (
- "定义流派与个人之间的联系。使用诸如'是对...的反叛'或'影响了'等关系词。记录代际之间传递的具体技法。"
-)
+MOVEMENT_EDGE_PROMPT = "定义流派与个人之间的联系。使用诸如'是对...的反叛'或'影响了'等关系词。记录代际之间传递的具体技法。"
# ==============================================================================
# 3. 模板类
# ==============================================================================
+
class ArtMovementGraph(AutoGraph[MovementEntity, ArtInfluenceEdge]):
"""
艺术流派图谱模板,用于映射艺术风格、流派影响力和艺术家所属流派。
-
+
适用于教学应用和艺术史深度分析。
-
+
示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
>>> llm = ChatOpenAI()
@@ -64,6 +68,7 @@ class ArtMovementGraph(AutoGraph[MovementEntity, ArtInfluenceEdge]):
>>> graph.feed_text(text)
>>> print(graph.nodes) # 流派与艺术家详情
"""
+
def __init__(
self,
llm_client: BaseChatModel,
@@ -74,7 +79,7 @@ class ArtMovementGraph(AutoGraph[MovementEntity, ArtInfluenceEdge]):
chunk_overlap: int = 256,
max_workers: int = 10,
verbose: bool = False,
- **kwargs: Any
+ **kwargs: Any,
):
"""
初始化艺术流派图谱模板。
@@ -93,7 +98,9 @@ class ArtMovementGraph(AutoGraph[MovementEntity, ArtInfluenceEdge]):
node_schema=MovementEntity,
edge_schema=ArtInfluenceEdge,
node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation.lower()})-->{x.target.strip()}",
+ edge_key_extractor=lambda x: (
+ f"{x.source.strip()}--({x.relation.lower()})-->{x.target.strip()}"
+ ),
nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),
llm_client=llm_client,
embedder=embedder,
@@ -105,8 +112,9 @@ class ArtMovementGraph(AutoGraph[MovementEntity, ArtInfluenceEdge]):
prompt=MOVEMENT_GRAPH_PROMPT,
prompt_for_node_extraction=MOVEMENT_NODE_PROMPT,
prompt_for_edge_extraction=MOVEMENT_EDGE_PROMPT,
- **kwargs
+ **kwargs,
)
+
def show(
self,
*,
@@ -117,20 +125,21 @@ class ArtMovementGraph(AutoGraph[MovementEntity, ArtInfluenceEdge]):
) -> 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: MovementEntity) -> str:
- info = f" ({ node.category })" if getattr(node, "category", None) else ""
- return f"{ node.name }{info}"
-
+ info = f" ({node.category})" if getattr(node, "category", None) else ""
+ return f"{node.name}{info}"
+
def edge_label_extractor(edge: ArtInfluenceEdge) -> str:
- return f"{ edge.source }"
-
+ return f"{edge.relation}"
+
super().show(
node_label_extractor=node_label_extractor,
edge_label_extractor=edge_label_extractor,
diff --git a/hyperextract/templates/zh/art/provenance.py b/hyperextract/templates/zh/art/provenance.py
index aa39fa5..8380239 100644
--- a/hyperextract/templates/zh/art/provenance.py
+++ b/hyperextract/templates/zh/art/provenance.py
@@ -8,16 +8,20 @@ from hyperextract.types import AutoGraph
# 1. 模式定义 (Schema)
# ==============================================================================
+
class ArtEntity(BaseModel):
"""艺术领域实体(如:作品、艺术家、博物馆、私人收藏家、拍卖行)。"""
+
name: str = Field(description="艺术品名称、人物姓名或机构名称。")
category: str = Field(
description="类别:'艺术品'、'艺术家'、'收藏家'、'机构'、'地理位置'。"
)
description: Optional[str] = Field(description="材质、创作日期或历史地位描述。")
+
class ProvenanceEdge(BaseModel):
"""艺术品的所有权或流转记录。"""
+
source: str = Field(description="原持有者或起始地点。")
target: str = Field(description="新持有者或目的地。")
transfer_type: str = Field(
@@ -25,6 +29,7 @@ class ProvenanceEdge(BaseModel):
)
specification: Optional[str] = Field(description="流转日期、成交价格或拍卖详情。")
+
# ==============================================================================
# 2. 提示词 (Prompts)
# ==============================================================================
@@ -37,24 +42,21 @@ PROVENANCE_GRAPH_PROMPT = (
"- 捕捉提到的具体日期、成交价格及传承细节。"
)
-PROVENANCE_NODE_PROMPT = (
- "提取艺术实体:识别作品、艺术家、收藏家、博物馆和拍卖行。标注作品的材质及相关人物/机构的角色。"
-)
+PROVENANCE_NODE_PROMPT = "提取艺术实体:识别作品、艺术家、收藏家、博物馆和拍卖行。标注作品的材质及相关人物/机构的角色。"
-PROVENANCE_EDGE_PROMPT = (
- "构建传承链条。将前任所有者与现任所有者联系起来,标注流转类型(如'捐赠予')。包含流转的时间段和交易详情。"
-)
+PROVENANCE_EDGE_PROMPT = "构建传承链条。将前任所有者与现任所有者联系起来,标注流转类型(如'捐赠予')。包含流转的时间段和交易详情。"
# ==============================================================================
# 3. 模板类
# ==============================================================================
+
class ProvenanceGraph(AutoGraph[ArtEntity, ProvenanceEdge]):
"""
艺术品流传图谱模板,用于追踪艺术品和文物的历史所有权。
-
+
适用于艺术品鉴定、馆藏档案管理和历史研究。
-
+
示例:
>>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
>>> llm = ChatOpenAI(model="gpt-4o")
@@ -64,6 +66,7 @@ class ProvenanceGraph(AutoGraph[ArtEntity, ProvenanceEdge]):
>>> graph.feed_text(text)
>>> print(graph.edges) # 提取的作品所有权转移记录
"""
+
def __init__(
self,
llm_client: BaseChatModel,
@@ -74,7 +77,7 @@ class ProvenanceGraph(AutoGraph[ArtEntity, ProvenanceEdge]):
chunk_overlap: int = 256,
max_workers: int = 10,
verbose: bool = False,
- **kwargs: Any
+ **kwargs: Any,
):
"""
初始化艺术品流传图谱模板。
@@ -93,7 +96,9 @@ class ProvenanceGraph(AutoGraph[ArtEntity, ProvenanceEdge]):
node_schema=ArtEntity,
edge_schema=ProvenanceEdge,
node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source.strip()}--({x.transfer_type.lower()})-->{x.target.strip()}",
+ edge_key_extractor=lambda x: (
+ f"{x.source.strip()}--({x.transfer_type.lower()})-->{x.target.strip()}"
+ ),
nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),
llm_client=llm_client,
embedder=embedder,
@@ -105,8 +110,9 @@ class ProvenanceGraph(AutoGraph[ArtEntity, ProvenanceEdge]):
prompt=PROVENANCE_GRAPH_PROMPT,
prompt_for_node_extraction=PROVENANCE_NODE_PROMPT,
prompt_for_edge_extraction=PROVENANCE_EDGE_PROMPT,
- **kwargs
+ **kwargs,
)
+
def show(
self,
*,
@@ -117,21 +123,21 @@ class ProvenanceGraph(AutoGraph[ArtEntity, ProvenanceEdge]):
) -> 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: ArtEntity) -> str:
- info = f" ({ node.category })" if getattr(node, "category", None) else ""
- return f"{ node.name }{info}"
-
+ info = f" ({node.category})" if getattr(node, "category", None) else ""
+ return f"{node.name}{info}"
+
def edge_label_extractor(edge: ProvenanceEdge) -> str:
- info = f" ({ edge.specification })" if getattr(edge, "specification", None) else ""
- return f"{ edge.source }{info}"
-
+ return f"{edge.transfer_type}"
+
super().show(
node_label_extractor=node_label_extractor,
edge_label_extractor=edge_label_extractor,
diff --git a/hyperextract/templates/zh/automotive/car_spec.py b/hyperextract/templates/zh/automotive/car_spec.py
index ed2e891..9666886 100644
--- a/hyperextract/templates/zh/automotive/car_spec.py
+++ b/hyperextract/templates/zh/automotive/car_spec.py
@@ -129,7 +129,7 @@ class CarSpecGraph(AutoGraph[CarComponent, CarSystemRelation]):
return f"{ node.name }{info}"
def edge_label_extractor(edge: CarSystemRelation) -> str:
- return f"{ edge.source }"
+ return f"{ edge.relation_type }"
super().show(
node_label_extractor=node_label_extractor,
diff --git a/hyperextract/templates/zh/automotive/maintenance.py b/hyperextract/templates/zh/automotive/maintenance.py
index b2b5155..e09e22d 100644
--- a/hyperextract/templates/zh/automotive/maintenance.py
+++ b/hyperextract/templates/zh/automotive/maintenance.py
@@ -125,7 +125,7 @@ class CarMaintenanceGraph(AutoGraph[MaintenanceItem, MaintenanceSequence]):
return f"{ node.item_name }{info}"
def edge_label_extractor(edge: MaintenanceSequence) -> str:
- return f"{ edge.source }"
+ return f"{ edge.action }"
super().show(
node_label_extractor=node_label_extractor,
diff --git a/hyperextract/templates/zh/automotive/manufacturing.py b/hyperextract/templates/zh/automotive/manufacturing.py
index 1301067..29afdb7 100644
--- a/hyperextract/templates/zh/automotive/manufacturing.py
+++ b/hyperextract/templates/zh/automotive/manufacturing.py
@@ -129,7 +129,7 @@ class AutomotiveMfgGraph(AutoGraph[ManufacturingEntity, SupplyChainRelation]):
return f"{ node.name }{info}"
def edge_label_extractor(edge: SupplyChainRelation) -> str:
- return f"{ edge.source }"
+ return f"{ edge.relation_type }"
super().show(
node_label_extractor=node_label_extractor,
diff --git a/hyperextract/templates/zh/biology/metabolic.py b/hyperextract/templates/zh/biology/metabolic.py
index 949f33c..e9a9b6e 100644
--- a/hyperextract/templates/zh/biology/metabolic.py
+++ b/hyperextract/templates/zh/biology/metabolic.py
@@ -114,11 +114,10 @@ class MetabolicHypergraph(AutoHypergraph[MetaboliteNode, MetabolicReactionHypere
top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
"""
def node_label_extractor(node: MetaboliteNode) -> str:
- info = f" ({ node.formula })" if getattr(node, "formula", None) else ""
- return f"{ node.name }{info}"
+ return f"{node.name}"
def edge_label_extractor(edge: MetabolicReactionHyperedge) -> str:
- return f"{ edge.reaction_id }"
+ return f"{edge.reaction_id}"
super().show(
node_label_extractor=node_label_extractor,
diff --git a/hyperextract/templates/zh/biology/network.py b/hyperextract/templates/zh/biology/network.py
index ce24dad..c882b5e 100644
--- a/hyperextract/templates/zh/biology/network.py
+++ b/hyperextract/templates/zh/biology/network.py
@@ -118,7 +118,7 @@ class BiologicalNetwork(AutoGraph[BioEntityNode, BioInteractionEdge]):
return f"{ node.name }{info}"
def edge_label_extractor(edge: BioInteractionEdge) -> str:
- return f"{ edge.source }"
+ return f"{ edge.interaction_type }"
super().show(
node_label_extractor=node_label_extractor,
diff --git a/hyperextract/templates/zh/biology/taxonomy.py b/hyperextract/templates/zh/biology/taxonomy.py
index e718385..85d91d7 100644
--- a/hyperextract/templates/zh/biology/taxonomy.py
+++ b/hyperextract/templates/zh/biology/taxonomy.py
@@ -112,12 +112,10 @@ class TaxonomyGraph(AutoGraph[TaxonNode, TaxonomyRelation]):
top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
"""
def node_label_extractor(node: TaxonNode) -> str:
- info = f" ({ node.description })" if getattr(node, "description", None) else ""
- return f"{ node.name }{info}"
+ return f"{node.name}"
def edge_label_extractor(edge: TaxonomyRelation) -> str:
- info = f" ({ edge.type })" if getattr(edge, "type", None) else ""
- return f"{ edge.source }{info}"
+ return f"{edge.type}"
super().show(
node_label_extractor=node_label_extractor,
diff --git a/hyperextract/templates/zh/business/equity.py b/hyperextract/templates/zh/business/equity.py
index c57d710..b55d6c8 100644
--- a/hyperextract/templates/zh/business/equity.py
+++ b/hyperextract/templates/zh/business/equity.py
@@ -136,7 +136,7 @@ class EquityStructureGraph(AutoGraph[StakeholderNode, OwnershipRelation]):
return f"{ node.name }{info}"
def edge_label_extractor(edge: OwnershipRelation) -> str:
- return f"{ edge.source }"
+ return f"{edge.control_type}"
super().show(
node_label_extractor=node_label_extractor,
diff --git a/hyperextract/templates/zh/business/strategy.py b/hyperextract/templates/zh/business/strategy.py
index 6b7ba7c..f304ec0 100644
--- a/hyperextract/templates/zh/business/strategy.py
+++ b/hyperextract/templates/zh/business/strategy.py
@@ -131,11 +131,10 @@ class StrategicChainGraph(AutoTemporalGraph[StrategicNode, StrategicPivot]):
top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
"""
def node_label_extractor(node: StrategicNode) -> str:
- return f"{ node.name }"
+ return f"{node.name}"
def edge_label_extractor(edge: StrategicPivot) -> str:
- info = f" ({ edge.timestamp })" if getattr(edge, "timestamp", None) else ""
- return f"{ edge.source }{info}"
+ return f"{edge.action}"
super().show(
node_label_extractor=node_label_extractor,
diff --git a/hyperextract/templates/zh/chemistry/molecular.py b/hyperextract/templates/zh/chemistry/molecular.py
index 882e2d4..bf67105 100644
--- a/hyperextract/templates/zh/chemistry/molecular.py
+++ b/hyperextract/templates/zh/chemistry/molecular.py
@@ -114,10 +114,10 @@ class MolecularStructureGraph(AutoSpatialGraph[AtomNode, ChemicalBond]):
top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
"""
def node_label_extractor(node: AtomNode) -> str:
- return f"{ node.name }"
+ return f"{node.name}"
def edge_label_extractor(edge: ChemicalBond) -> str:
- return f"{ edge.source }"
+ return f"{edge.bond_type}"
super().show(
node_label_extractor=node_label_extractor,
diff --git a/hyperextract/templates/zh/chemistry/protocol.py b/hyperextract/templates/zh/chemistry/protocol.py
index d508d7d..5b92258 100644
--- a/hyperextract/templates/zh/chemistry/protocol.py
+++ b/hyperextract/templates/zh/chemistry/protocol.py
@@ -116,11 +116,10 @@ class LabProtocolTemporal(AutoTemporalGraph[LabOperation, ProtocolTransition]):
top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
"""
def node_label_extractor(node: LabOperation) -> str:
- return f"{ node.op_id }"
+ return f"{node.op_id}"
def edge_label_extractor(edge: ProtocolTransition) -> str:
- info = f" ({ edge.timestamp })" if getattr(edge, "timestamp", None) else ""
- return f"{ edge.transition_id }{info}"
+ return f"{edge.transition_id}"
super().show(
node_label_extractor=node_label_extractor,
diff --git a/hyperextract/templates/zh/chemistry/reaction.py b/hyperextract/templates/zh/chemistry/reaction.py
index 4b5ac5e..ec1fe65 100644
--- a/hyperextract/templates/zh/chemistry/reaction.py
+++ b/hyperextract/templates/zh/chemistry/reaction.py
@@ -116,11 +116,11 @@ class ChemicalReactionHyper(AutoHypergraph[ChemicalEntity, ReactionEvent]):
top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
"""
def node_label_extractor(node: ChemicalEntity) -> str:
- info = f" ({ node.phase })" if getattr(node, "phase", None) else ""
- return f"{ node.name }{info}"
+ info = f" ({node.phase})" if getattr(node, "phase", None) else ""
+ return f"{node.name}{info}"
def edge_label_extractor(edge: ReactionEvent) -> str:
- return f"{ edge.reaction_id }"
+ return f"{edge.reaction_id}"
super().show(
node_label_extractor=node_label_extractor,
diff --git a/hyperextract/templates/zh/construction/project_timeline.py b/hyperextract/templates/zh/construction/project_timeline.py
index 44a3228..d07f2b1 100644
--- a/hyperextract/templates/zh/construction/project_timeline.py
+++ b/hyperextract/templates/zh/construction/project_timeline.py
@@ -144,12 +144,11 @@ class ProjectSchedulingTimeline(AutoTemporalGraph[MilestoneTaskNode, TemporalDep
top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
"""
def node_label_extractor(node: MilestoneTaskNode) -> str:
- info = f" ({ node.phase })" if getattr(node, "phase", None) else ""
- return f"{ node.task_name }{info}"
+ info = f" ({node.phase})" if getattr(node, "phase", None) else ""
+ return f"{node.task_name}{info}"
def edge_label_extractor(edge: TemporalDependency) -> str:
- info = f" ({ edge.timestamp })" if getattr(edge, "timestamp", None) else ""
- return f"{ edge.source }{info}"
+ return f"{edge.dependency_type}"
super().show(
node_label_extractor=node_label_extractor,
@@ -158,4 +157,4 @@ class ProjectSchedulingTimeline(AutoTemporalGraph[MilestoneTaskNode, TemporalDep
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,
- )
\ No newline at end of file
+ )
diff --git a/hyperextract/templates/zh/construction/resource_registry.py b/hyperextract/templates/zh/construction/resource_registry.py
index 8afb9b1..9b3d927 100644
--- a/hyperextract/templates/zh/construction/resource_registry.py
+++ b/hyperextract/templates/zh/construction/resource_registry.py
@@ -105,4 +105,4 @@ class ResourceRegistrySet(AutoSet[ConstructionResource]):
item_label_extractor=item_label_extractor,
top_k_for_search=top_k_for_search,
top_k_for_chat=top_k_for_chat,
- )
\ No newline at end of file
+ )
diff --git a/hyperextract/templates/zh/construction/site_topology.py b/hyperextract/templates/zh/construction/site_topology.py
index b9ec8e3..600edf7 100644
--- a/hyperextract/templates/zh/construction/site_topology.py
+++ b/hyperextract/templates/zh/construction/site_topology.py
@@ -142,10 +142,10 @@ class SiteTopologyGraph(AutoSpatialGraph[PhysicalElementNode, SpatialRelation]):
top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
"""
def node_label_extractor(node: PhysicalElementNode) -> str:
- return f"{ node.name }"
+ return f"{node.name}"
def edge_label_extractor(edge: SpatialRelation) -> str:
- return f"{ edge.source }"
+ return f"{edge.relation_type}"
super().show(
node_label_extractor=node_label_extractor,
@@ -154,4 +154,4 @@ class SiteTopologyGraph(AutoSpatialGraph[PhysicalElementNode, SpatialRelation]):
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,
- )
\ No newline at end of file
+ )
diff --git a/hyperextract/templates/zh/cybersecurity/intrusion_kill_chain.py b/hyperextract/templates/zh/cybersecurity/intrusion_kill_chain.py
index 7cae783..5f2c5db 100644
--- a/hyperextract/templates/zh/cybersecurity/intrusion_kill_chain.py
+++ b/hyperextract/templates/zh/cybersecurity/intrusion_kill_chain.py
@@ -160,11 +160,10 @@ class IntrusionKillChainGraph(AutoGraph[AttackStageNode, KillChainLink]):
top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
"""
def node_label_extractor(node: AttackStageNode) -> str:
- info = f" ({ node.timestamp })" if getattr(node, "timestamp", None) else ""
- return f"{ node.stage_name }{info}"
+ return f"{node.stage_name}"
def edge_label_extractor(edge: KillChainLink) -> str:
- return f"{ edge.source }"
+ return f"{edge.causality}"
super().show(
node_label_extractor=node_label_extractor,
@@ -173,4 +172,4 @@ class IntrusionKillChainGraph(AutoGraph[AttackStageNode, KillChainLink]):
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,
- )
\ No newline at end of file
+ )
diff --git a/hyperextract/templates/zh/cybersecurity/threat_intelligence_nexus.py b/hyperextract/templates/zh/cybersecurity/threat_intelligence_nexus.py
index cbcf124..f0f7c38 100644
--- a/hyperextract/templates/zh/cybersecurity/threat_intelligence_nexus.py
+++ b/hyperextract/templates/zh/cybersecurity/threat_intelligence_nexus.py
@@ -161,10 +161,10 @@ class ThreatIntelligenceNexusHypergraph(
top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
"""
def node_label_extractor(node: ThreatActorNode) -> str:
- return f"{ node.actor_name }"
+ return f"{node.actor_name}"
def edge_label_extractor(edge: IntelligenceNexus) -> str:
- return f"{ edge.participants }"
+ return f"{edge.campaign_name}"
super().show(
node_label_extractor=node_label_extractor,
@@ -173,4 +173,4 @@ class ThreatIntelligenceNexusHypergraph(
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,
- )
\ No newline at end of file
+ )
diff --git a/hyperextract/templates/zh/cybersecurity/vulnerability_catalog.py b/hyperextract/templates/zh/cybersecurity/vulnerability_catalog.py
index ff42aaa..1c93e69 100644
--- a/hyperextract/templates/zh/cybersecurity/vulnerability_catalog.py
+++ b/hyperextract/templates/zh/cybersecurity/vulnerability_catalog.py
@@ -111,10 +111,10 @@ class VulnerabilityUnifiedCatalog(AutoSet[VulnerabilityEntry]):
top_k_for_chat (int): Number of items to retrieve for chat context. Default 3.
"""
def item_label_extractor(item: VulnerabilityEntry) -> str:
- return f"{ item.title }"
+ return f"{item.title}"
super().show(
item_label_extractor=item_label_extractor,
top_k_for_search=top_k_for_search,
top_k_for_chat=top_k_for_chat,
- )
\ No newline at end of file
+ )
diff --git a/hyperextract/templates/zh/education/academic_lexicon.py b/hyperextract/templates/zh/education/academic_lexicon.py
index 12f0313..1bb0795 100644
--- a/hyperextract/templates/zh/education/academic_lexicon.py
+++ b/hyperextract/templates/zh/education/academic_lexicon.py
@@ -109,7 +109,7 @@ class AcademicLexiconSet(AutoSet[AcademicTerm]):
top_k_for_chat (int): Number of items to retrieve for chat context. Default 3.
"""
def item_label_extractor(item: AcademicTerm) -> str:
- return f"{ item.term }"
+ return f"{item.term}"
super().show(
item_label_extractor=item_label_extractor,
diff --git a/hyperextract/templates/zh/education/interdisciplinary_nexus.py b/hyperextract/templates/zh/education/interdisciplinary_nexus.py
index 85f62cf..2c70524 100644
--- a/hyperextract/templates/zh/education/interdisciplinary_nexus.py
+++ b/hyperextract/templates/zh/education/interdisciplinary_nexus.py
@@ -134,10 +134,10 @@ class InterdisciplinaryNexusHypergraph(AutoHypergraph[ConceptNode, Interdiscipli
top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
"""
def node_label_extractor(node: ConceptNode) -> str:
- return f"{ node.name }"
+ return f"{node.name}"
def edge_label_extractor(edge: InterdisciplinaryEdge) -> str:
- return f"{ edge.participants }"
+ return f"{edge.unifying_theme}"
super().show(
node_label_extractor=node_label_extractor,
diff --git a/hyperextract/templates/zh/education/prerequisite_map.py b/hyperextract/templates/zh/education/prerequisite_map.py
index bbd0fe5..7b1eab0 100644
--- a/hyperextract/templates/zh/education/prerequisite_map.py
+++ b/hyperextract/templates/zh/education/prerequisite_map.py
@@ -148,11 +148,10 @@ class PrerequisiteMapGraph(AutoGraph[KnowledgePointNode, PrerequisiteRelation]):
top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
"""
def node_label_extractor(node: KnowledgePointNode) -> str:
- info = f" ({ node.description })" if getattr(node, "description", None) else ""
- return f"{ node.name }{info}"
+ return f"{node.name}"
def edge_label_extractor(edge: PrerequisiteRelation) -> str:
- return f"{ edge.source }"
+ return f"{edge.dependency_type}"
super().show(
node_label_extractor=node_label_extractor,
diff --git a/hyperextract/templates/zh/general/concept_map.py b/hyperextract/templates/zh/general/concept_map.py
index 6bdbcd0..960bbc7 100644
--- a/hyperextract/templates/zh/general/concept_map.py
+++ b/hyperextract/templates/zh/general/concept_map.py
@@ -129,10 +129,10 @@ class ConceptMap(AutoGraph[Concept, ConceptRelation]):
top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
"""
def node_label_extractor(node: Concept) -> str:
- return f"{ node.term }"
+ return f"{node.term}"
def edge_label_extractor(edge: ConceptRelation) -> str:
- return f"{ edge.source }"
+ return f"{edge.relation_type}"
super().show(
node_label_extractor=node_label_extractor,
diff --git a/hyperextract/templates/zh/general/knowledge_graph.py b/hyperextract/templates/zh/general/knowledge_graph.py
index 8971779..0bde8f4 100644
--- a/hyperextract/templates/zh/general/knowledge_graph.py
+++ b/hyperextract/templates/zh/general/knowledge_graph.py
@@ -132,11 +132,11 @@ class KnowledgeGraph(AutoGraph[Entity, Relation]):
top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
"""
def node_label_extractor(node: Entity) -> str:
- info = f" ({ node.category })" if getattr(node, "category", None) else ""
- return f"{ node.name }{info}"
+ info = f" ({node.category})" if getattr(node, "category", None) else ""
+ return f"{node.name}{info}"
def edge_label_extractor(edge: Relation) -> str:
- return f"{ edge.source }"
+ return f"{edge.relation}"
super().show(
node_label_extractor=node_label_extractor,
diff --git a/hyperextract/templates/zh/general/logic_graph.py b/hyperextract/templates/zh/general/logic_graph.py
index d507aae..2d4f583 100644
--- a/hyperextract/templates/zh/general/logic_graph.py
+++ b/hyperextract/templates/zh/general/logic_graph.py
@@ -128,10 +128,10 @@ class LogicGraph(AutoGraph[LogicNode, LogicRelation]):
top_k_edges_for_chat (int): Number of edges to retrieve for chat context. Default 3.
"""
def node_label_extractor(node: LogicNode) -> str:
- return f"{ node.statement }"
+ return f"{node.statement}"
def edge_label_extractor(edge: LogicRelation) -> str:
- return f"{ edge.source }"
+ return f"{edge.inference}"
super().show(
node_label_extractor=node_label_extractor,