Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.
Refactor food and game schemas for improved clarity and consistency
yifanfeng9723f9c44710ae
diff --git a/hyperextract/templates/en/finance/market_sentiment.py b/hyperextract/templates/en/finance/market_sentiment.pyindex 3a96e6a..a0912d9 100644--- a/hyperextract/templates/en/finance/market_sentiment.py+++ b/hyperextract/templates/en/finance/market_sentiment.py@@ -25,20 +25,6 @@ class MarketDriver(BaseModel):)-class MarketTarget(BaseModel):- """- A trading asset or financial metric that is influenced by market drivers.- """-- ticker: str = Field(description="Ticker symbol (e.g., 'AAPL', 'AI Index').")- asset_type: str = Field(- description="Type: 'Equity', 'Index', 'Bond', 'Commodity', 'Currency'."- )- metric: Optional[str] = Field(- None, description="Specific metric if applicable (e.g., 'EPS', 'P/E Ratio')."- )--class AnalystInfluence(BaseModel):"""Represents how a market driver influences an asset's outlook.diff --git a/hyperextract/templates/en/finance/supply_chain.py b/hyperextract/templates/en/finance/supply_chain.pyindex 76b014c..5304dc5 100644--- a/hyperextract/templates/en/finance/supply_chain.py+++ b/hyperextract/templates/en/finance/supply_chain.py@@ -18,11 +18,8 @@ class SupplyEntity(BaseModel):entity_type: str = Field(description="Type: 'Customer', 'Supplier', 'Strategic Partner', 'Distributor', 'Our Company'.")- jurisdiction: Optional[str] = Field(- None, description="Geographic location or headquarters region."- )- notes: Optional[str] = Field(- None, description="Additional details (e.g., 'Certified Organic', 'ISO Compliant')."+ details: Optional[str] = Field(+ None, description="Jurisdiction, certifications, and compliance notes.")@@ -33,24 +30,15 @@ class SupplyTransaction(BaseModel):source: str = Field(description="The supplier or upstream entity.")target: str = Field(description="The buyer or downstream entity.")- transaction_type: str = Field(+ relationship_type: str = Field(description="Type: 'Supply', 'Purchase', 'Distribution', 'Strategic Partnership'.")product_service: str = Field(description="What is being supplied or transacted (e.g., 'Lithium Chips', 'Logistics Services').")- dependency: str = Field(- description="Dependency level: 'Critical', 'High', 'Moderate', 'Low'."- )- volume_percentage: Optional[str] = Field(- None, description="Percentage of total supply/revenue if disclosed (e.g., '80%')."- )- geographic_origin: Optional[str] = Field(- None, description="Source region or geopolitical consideration."- )- risks: Optional[str] = Field(+ risk_assessment: Optional[str] = Field(None,- description="Any disclosed risks or vulnerabilities (e.g., 'Single-source supplier', 'Tariff exposure').",+ description="Combined assessment of dependency level, volume percentage, geographic origins, and risks.",)@@ -59,32 +47,26 @@ class SupplyTransaction(BaseModel):# ==============================================================================_PROMPT = (- "You are a supply chain analyst. Extract supply chain entities and their relationships "- "from corporate filings and supply chain audits.\n\n"+ "You are a supply chain analyst. Extract supply chain entities and relationships.\n\n""Rules:\n"- "- Identify key suppliers, customers, and strategic partners mentioned.\n"- "- Extract transaction types and product/service descriptions.\n"- "- Assess dependency levels based on disclosed volume or importance.\n"- "- Document any geopolitical or regulatory risks."+ "- Identify suppliers, customers, and partners.\n"+ "- Extract transaction types and products.\n"+ "- Summarize dependency, volume, and geopolitical risks in **risk_assessment**.")_NODE_PROMPT = (- "You are a supply chain analyst. Extract all supply chain participants (Nodes) from the text.\n\n"- "Extraction Rules:\n"- "- Identify companies, suppliers, customers, and distribution partners.\n"- "- Classify each entity's role in the supply chain.\n"- "- Note jurisdiction and any certifications or compliance notes.\n"- "- DO NOT establish transaction relationships at this stage."+ "You are a supply chain analyst. Extract supply chain participants/entities (Nodes).\n\n"+ "Rules:\n"+ "- Identify companies and partners.\n"+ "- Classify entity roles.\n"+ "- Capture location and certifications in **details**.")_EDGE_PROMPT = (- "You are a supply chain analyst. Given the list of supply chain entities, extract the "- "transaction relationships (Edges).\n\n"- "Extraction Rules:\n"- "- Connect supplier to buyer with the specific product/service being transacted.\n"- "- Assess dependency level based on disclosed volume percentages or importance keywords.\n"- "- Extract geographic origin and any disclosed risks (tariffs, single-source).\n"- "- Only connect entities that exist in the provided list."+ "You are a supply chain analyst. Extract transaction relationships (Edges).\n\n"+ "Rules:\n"+ "- Connect entities via product/service flows.\n"+ "- **risk_assessment**: Combine dependency level, volume info, and risks (tariffs, single-source).")# ==============================================================================@@ -178,8 +160,8 @@ class SupplyChainGraph(AutoGraph[SupplyEntity, SupplyTransaction]):return f"{node.name} ({node.entity_type})"def edge_label_extractor(edge: SupplyTransaction) -> str:- vol = f" {edge.volume_percentage}" if edge.volume_percentage else ""- return f"{edge.product_service}{vol} [{edge.dependency}]"+ risk = f" [{edge.risk_assessment}]" if edge.risk_assessment else ""+ return f"{edge.product_service}{risk}"super().show(node_label_extractor=node_label_extractor,diff --git a/hyperextract/templates/en/food/culinary_dish.py b/hyperextract/templates/en/food/culinary_dish.pyindex 7509e10..0d9d8f1 100644--- a/hyperextract/templates/en/food/culinary_dish.py+++ b/hyperextract/templates/en/food/culinary_dish.py@@ -1,4 +1,4 @@-from typing import Optional, List, Any+from typing import Optional, Anyfrom pydantic import BaseModel, Fieldfrom langchain_core.language_models.chat_models import BaseChatModelfrom langchain_core.embeddings import Embeddings@@ -15,36 +15,21 @@ class CulinaryDish(BaseModel):"""name: str = Field(- description="Standardized dish name (e.g., 'Kung Pao Chicken', 'Mapo Tofu', 'Risotto')."+ description="Standardized dish name (e.g., 'Kung Pao Chicken').")- cuisine: str = Field(- description="Cuisine origin (e.g., 'Sichuan', 'Italian', 'French', 'Indian', 'Thai')."+ origin: Optional[str] = Field(+ None, description="Cuisine type, geographic origin, and seasonal relevance.")- region: Optional[str] = Field(- None, description="Specific geographic region or city of origin if applicable."+ ingredients: Optional[str] = Field(+ None, description="Core ingredients, proteins, and key spices.")- primary_ingredients: List[str] = Field(- default_factory=list, description="Core ingredients defining the dish (e.g., ['Chicken', 'Peanuts', 'Dried Chilies'])."- )- protein_type: Optional[str] = Field(+ profile: Optional[str] = Field(None,- description="Main protein: 'Chicken', 'Beef', 'Pork', 'Seafood', 'Plant-based', 'No protein'.",- )- flavor_profile: str = Field(- description="Predominant taste characteristics (e.g., 'Spicy & Numbing', 'Sweet & Sour', 'Umami-rich')."- )- cooking_method: Optional[str] = Field(- None, description="Primary cooking technique (e.g., 'Stir-fry', 'Braised', 'Steamed', 'Grilled')."- )- dietary_attributes: List[str] = Field(- default_factory=list,- description="Dietary tags (e.g., 'Contains Nuts', 'Gluten-Free', 'Vegetarian', 'Dairy-Free').",- )- serving_suggestion: Optional[str] = Field(- None, description="Typical serving context (e.g., 'Appetizer', 'Main course', 'Side dish')."+ description="Flavor characteristics, texture notes, and cooking techniques.")- seasonal_note: Optional[str] = Field(- None, description="Seasonal availability or association (e.g., 'Summer dish', 'Winter comfort food')."+ description: Optional[str] = Field(+ None,+ description="General description including dietary info, serving suggestions, and history.",)@@ -53,15 +38,13 @@ class CulinaryDish(BaseModel):# ==============================================================================_PROMPT = (- "You are a culinary expert and food historian. Your task is to extract and standardize "- "representative culinary dishes from menus, cookbooks, recipe collections, and food reviews.\n\n"+ "You are a culinary expert. Extract representative culinary dishes from text.\n\n""Extraction Rules:\n"- "- Standardize dish names to their most recognized form (e.g., 'Kung Pao Chicken' vs. 'Gong Bao Ji Ding').\n"- "- Identify the cuisine origin and specific geographic region.\n"- "- Extract core ingredients that define the dish.\n"- "- Capture the predominant flavor profile using precise descriptors.\n"- "- Note dietary attributes and allergenic ingredients.\n"- "- Deduplicate: If the same dish appears with slight variations, merge into one entry.\n"+ "- Standardize dish names.\n"+ "- **origin**: Combine cuisine, region, and seasonality.\n"+ "- **ingredients**: List main proteins and vegetables/spices.\n"+ "- **profile**: Describe flavor, texture, and method (e.g. 'Spicy, Stir-fried').\n"+ "- **description**: Capture dietary notes, serving context, and any cultural backstory.\n")# ==============================================================================@@ -71,23 +54,9 @@ _PROMPT = (class CulinaryDishSet(AutoSet[CulinaryDish]):"""- Applicable to: Restaurant Menus, Cookbooks, Food Encyclopedias, Recipe Websites,- Food Blogs, Culinary Magazine Articles, Restaurant Review Databases, Dining Guides.+ Applicable to: Restaurant Menus, Cookbooks, Food Encyclopedias.Template for building a standardized culinary foundation through **key-based information accumulation**.- Automatically merges information about the same dish (identified by standardized dish name) from- multiple sources into a single enriched entry, capturing ingredients, preparation, origin, and characteristics.-- Example Usage:- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings- >>> llm = ChatOpenAI(model="gpt-4o")- >>> embedder = OpenAIEmbeddings()- >>> dishes = CulinaryDishSet(llm_client=llm, embedder=embedder)- >>> # Source 1: Extract basic info (name, cuisine, region)- >>> dishes.feed_text("Kung Pao Chicken is a famous dish from Sichuan province with peanuts and dried chilies.")- >>> # Source 2: Extract complementary details (ingredients, flavor, technique)- >>> dishes.feed_text("Kung Pao Chicken features rapid stir-frying of chicken with roasted peanuts, creating a sweet and spicy taste.")- >>> dishes.show() # Shows merged 'Kung Pao Chicken' entry with accumulated details from both sources"""def __init__(@@ -101,18 +70,6 @@ class CulinaryDishSet(AutoSet[CulinaryDish]):verbose: bool = False,**kwargs: Any,):- """- Initialize the Culinary Dish Set template.-- Args:- llm_client (BaseChatModel): The LLM for dish extraction and standardization.- embedder (Embeddings): Embedding model for semantic retrieval and knowledge graph visualization.- chunk_size (int): Size of text chunks for processing.- chunk_overlap (int): Overlap between chunks.- max_workers (int): Parallel processing workers.- verbose (bool): Enable progress logging.- **kwargs: Additional parameters for AutoSet.- """super().__init__(item_schema=CulinaryDish,key_extractor=lambda x: x.name.strip().lower(),@@ -132,16 +89,11 @@ class CulinaryDishSet(AutoSet[CulinaryDish]):top_k_for_search: int = 3,top_k_for_chat: int = 3,) -> None:- """- Display the culinary dish collection using OntoSight.-- Args:- top_k_for_search (int): Number of dishes to retrieve for search context. Default 3.- top_k_for_chat (int): Number of dishes to retrieve for chat context. Default 3.- """-- def item_label_extractor(dish: CulinaryDish) -> str:- return f"{dish.name} ({dish.cuisine})"+ def item_label_extractor(item: CulinaryDish) -> str:+ parts = [item.name]+ if item.origin:+ parts.append(f"({item.origin})")+ return " ".join(parts)super().show(item_label_extractor=item_label_extractor,diff --git a/hyperextract/templates/en/food/flavor_pairing.py b/hyperextract/templates/en/food/flavor_pairing.pydeleted file mode 100644index ceba4ed..0000000--- a/hyperextract/templates/en/food/flavor_pairing.py+++ /dev/null@@ -1,190 +0,0 @@-from typing import Optional, Any-from pydantic import BaseModel, Field-from langchain_core.language_models.chat_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoGraph--# ==============================================================================-# 1. Schema Definitions-# ==============================================================================---class FlavorComponent(BaseModel):- """- A food ingredient or flavor compound involved in pairing relationships.- """-- name: str = Field(description="Name of food/ingredient/compound (e.g., 'Strawberry', 'Furaneol', 'Vanilla').")- component_type: str = Field(- description="Type: 'Ingredient', 'Chemical Compound', 'Flavor Note', 'Aroma'."- )- description: Optional[str] = Field(- None, description="Additional details (e.g., chemical formula, source, sensory profile)."- )---class FlavorRelationship(BaseModel):- """- A pairing or flavor relationship between two components.- """-- source: str = Field(description="First component.")- target: str = Field(description="Second component.")- relationship_type: str = Field(- description="Type: 'Contains', 'Pairs_Well', 'Conflicts', 'Complements', 'Shared_Flavor'."- )- pairing_mechanism: str = Field(- description="Why they pair or connect (e.g., 'Shared sulfur compounds', 'Complementary sweetness', 'Similar volatile compounds')."- )- pairing_quality: Optional[str] = Field(- None, description="Quality assessment (e.g., 'Strong', 'Moderate', 'Subtle', 'Surprising')."- )- culinary_context: Optional[str] = Field(- None,- description="In what culinary context they pair well (e.g., 'Sweet desserts', 'Savory broths', 'Asian cuisine').",- )- supporting_evidence: Optional[str] = Field(- None,- description="Scientific evidence or reference (e.g., 'Clinical taste panel study', 'Food Chemistry Journal').",- )---# ==============================================================================-# 2. Prompts-# ==============================================================================--_PROMPT = (- "You are a food chemist and flavor scientist. Extract flavor components and their pairing "- "relationships from food science literature and sensory evaluation reports.\n\n"- "Rules:\n"- "- Identify food ingredients, volatile compounds, and flavor molecules mentioned.\n"- "- Extract flavor pairing relationships and the chemistry/science behind them.\n"- "- Distinguish between complementary, conflicting, and surprising pairings.\n"- "- Document the evidence basis (taste panel, chemical analysis, etc.)."-)--_NODE_PROMPT = (- "You are a food chemist. Extract all flavor components and compounds (Nodes) from the text.\n\n"- "Extraction Rules:\n"- "- Identify food ingredients (Strawberry, Tomato) and flavor compounds (Furaneol, Vanillin).\n"- "- Classify each as Ingredient, Chemical Compound, or Flavor Note.\n"- "- Include sensory or chemical descriptors where provided.\n"- "- DO NOT establish pairings or relationships at this stage."-)--_EDGE_PROMPT = (- "You are a food chemist. Given the list of flavor components, extract their pairing and "- "relationship connections (Edges).\n\n"- "Extraction Rules:\n"- "- Connect components that share flavor molecules or pair well culinarily.\n"- "- Extract the scientific mechanism (shared compounds, complementary tastes).\n"- "- Assess pairing quality and context (when/why they work together).\n"- "- Include supporting evidence from research or sensory studies.\n"- "- Only connect components that exist in the provided list."-)--# ==============================================================================-# 3. Template Class-# ==============================================================================---class FlavorPairingGraph(AutoGraph[FlavorComponent, FlavorRelationship]):- """- Applicable to: Food Chemistry Research Papers (journals like Food Chemistry, LWT),- Sensory Evaluation Reports, Recipe Development Studies, Flavor Science Books,- Culinary Science Databases, Molecular Gastronomy Guides.-- Template for extracting and mapping flavor and culinary science knowledge. Enables- understanding of ingredients' chemical similarities, predicting novel flavor combinations,- and supporting data-driven recipe development.-- Example Usage:- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings- >>> llm = ChatOpenAI(model="gpt-4o")- >>> embedder = OpenAIEmbeddings()- >>> flavors = FlavorPairingGraph(llm_client=llm, embedder=embedder)- >>> paper = "Strawberries and tomatoes both contain furaneol, leading to surprising pairing potential..."- >>> flavors.feed_text(paper)-- >>> flavors.show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- extraction_mode: str = "one_stage",- chunk_size: int = 2048,- chunk_overlap: int = 256,- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- Initialize the Flavor Pairing Graph template.-- Args:- llm_client (BaseChatModel): The LLM for component and relationship extraction.- embedder (Embeddings): Embedding model for deduplication.- extraction_mode (str): "one_stage" or "two_stage".- chunk_size (int): Max characters per chunk.- chunk_overlap (int): Overlap between chunks.- max_workers (int): Parallel processing workers.- verbose (bool): Enable progress logging.- **kwargs: Additional arguments for AutoGraph.- """- super().__init__(- node_schema=FlavorComponent,- edge_schema=FlavorRelationship,- node_key_extractor=lambda x: x.name.strip().lower(),- edge_key_extractor=lambda x: (- f"{x.source.strip()}--({x.relationship_type})-->{x.target.strip()}"- ),- nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),- llm_client=llm_client,- embedder=embedder,- extraction_mode=extraction_mode,- chunk_size=chunk_size,- chunk_overlap=chunk_overlap,- max_workers=max_workers,- verbose=verbose,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- **kwargs,- )-- def show(- self,- *,- top_k_nodes_for_search: int = 3,- top_k_edges_for_search: int = 3,- top_k_nodes_for_chat: int = 3,- top_k_edges_for_chat: int = 3,- ) -> None:- """- Visualize the flavor pairing graph using OntoSight.-- Args:- top_k_nodes_for_search (int): Number of components to retrieve. Default 3.- top_k_edges_for_search (int): Number of relationships to retrieve. Default 3.- top_k_nodes_for_chat (int): Components for chat context. Default 3.- top_k_edges_for_chat (int): Relationships for chat context. Default 3.- """-- def node_label_extractor(node: FlavorComponent) -> str:- return f"{node.name} ({node.component_type})"-- def edge_label_extractor(edge: FlavorRelationship) -> str:- quality = f" ({edge.pairing_quality})" if edge.pairing_quality else ""- return f"{edge.relationship_type}{quality}"-- super().show(- node_label_extractor=node_label_extractor,- edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_nodes_for_search,- top_k_edges_for_search=top_k_edges_for_search,- top_k_nodes_for_chat=top_k_nodes_for_chat,- top_k_edges_for_chat=top_k_edges_for_chat,- )diff --git a/hyperextract/templates/en/food/haccp_safety.py b/hyperextract/templates/en/food/haccp_safety.pyindex f193203..5b2df4e 100644--- a/hyperextract/templates/en/food/haccp_safety.py+++ b/hyperextract/templates/en/food/haccp_safety.py@@ -49,19 +49,13 @@ class ControlMeasure(BaseModel):source: str = Field(description="The biological hazard name.")target: str = Field(description="The CCP name.")critical_limit: str = Field(- description="Critical limit defining the boundary between safe/unsafe (e.g., '>=72°C for >=15 seconds', 'pH < 4.6')."+ description="Boundary between safe/unsafe (e.g. '>72C').")- monitoring_procedure: str = Field(- description="How the CCP is monitored (e.g., 'Thermometer reading every batch', 'pH meter daily')."+ monitoring: str = Field(+ description="Procedure and frequency of monitoring.")- monitoring_frequency: str = Field(- description="How often monitoring occurs (e.g., 'Every 2 hours', 'Per batch', 'Daily')."- )- corrective_action: str = Field(- description="Action if critical limit is not met (e.g., 'Discard product', 'Reprocess', 'Alert QA')."- )- verification: Optional[str] = Field(- None, description="Verification method to confirm effectiveness (e.g., 'Culture tests monthly')."+ details: Optional[str] = Field(+ None, description="Corrective actions and verification methods.")@@ -70,34 +64,29 @@ class ControlMeasure(BaseModel):# ==============================================================================_PROMPT = (- "You are a food safety specialist trained in HACCP principles. Extract hazards, critical control points, "- "and their control measures from HACCP plans and food safety documentation.\n\n"+ "You are a food safety specialist. Extract hazards, CCPs, and controls.\n\n""Rules:\n"- "- Identify biological hazards relevant to the product and process.\n"- "- Identify CCPs where hazards can be eliminated or controlled.\n"- "- Extract critical limits, monitoring procedures, and corrective actions.\n"- "- Ensure each CCP is linked to specific hazard(s) it controls."+ "- Identify hazards and CCPs.\n"+ "- Link hazards to CCPs via control measures.\n"+ "- Extract **critical_limit** and **monitoring** details.\n"+ "- Capture corrective actions in **details**.")_NODE_PROMPT = (- "You are a food safety specialist. Extract all hazards and CCPs (Nodes) from the HACCP documentation.\n\n"- "Extraction Rules:\n"- "- Identify all biological hazards mentioned (pathogens, allergens if applicable).\n"- "- Identify all CCPs (cooking, cooling, metal detection stages).\n"- "- Classify each hazard by type (Bacterial, Viral, Fungal, Parasitic).\n"- "- Classify each CCP by production stage.\n"- "- DO NOT establish control relationships at this stage."+ "You are a food safety specialist. Extract hazards and CCPs (Nodes).\n\n"+ "Rules:\n"+ "- Identify biological hazards and classify type.\n"+ "- Identify CCPs and production stage.\n")_EDGE_PROMPT = (- "You are a food safety specialist. Given the list of hazards and CCPs, extract the control relationships (Edges).\n\n"- "Extraction Rules:\n"- "- Connect each hazard to the CCP(s) that control it.\n"- "- Extract critical limits with precise thresholds and units.\n"- "- Extract monitoring procedures and frequency from the HACCP document.\n"- "- Extract corrective actions to be taken if limits are violated.\n"- "- Include verification methods when documented.\n"- "- Only create edges between hazards and CCPs that exist in the provided lists."+ "You are a food safety specialist. Extract control measures (Edges).\n\n"+ "Rules:\n"+ "- Connect hazard to CCP.\n"+ "- **critical_limit**: Safety boundary.\n"+ "- **monitoring**: How and when to check.\n"+ "- **details**: Corrective actions and verification.\n"+ "- Only connect existing nodes.")# ==============================================================================diff --git a/hyperextract/templates/en/food/recipe_process.py b/hyperextract/templates/en/food/recipe_process.pyindex 7d1499e..61b128f 100644--- a/hyperextract/templates/en/food/recipe_process.py+++ b/hyperextract/templates/en/food/recipe_process.py@@ -36,21 +36,8 @@ class ProcessingStep(BaseModel):action: str = Field(description="The processing action (e.g., 'Blend', 'Heat', 'Cool', 'Rest', 'Knead', 'Ferment').")- duration: str = Field(- description="How long the action takes (e.g., '10 mins', '2 hours', 'Overnight', '15s')."- )- temperature: Optional[str] = Field(- None, description="Temperature setting if applicable (e.g., '175°C', 'Room temperature', '4°C')."- )- equipment: Optional[str] = Field(- None, description="Equipment used (e.g., 'Stand Mixer', 'Oven', 'Water Bath', 'Thermometer')."- )- parameters: Optional[str] = Field(- None,- description="Additional parameters (speed, pressure, etc., e.g., 'Medium speed', '200 PSI').",- )- notes: Optional[str] = Field(- None, description="Special instructions or observations (e.g., 'A light cream should form')."+ process_conditions: Optional[str] = Field(+ None, description="Combine duration, temp, equipment, and parameters.")@@ -59,35 +46,29 @@ class ProcessingStep(BaseModel):# ==============================================================================_PROMPT = (- "You are a professional chef and food scientist. Extract the step-by-step recipe or industrial "- "food production process from formulation sheets and SOPs.\n\n"+ "You are a food scientist. Extract recipe process steps.\n\n""Rules:\n"- "- Identify each distinct processing action and transformation.\n"- "- Extract ingredient states before and after each step.\n"- "- Capture timing, temperature, and equipment precisely.\n"- "- Maintain strict sequence order (Step 1 -> Step 2, etc.).\n"- "- Include any notes on texture, appearance, or sensory cues."+ "- Identify processing actions and transformations.\n"+ "- Extract ingredient states pre/post step.\n"+ "- Capture **process_conditions** (time, temp, equipment).\n"+ "- Maintain sequence order.")_NODE_PROMPT = (- "You are a professional chef and food scientist. Extract all ingredient states (Nodes) from the recipe.\n\n"- "Extraction Rules:\n"- "- Identify distinct states/stages in the recipe (raw, mixed, heated, cooled, rested).\n"- "- Describe what ingredients are present at each state.\n"- "- Note the physical form (liquid, solid, dough, etc.).\n"- "- Maintain exact names and descriptions from the source.\n"- "- DO NOT describe the actions or transitions between states at this stage."+ "You are a food scientist. Extract ingredient states (Nodes).\n\n"+ "Rules:\n"+ "- Identify distinct states (raw, mixed, cooked).\n"+ "- List ingredients present.\n"+ "- Note physical form.")_EDGE_PROMPT = (- "You are a professional chef. Given the list of ingredient states, extract the processing "- "steps that transform one state into another (Edges).\n\n"- "Extraction Rules:\n"- "- Connect each source state to its target state with the specific action.\n"- "- Extract duration, temperature, and equipment for each step.\n"- "- Extract any special parameters (speed, pressure) or sensory cues.\n"- "- Maintain strict step ordering (Step 1, Step 2, etc.).\n"- "- Only connect states that exist in the provided list."+ "You are a food scientist. Extract processing steps (Edges).\n\n"+ "Rules:\n"+ "- Connect source to target state via action.\n"+ "- **process_conditions**: Time, temperature, equipment.\n"+ "- Maintain exact step order.\n"+ "- Only connect existing nodes.")# ==============================================================================@@ -184,8 +165,8 @@ class RecipeProcessGraph(AutoTemporalGraph[IngredientState, ProcessingStep]):return f"{node.name} ({node.physical_state if node.physical_state else 'Unknown'})"def edge_label_extractor(edge: ProcessingStep) -> str:- temp = f" {edge.temperature}" if edge.temperature else ""- return f"{edge.action} ({edge.duration}){temp}"+ temp = f" ({edge.process_conditions})" if edge.process_conditions else ""+ return f"{edge.action}{temp}"super().show(node_label_extractor=node_label_extractor,diff --git a/hyperextract/templates/en/game/game_character_compendium.py b/hyperextract/templates/en/game/game_character_compendium.pyindex 9f5efdc..5801424 100644--- a/hyperextract/templates/en/game/game_character_compendium.py+++ b/hyperextract/templates/en/game/game_character_compendium.py@@ -21,34 +21,19 @@ class GameCharacterSchema(BaseModel):character_name: str = Field(..., description="The standard name of the character, e.g., 'Yasuo'")- character_class: str = Field(+ class_role: str = Field(...,- description="Character class/role: 'Swordsman', 'Mage', 'Archer', 'Tank', 'Support', etc.",+ description="Character class/role (e.g., 'Mage', 'Tank') and playstyle summary.",)- background_story: Optional[str] = Field(- None, description="Character lore, origin story, and background"+ affiliation: Optional[str] = Field(+ None, description="Faction, team, or origin region.")- signature_abilities: Optional[str] = Field(+ abilities: Optional[str] = Field(None,- description="List of main/signature skills and abilities this character possesses",+ description="Signature skills, ultimate ability, and key base stats.",)- base_stats: Optional[str] = Field(- None,- description="Base attributes: HP, mana, attack, defense, speed, etc. with numerical values",- )- recommended_playstyle: Optional[str] = Field(- None,- description="How to effectively play this character: positioning, combos, item builds, etc.",- )- origin_region: Optional[str] = Field(- None, description="The region/world area this character comes from"- )- faction_affiliation: Optional[str] = Field(- None, description="Which faction, team, or organization this character belongs to"- )- voice_actor: Optional[str] = Field(- None,- description="Official voice actor name(s) for this character in different languages",+ lore: Optional[str] = Field(+ None, description="Background story, personality, and voice actor info.")diff --git a/hyperextract/templates/en/game/game_item_compendium.py b/hyperextract/templates/en/game/game_item_compendium.pyindex c40869c..7d7dc6a 100644--- a/hyperextract/templates/en/game/game_item_compendium.py+++ b/hyperextract/templates/en/game/game_item_compendium.py@@ -24,28 +24,18 @@ class GameItemSchema(BaseModel):"""Schema for individual game items in the compendium."""item_name: str = Field(- ..., description="The standard English or localized name of the item"+ ..., description="The standard name of the item")category: str = Field(...,- description="Item classification: 'Weapon', 'Armor', 'Consumable', 'Accessory', 'Material', etc.",+ description="Item classification (Weapon, Potion, Material, etc.)",)- stat_bonuses: Optional[str] = Field(+ item_data: Optional[str] = Field(None,- description="Attribute bonuses provided by this item, e.g., '+50 attack, +100 HP'",+ description="Stat bonuses, special effects, and crafting recipe information.",)- crafting_recipe: Optional[str] = Field(- None, description="How to craft this item from other materials or items"- )- drop_sources: Optional[str] = Field(- None,- description="Where to obtain this item: which monsters drop it, NPCs who sell it, quest rewards, etc.",- )- suitable_heroes: Optional[str] = Field(- None, description="Which character classes or heroes benefit most from this item"- )- lore_background: Optional[str] = Field(- None, description="The gameplay lore or in-world story of this item"+ description: Optional[str] = Field(+ None, description="Acquisition info, suitable heroes, and lore background.",)@@ -59,14 +49,10 @@ Your task is to extract structured information about game items from the provideFor each item mentioned in the text, extract:1. **item_name**: The official or standard name of the item2. **category**: The type/class of item (weapon, armor, consumable, etc.)-3. **stat_bonuses**: Any attribute, damage, defense, or status effect bonuses this item provides-4. **crafting_recipe**: How players can craft or combine items to create this item-5. **drop_sources**: Where/who drops this item, shops that sell it, quest rewards, etc.-6. **suitable_heroes**: Which character classes or heroes are recommended to use this item-7. **lore_background**: Any in-game story, legend, or lore associated with this item--Extract only information explicitly mentioned in the text. If a field is not described, leave it empty.-Focus on being comprehensive and capturing all items mentioned, even if only briefly.+3. **item_data**: Stat bonuses, effects, and crafting recipes+4. **description**: Where to find it, recommended heroes, and background lore++Extract only information explicitly mentioned.### Source Text:"""diff --git a/hyperextract/templates/en/game/game_monster_compendium.py b/hyperextract/templates/en/game/game_monster_compendium.pyindex c852860..be079bc 100644--- a/hyperextract/templates/en/game/game_monster_compendium.py+++ b/hyperextract/templates/en/game/game_monster_compendium.py@@ -20,38 +20,20 @@ class GameMonsterSchema(BaseModel):monster_name: str = Field(..., description="The standard name of the monster, e.g., 'Goblin Warrior'")- monster_type: str = Field(+ type: str = Field(...,- description="Monster species/racial classification: 'Goblin', 'Dragon', 'Undead', 'Beast', etc.",- )- rarity_tier: Optional[str] = Field(- None,- description="Rarity level of the monster: 'Common', 'Elite', 'Boss', 'Legendary', etc.",+ description="Monster species and rarity classification (e.g., 'Undead / Boss', 'Beast / Common')",)habitat: Optional[str] = Field(None, description="Map areas or regions where this monster typically appears")- combat_stats: Optional[str] = Field(- None,- description="Combat attributes with numerical values: HP, attack, defense, magic resist, etc.",- )- special_abilities: Optional[str] = Field(+ abilities: Optional[str] = Field(None,- description="Unique skills or special attacks this monster can perform",+ description="Combat stats (HP/ATK), special skills, weaknesses, and encounter difficulty",)- elemental_weakness: Optional[str] = Field(+ loot_and_lore: Optional[str] = Field(None,- description="Element types this monster is weak to: Fire, Ice, Wind, Holy, Dark, etc.",- )- drop_table: Optional[str] = Field(- None,- description="Items dropped when defeated, including drop probability and item names",- )- respawn_timer: Optional[str] = Field(- None, description="How long it takes for this monster to respawn after defeat"- )- encounter_difficulty: Optional[str] = Field(- None, description="Recommended player level or difficulty assessment for encountering this monster"+ description="Items dropped, respawn mechanics, and background lore/flavor text",)@@ -62,20 +44,21 @@ class GameMonsterSchema(BaseModel):_PROMPT = """You are an expert game bestiary and monster guide author.Your task is to extract structured information about game monsters from the provided text.-For each monster mentioned, extract:+For each monster mentioned, extract these consolidated fields:1. **monster_name**: The official name of the monster-2. **monster_type**: The species or racial type of the monster-3. **rarity_tier**: How rare or powerful this monster is-4. **habitat**: Locations where this monster can be found-5. **combat_stats**: Numerical combat attributes (HP, ATK, DEF, etc.)-6. **special_abilities**: Unique or dangerous abilities this monster has-7. **elemental_weakness**: Element types that deal extra damage to this monster-8. **drop_table**: What items this monster drops and with what probability-9. **respawn_timer**: How long after defeat before the monster respawns-10. **encounter_difficulty**: Recommended player level or challenge rating--Extract only information explicitly mentioned. If a field is not described, leave it empty.-Be comprehensive in capturing all monster details, even if scattered throughout the text.+2. **type**: The species/race combined with rarity tier (e.g., Dragon/Legendary)+3. **habitat**: Locations where found+4. **abilities**:+ - Combat stats (HP/ATK)+ - Unique skills or attacks+ - Elemental weaknesses+ - Strategy or difficulty rating+5. **loot_and_lore**:+ - Dropped items and probabilities+ - Respawn timers or mechanics+ - Background lore and description++Extract only information explicitly mentioned. Keep descriptions concise but complete.### Source Text:"""@@ -169,7 +152,7 @@ class GameMonsterCompendium(AutoSet[GameMonsterSchema]):def monster_label_extractor(item: GameMonsterSchema) -> str:"""Extract display label: name with type."""- type_label = f" ({item.monster_type})" if item.monster_type else ""+ type_label = f" ({item.type})" if item.type else ""return f"{item.monster_name}{type_label}"super().show(diff --git a/hyperextract/templates/en/history/cultural_artifact_registry.py b/hyperextract/templates/en/history/cultural_artifact_registry.pyindex ea8a465..925ae16 100644--- a/hyperextract/templates/en/history/cultural_artifact_registry.py+++ b/hyperextract/templates/en/history/cultural_artifact_registry.py@@ -13,37 +13,20 @@ from hyperextract.types import AutoSetclass ArtifactSchema(BaseModel):artifact_name: str = Field(..., description="Official name of the artifact")- material: Optional[str] = Field(None, description="Primary material composition")- excavation_year: Optional[str] = Field(- None, description="Year the artifact was discovered"- )- excavation_location: Optional[str] = Field(- None, description="Geographic location of excavation"- )- current_museum: Optional[str] = Field(- None, description="Current museum or collection location"- )- dimensions: Optional[str] = Field(- None, description="Size and weight specifications"- )- symbolic_meaning: Optional[str] = Field(- None, description="Cultural or religious significance"- )- historical_period: Optional[str] = Field(- None, description="Civilization or historical era"- )+ period: Optional[str] = Field(None, description="Historical era, dynasty, or date")+ location: Optional[str] = Field(None, description="Excavation site and current museum location")+ physical_traits: Optional[str] = Field(None, description="Material, dimensions, and craftsmanship")+ significance: Optional[str] = Field(None, description="Cultural meaning, usage, and historical value")-_PROMPT = """You are a professional archaeologist and museum curator.-Extract comprehensive artifact information from the text:-1. artifact_name: Official artifact name-2. material: Material composition-3. excavation_year: Discovery year-4. excavation_location: Excavation site-5. current_museum: Current location/museum-6. dimensions: Physical measurements-7. symbolic_meaning: Cultural significance-8. historical_period: Historical era/dynasty+_PROMPT = """You are an archaeologist. Extract artifact information from text.++Field Guide:+1. **artifact_name**: Name of the artifact+2. **period**: Historical era+3. **location**: Combine excavation site and current location+4. **physical_traits**: Describe material, size, and craft+5. **significance**: Explain functionality and cultural meaningExtract only explicitly mentioned information.@@ -79,7 +62,7 @@ class CulturalArtifactRegistry(AutoSet[ArtifactSchema]):def show(self, *, top_k_for_search: int = 3, top_k_for_chat: int = 3) -> None:def label_extractor(item: ArtifactSchema) -> str:- period = f" ({item.historical_period})" if item.historical_period else ""+ period = f" ({item.period})" if item.period else ""return f"{item.artifact_name}{period}"super().show(diff --git a/hyperextract/templates/en/history/diplomatic_event_hypergraph.py b/hyperextract/templates/en/history/diplomatic_event_hypergraph.pyindex e537f82..e6dbb77 100644--- a/hyperextract/templates/en/history/diplomatic_event_hypergraph.py+++ b/hyperextract/templates/en/history/diplomatic_event_hypergraph.py@@ -22,15 +22,11 @@ class DiplomaticEventSchema(BaseModel):event_name: str = Field(..., description="Name of the event (e.g., 'Treaty of Versailles')")- signing_date: Optional[str] = Field(None, description="Date of the event")member_countries: List[str] = Field(default_factory=list, description="All participating countries")- key_terms: Optional[str] = Field(- None, description="Summary of key terms or outcomes"- )- leading_country: Optional[str] = Field(- None, description="Leading or initiating country"+ details: Optional[str] = Field(+ None, description="Signing date, key terms, leading countries, and outcomes.")@@ -43,7 +39,8 @@ A hyperedge connects multiple countries participating in a single event._NODE_PROMPT = """Extract all country/nation names mentioned in the text."""_EDGE_PROMPT = """Extract diplomatic events involving multiple countries.-For each event, list all participating countries in the member_countries field."""+For each event, list all participating countries in member_countries.+Combine key terms, signing date, and outcomes into the 'details' field."""class DiplomaticEventHypergraph(AutoHypergraph[CountrySchema, DiplomaticEventSchema]):diff --git a/hyperextract/templates/zh/finance/market_sentiment.py b/hyperextract/templates/zh/finance/market_sentiment.pyindex 4a8a4b6..a0759c8 100644--- a/hyperextract/templates/zh/finance/market_sentiment.py+++ b/hyperextract/templates/zh/finance/market_sentiment.py@@ -17,28 +17,12 @@ class MarketDriver(BaseModel):name: str = Field(description='驱动因素名称,例如"AI 需求"、"降息预期"、"监管明确化"等。')- driver_type: str = Field(- description='类型:"宏观"、"行业"、"公司特定"、"催化剂"。'- )+ driver_type: str = Field(description='类型:"宏观"、"行业"、"公司特定"、"催化剂"。')description: Optional[str] = Field(None, description="为什么这个驱动因素重要的详细解释。")-class MarketTarget(BaseModel):- """- 受市场驱动因素影响的交易资产或财务指标。- """-- ticker: str = Field(description='股票代码,例如"AAPL"、"AI 指数"。')- asset_type: str = Field(- description='类型:"股票"、"指数"、"债券"、"商品"、"货币"。'- )- metric: Optional[str] = Field(- None, description='具体指标(如适用),例如"EPS"、"P/E 比率"。'- )--class AnalystInfluence(BaseModel):"""表示市场驱动因素如何影响资产前景。@@ -46,21 +30,15 @@ class AnalystInfluence(BaseModel):source: str = Field(description="市场驱动因素名称。")target: str = Field(description="受影响资产/指标的股票代码。")- sentiment: str = Field(- description='情绪方向:"正面"、"负面"、"中性"。'- )- strength: str = Field(- description='影响力强度:"强"、"中等"、"弱"。'- )+ sentiment: str = Field(description='情绪方向:"正面"、"负面"、"中性"。')+ strength: str = Field(description='影响力强度:"强"、"中等"、"弱"。')analyst_view: str = Field(description='分析师建议或目标调整,例如"升级为买入"、"将目标价上调至 150 美元"等。')time_horizon: Optional[str] = Field(None, description='预期时间框架,例如"FY24"、"6-12 个月"、"长期"。')- source_firm: Optional[str] = Field(- None, description="研究机构或分析师来源的名称。"- )+ source_firm: Optional[str] = Field(None, description="研究机构或分析师来源的名称。")# ==============================================================================diff --git a/hyperextract/templates/zh/finance/supply_chain.py b/hyperextract/templates/zh/finance/supply_chain.pyindex bb1d79e..5aa0298 100644--- a/hyperextract/templates/zh/finance/supply_chain.py+++ b/hyperextract/templates/zh/finance/supply_chain.py@@ -18,11 +18,8 @@ class SupplyEntity(BaseModel):entity_type: str = Field(description='类型:"客户"、"供应商"、"战略伙伴"、"分销商"、"本公司"。')- jurisdiction: Optional[str] = Field(- None, description="地理位置或总部所在地。"- )- notes: Optional[str] = Field(- None, description='其他详情,例如"有机认证"、"ISO 合规"等。'+ details: Optional[str] = Field(+ None, description="地理管辖区、认证信息及合规说明。")@@ -33,24 +30,15 @@ class SupplyTransaction(BaseModel):source: str = Field(description="上游供应商或提供方。")target: str = Field(description="下游买方或需求方。")- transaction_type: str = Field(+ relationship_type: str = Field(description='类型:"供应"、"采购"、"分销"、"战略合作"。')product_service: str = Field(description='被供应或交易的内容,例如"锂芯片"、"物流服务"等。')- dependency: str = Field(- description='依赖程度:"关键"、"高"、"中等"、"低"。'- )- volume_percentage: Optional[str] = Field(- None, description='如有披露,总供应或收入的百分比,例如"80%"。'- )- geographic_origin: Optional[str] = Field(- None, description="来源地区或地缘政治考量。"- )- risks: Optional[str] = Field(+ risk_assessment: Optional[str] = Field(None,- description='披露的风险或脆弱性,例如"单一来源供应商"、"关税暴露"。'+ description="依赖程度、交易量占比、地理来源风险及地缘政治因素的综合评估。",)@@ -59,30 +47,26 @@ class SupplyTransaction(BaseModel):# ==============================================================================_PROMPT = (- "你是供应链分析师。从企业财报和供应链审计中提取供应链实体及其关系。\n\n"+ "你是供应链分析师。提取供应链实体及其关系。\n\n""规则:\n"- "- 识别提及的关键供应商、客户和战略伙伴。\n"- "- 提取交易类型和产品/服务描述。\n"- "- 根据披露的数量或重要性评估依赖程度。\n"- "- 记录任何地缘政治或监管风险。"+ "- 识别供应商、客户和伙伴。\n"+ "- 提取交易类型及产品。\n"+ "- 将依赖度、交易量及地缘政治风险汇总至 **risk_assessment**。")_NODE_PROMPT = (- "你是供应链分析师。从文本中提取所有供应链参与者(节点)。\n\n"- "提取规则:\n"- "- 识别公司、供应商、客户和分销合作伙伴。\n"- "- 对每个实体在供应链中的角色进行分类。\n"- "- 记录司法管辖区和任何认证或合规说明。\n"- "- 此阶段不建立交易关系。"+ "你是供应链分析师。提取供应链参与者(节点)。\n\n"+ "规则:\n"+ "- 识别公司及和伙伴。\n"+ "- 分类角色。\n"+ "- 记录地区及认证至 **details**。")_EDGE_PROMPT = (- "你是供应链分析师。在获得供应链实体清单的基础上,提取交易关系(边)。\n\n"- "提取规则:\n"- "- 将供应商连接到买方,说明具体的产品/服务。\n"- "- 根据披露的数量百分比或重要性关键词评估依赖程度。\n"- "- 提取地理来源和任何披露的风险(关税、单一来源)。\n"- "- 仅连接提供列表中存在的实体。"+ "你是供应链分析师。提取交易关系(边)。\n\n"+ "规则:\n"+ "- 通过产品/服务连接实体。\n"+ "- **risk_assessment**: 综合评估依赖度、交易量及风险(关税、单一来源)。")# ==============================================================================@@ -174,8 +158,8 @@ class SupplyChainGraph(AutoGraph[SupplyEntity, SupplyTransaction]):return f"{node.name} ({node.entity_type})"def edge_label_extractor(edge: SupplyTransaction) -> str:- vol = f" {edge.volume_percentage}" if edge.volume_percentage else ""- return f"{edge.product_service}{vol} [{edge.dependency}]"+ risk = f" [{edge.risk_assessment}]" if edge.risk_assessment else ""+ return f"{edge.product_service}{risk}"super().show(node_label_extractor=node_label_extractor,diff --git a/hyperextract/templates/zh/food/__init__.py b/hyperextract/templates/zh/food/__init__.pyindex efd1d48..5f864b4 100644--- a/hyperextract/templates/zh/food/__init__.py+++ b/hyperextract/templates/zh/food/__init__.py@@ -6,12 +6,10 @@from .haccp_safety import FoodSafetyHACCPGraphfrom .recipe_process import RecipeProcessGraph-from .flavor_pairing import FlavorPairingGraphfrom .culinary_dish import CulinaryDishSet__all__ = ["FoodSafetyHACCPGraph","RecipeProcessGraph",- "FlavorPairingGraph","CulinaryDishSet",]diff --git a/hyperextract/templates/zh/food/culinary_dish.py b/hyperextract/templates/zh/food/culinary_dish.pyindex 8169ede..9a51833 100644--- a/hyperextract/templates/zh/food/culinary_dish.py+++ b/hyperextract/templates/zh/food/culinary_dish.py@@ -11,39 +11,24 @@ from hyperextract.types import AutoSetclass CulinaryDish(BaseModel):"""- 菜肴条目,包括其身份、成分和烹饪特征。+ 菜肴知识条目。"""- name: str = Field(description="菜肴的标准名称,例如宫保鸡丁或红烧肉。")- cuisine: Optional[str] = Field(- None, description="烹饪传统或菜系,例如四川、法式、意大利、日式。"+ name: str = Field(description="菜肴的标准名称,例如宫保鸡丁。")+ origin: Optional[str] = Field(+ None, description="菜系、地理原产地及适应季节(如:四川/夏季)。")- region: Optional[str] = Field(- None, description="地理原产地,例如中国四川、法国普罗旺斯。"- )- primary_ingredients: Optional[str] = Field(+ ingredients: Optional[str] = Field(None,- description="主要成分列表,例如鸡、花生、干辣椒、酱油、糖。"- )- protein_type: Optional[str] = Field(- None, description="主要蛋白质或基础:鸡肉、猪肉、鱼、豆腐、蔬菜。"+ description="主要食材、蛋白质类型及核心酱料。")- flavor_profile: Optional[str] = Field(+ profile: Optional[str] = Field(None,- description="总体味道特征,例如辛辣甜蜜、香气温暖、咸香鲜美。"- )- cooking_method: Optional[str] = Field(- None, description="烹饪技术,例如炒、炖、烧烤、炸、蒸。"+ description="风味特征(酸甜苦辣)、口感及烹饪方法(蒸炒炸)。")- dietary_attributes: Optional[str] = Field(+ description: Optional[str] = Field(None,- description="饮食特征,例如素食、无麸质、低钠、高蛋白。"- )- serving_suggestion: Optional[str] = Field(- None, description="典型的供菜方式或配菜,例如配米饭和蔬菜。"- )- seasonal_note: Optional[str] = Field(- None, description="季节性或时间相关性,例如冬季舒适食物、夏季开胃菜。"+ description="其它描述,包括饮食宜忌、配菜建议及历史背景。")@@ -52,13 +37,13 @@ class CulinaryDish(BaseModel):# ==============================================================================_PROMPT = (- "你是美食知识库管理员。从菜单、食谱甚至非结构化美食文本中提取菜肴。\n\n"- "规则:\n"- "- 识别每个不同的菜肴名称和变体。\n"- "- 捕捉烹饪传统、地理原产地、主要成分。\n"- "- 记录烹饪方法、风味特征和任何特殊属性。\n"- "- 保持原始文本中的名称和描述。\n"- "- 为后续去重标准化做准备(名称、成分)。"+ "你是美食知识库管理员。从文本中提取菜肴信息。\n\n"+ "提取规则:\n"+ "- 识别菜肴标准名称。\n"+ "- **origin**: 整合菜系、城市及季节信息。\n"+ "- **ingredients**: 列出核心食材和配料。\n"+ "- **profile**: 描述味道、质地及烹饪工艺。\n"+ "- **description**: 包含文化背景、饮食特征等补充信息。\n")# ==============================================================================@@ -68,21 +53,9 @@ _PROMPT = (class CulinaryDishSet(AutoSet[CulinaryDish]):"""- 适用文档: 餐厅菜单、美食博客、烹饪书籍、食材供应商列表、菜肴数据库、美食指南、社交媒体。+ 适用文档: 菜单、食谱、美食博客。- 模板用于构建标准化的菜肴知识库,通过**精确的菜肴名称为键进行信息累加**。- 自动将来自多个文本源的同一菜肴信息合并为一条完整条目,从各源中积累食材、烹饪方法、地域特征和风味描述。-- 使用示例:- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings- >>> llm = ChatOpenAI(model="gpt-4o")- >>> embedder = OpenAIEmbeddings()- >>> dishes = CulinaryDishSet(llm_client=llm, embedder=embedder)- >>> # 来源 1:提取基本信息(名称、菜系、地域)- >>> dishes.feed_text("宫保鸡丁是来源于四川的著名菜肴,主要食材有鸡肉、花生、干辣椒。")- >>> # 来源 2:提取补充信息(风味、烹饪手法)- >>> dishes.feed_text("宫保鸡丁采用大火快速炒制,花生要烘烤,整体风味是甜辣鲜香。")- >>> dishes.show() # 显示合并后包含两个来源信息的"宫保鸡丁"条目+ 模板用于构建标准化的菜肴知识库。"""def __init__(@@ -96,18 +69,6 @@ class CulinaryDishSet(AutoSet[CulinaryDish]):verbose: bool = False,**kwargs: Any,):- """- 初始化食物菜肴集合模板。-- Args:- llm_client (BaseChatModel): 用于提取的 LLM。- embedder (Embeddings): 用于语义检索和知识图谱可视化的嵌入模型。- chunk_size (int): 每个分块的最大字符数。- chunk_overlap (int): 分块之间的重叠。- max_workers (int): 并行处理工作线程数。- verbose (bool): 是否启用进度日志。- **kwargs: AutoSet 的其他参数。- """super().__init__(item_schema=CulinaryDish,key_extractor=lambda x: x.name.strip().lower(),@@ -127,18 +88,10 @@ class CulinaryDishSet(AutoSet[CulinaryDish]):top_k_items_for_search: int = 10,top_k_items_for_chat: int = 10,) -> None:- """- 使用 OntoSight 可视化菜肴集合。-- Args:- top_k_items_for_search (int): 检索的菜肴数。默认 10。- top_k_items_for_chat (int): 对话上下文中的菜肴数。默认 10。- """-def item_label_extractor(item: CulinaryDish) -> str:parts = [item.name]- if item.cuisine:- parts.append(f"({item.cuisine})")+ if item.origin:+ parts.append(f"({item.origin})")return " ".join(parts)super().show(diff --git a/hyperextract/templates/zh/food/flavor_pairing.py b/hyperextract/templates/zh/food/flavor_pairing.pydeleted file mode 100644index dc74825..0000000--- a/hyperextract/templates/zh/food/flavor_pairing.py+++ /dev/null@@ -1,187 +0,0 @@-from typing import Optional, Any, Literal-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 FlavorComponent(BaseModel):- """- 个别风味分子或复合物及其性质。- """-- name: str = Field(description="风味成分的名称,例如木质素、硫含物、咖啡因。")- component_type: str = Field(- description="分类:分子、香气、甜味、苦味、酸味、鲜味、油质、烤焙、花卉。"- )- description: str = Field(- description="来自文本的成分特征,例如温暖、烟熏、柔和的甜味。"- )---class FlavorRelationship(BaseModel):- """- 两个风味成分之间的关系。- """-- source_component: str = Field(description="第一个风味成分的名称。")- target_component: str = Field(description="第二个风味成分的名称。")- relationship_type: Literal[- "Contains", "Pairs_Well", "Confirms", "Complements", "Contrasts"- ] = Field(- description="关系类型:Contains(包含)、Pairs_Well(配对好)、Confirms(确认)、Complements(补充)、Contrasts(对比)。"- )- pairing_mechanism: Optional[str] = Field(- None,- description="为什么这两个成分会一起工作,例如共享的木质素分子或互补的甜度曲线。"- )- pairing_quality: Optional[str] = Field(- None, description="配对质量的评估:优秀、好、可接受、有冲突。"- )- culinary_context: Optional[str] = Field(- None, description='应用这个配对的烹饪环境或菜肴,例如"法式高汤"或"甜点"。'- )---# ==============================================================================-# 2. 提示词 (Prompts)-# ==============================================================================--_PROMPT = (- "你是美食科学家。从美食科学论文中提取风味配对和感官关系。\n\n"- "规则:\n"- "- 识别个别风味分子和复合物。\n"- "- 链接配对好的成分和为什么它们有效。\n"- "- 提取描述性术语(温暖、烟熏、花卉等)。\n"- "- 关注共享分子或感官相补性的机制。\n"- "- 记录烹饪环境(酱料、甜点、肉类等)。"-)--_NODE_PROMPT = (- "你是美食科学家。从食品科学论文或菜谱中提取所有风味成分(节点)。\n\n"- "提取规则:\n"- "- 列出所有提到的风味分子、香气或感官特征。\n"- "- 分类为 molecules、aromas、tastes、textures 等。\n"- "- 包括来自源文本的描述性特征(工作、柔软、复杂)。\n"- "- 不包括有关如何将成分配对的信息。\n"- "- 此阶段保持所有成分作为独立实体。"-)--_EDGE_PROMPT = (- "你是美食科学家。给定一个成分列表,识别哪些成分配对好(边),以及为什么。\n\n"- "配对规则:\n"- "- 连接列表中存在的成分。\n"- "- 说明配对机制(共享分子、互补风味)。\n"- "- 评评对质量(优秀、好、可接受、冲突)。\n"- "- 记录烹饪应用(什么菜肴、什么菜系)。\n"- "- 来自源文本中的链接只存在于显式提及的成分。"-)--# ==============================================================================-# 3. 模板类-# ==============================================================================---class FlavorPairingGraph(AutoGraph[FlavorComponent, FlavorRelationship]):- """- 适用文档: 美食科学期刊、经验烹饪书、感官评估报告、风味科学研究、菜单设计指南、R&D 笔记。-- 模板用于从感官和分子证据中提取风味配对知识。支持菜单创新、厨师培训和结构化食物组合理论。-- 使用示例:- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings- >>> llm = ChatOpenAI(model="gpt-4o")- >>> embedder = OpenAIEmbeddings()- >>> flavors = FlavorPairingGraph(llm_client=llm, embedder=embedder)- >>> text = "草莓和黑胡椒通过共有的木质素分子进行配对"- >>> flavors.feed_text(text)- >>> flavors.show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- extraction_mode: str = "one_stage",- chunk_size: int = 2048,- chunk_overlap: int = 256,- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any,- ):- """- 初始化风味配对图谱模板。-- Args:- llm_client (BaseChatModel): 用于提取的 LLM。- embedder (Embeddings): 用于去重的嵌入模型。- extraction_mode (str): "one_stage" 或 "two_stage"。- chunk_size (int): 每个分块的最大字符数。- chunk_overlap (int): 分块之间的重叠。- max_workers (int): 并行处理工作线程数。- verbose (bool): 是否启用进度日志。- **kwargs: AutoGraph 的其他参数。- """- super().__init__(- node_schema=FlavorComponent,- edge_schema=FlavorRelationship,- node_key_extractor=lambda x: x.name.strip().lower(),- edge_key_extractor=lambda x: (- x.source_component.strip().lower(),- x.target_component.strip().lower(),- ),- nodes_in_edge_extractor=lambda x: (- x.source_component.strip(),- x.target_component.strip(),- ),- llm_client=llm_client,- embedder=embedder,- extraction_mode=extraction_mode,- chunk_size=chunk_size,- chunk_overlap=chunk_overlap,- max_workers=max_workers,- verbose=verbose,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- **kwargs,- )-- def show(- self,- *,- top_k_nodes_for_search: int = 5,- top_k_edges_for_search: int = 5,- top_k_nodes_for_chat: int = 5,- top_k_edges_for_chat: int = 5,- ) -> None:- """- 使用 OntoSight 可视化风味配对网络。-- Args:- top_k_nodes_for_search (int): 检索的成分数。默认 5。- top_k_edges_for_search (int): 检索的配对数。默认 5。- top_k_nodes_for_chat (int): 对话上下文中的成分数。默认 5。- top_k_edges_for_chat (int): 对话上下文中的配对数。默认 5。- """-- def node_label_extractor(node: FlavorComponent) -> str:- return f"{node.name} ({node.component_type})"-- def edge_label_extractor(edge: FlavorRelationship) -> str:- quality = f" [{edge.pairing_quality}]" if edge.pairing_quality else ""- return f"{edge.relationship_type}{quality}"-- super().show(- node_label_extractor=node_label_extractor,- edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_nodes_for_search,- top_k_edges_for_search=top_k_edges_for_search,- top_k_nodes_for_chat=top_k_nodes_for_chat,- top_k_edges_for_chat=top_k_edges_for_chat,- )diff --git a/hyperextract/templates/zh/food/haccp_safety.py b/hyperextract/templates/zh/food/haccp_safety.pyindex 7d4b3f0..72c2527 100644--- a/hyperextract/templates/zh/food/haccp_safety.py+++ b/hyperextract/templates/zh/food/haccp_safety.py@@ -49,19 +49,13 @@ class ControlMeasure(BaseModel):source: str = Field(description="生物学危害名称。")target: str = Field(description="CCP 名称。")critical_limit: str = Field(- description='定义安全/不安全分界线的关键限值,例如">=72°C 持续 >=15 秒"、"pH < 4.6"等。'+ description='定义安全/不安全分界线的关键限值(如">=72°C 持续 >=15 秒")。')- monitoring_procedure: str = Field(- description='如何监测 CCP,例如"每批次温度计读数"、"每天 pH 计测量"等。'+ monitoring: str = Field(+ description="监测程序与频率(如何监测以及多久监测一次)。")- monitoring_frequency: str = Field(- description='监测频率,例如"每 2 小时"、"每批次"、"每天"等。'- )- corrective_action: str = Field(- description='如果不达到关键限值的行动,例如"销毁产品"、"重新加工"、"警报 QA"等。'- )- verification: Optional[str] = Field(- None, description='验证有效性的方法,例如"每月进行培养测试"等。'+ details: Optional[str] = Field(+ None, description="纠偏行动及验证有效性的方法。")@@ -70,33 +64,29 @@ class ControlMeasure(BaseModel):# ==============================================================================_PROMPT = (- "你是食品安全专家,熟悉 HACCP 原则。从 HACCP 计划和食品安全文件中提取危害、关键控制点及其控制措施。\n\n"+ "你是食品安全专家。提取危害、关键控制点(CCP)及其控制措施。\n\n""规则:\n"- "- 识别与产品和工序相关的生物学危害。\n"- "- 识别可以消除或控制危害的 CCP。\n"- "- 提取关键限值、监测程序和纠偏行动。\n"- "- 确保每个 CCP 链接到它控制的具体危害。"+ "- 识别所有提及的危害与 CCP。\n"+ "- 将危害连接到对应的 CCP。\n"+ "- 提取 **关键限值 (critical_limit)** 与 **监测 (monitoring)** 指标。\n"+ "- 将纠偏行动与验证方法归入 **详情 (details)**。")_NODE_PROMPT = (- "你是食品安全专家。从 HACCP 文件中提取所有危害和 CCP(节点)。\n\n"+ "你是食品安全专家。从文件中提取危害和 CCP(节点)。\n\n""提取规则:\n"- "- 识别所有提及的生物学危害(病原体、过敏原如适用)。\n"- "- 识别所有 CCP(烹饪、冷却、金属检测阶段)。\n"- "- 按类型对每个危害进行分类(细菌、病毒、真菌、寄生虫)。\n"- "- 按生产阶段对每个 CCP 进行分类。\n"- "- 此阶段不建立控制关系。"+ "- 识别生物学危害并分类。\n"+ "- 识别 CCP 及其生产阶段。\n")_EDGE_PROMPT = (- "你是食品安全专家。在获得危害和 CCP 清单的基础上,提取控制关系(边)。\n\n"+ "你是食品安全专家。提取控制措施(边)。\n\n""提取规则:\n"- "- 将每个危害连接到控制它的 CCP。\n"- "- 提取具有精确阈值和单位的关键限值。\n"- "- 从 HACCP 文件中提取监测程序和频率。\n"- "- 提取超过限值时应采取的纠偏行动。\n"- "- 在有文件记录时包括验证方法。\n"- "- 仅在提供的列表中存在的危害和 CCP 之间创建边。"+ "- 将危害连接到 CCP。\n"+ "- **critical_limit**: 安全分界线。\n"+ "- **monitoring**: 如何及何时监测。\n"+ "- **details**: 纠偏行动及验证方法。\n"+ "- 仅连接存在的节点。")# ==============================================================================diff --git a/hyperextract/templates/zh/food/recipe_process.py b/hyperextract/templates/zh/food/recipe_process.pyindex 0ec0aed..1887088 100644--- a/hyperextract/templates/zh/food/recipe_process.py+++ b/hyperextract/templates/zh/food/recipe_process.py@@ -36,21 +36,8 @@ class ProcessingStep(BaseModel):action: str = Field(description="加工动作,例如混合、加热、冷却、静置、揉搓、发酵。")- duration: str = Field(- description="动作持续时间,例如10分钟、2小时、一夜、15秒。"- )- temperature: Optional[str] = Field(- None, description="温度设置(如适用),例如175°C、室温、4°C。"- )- equipment: Optional[str] = Field(- None, description="使用的设备,例如台式搅拌机、烤箱、水浴、温度计。"- )- parameters: Optional[str] = Field(- None,- description="其他参数(速度、压力等),例如中等速度、200 PSI。"- )- notes: Optional[str] = Field(- None, description='特殊说明或观察,例如"应形成轻微奶油状"。'+ process_conditions: Optional[str] = Field(+ None, description="综述持续时间、温度、设备及工艺参数。")@@ -59,33 +46,29 @@ class ProcessingStep(BaseModel):# ==============================================================================_PROMPT = (- "你是专业厨师和食品科学家。从配方单和 SOP 中提取分步食谱或工业食品生产工序。\n\n"+ "你是食品科学家。提取配方工序步骤。\n\n""规则:\n"- "- 识别每个不同的加工动作和转换。\n"- "- 提取每个步骤前后的食材状态。\n"- "- 精确捕捉时间、温度和设备。\n"- "- 保持严格的顺序(步骤 1 -> 步骤 2 等)。\n"- "- 包括关于质地、外观或感官线索的说明。"+ "- 识别加工动作及能量转换。\n"+ "- 提取步骤前后的食材状态。\n"+ "- 捕捉 **工艺条件 (process_conditions)**(时间、温度、设备等)。\n"+ "- 保持严格的先后顺序。")_NODE_PROMPT = (- "你是专业厨师和食品科学家。从食谱中提取所有食材状态(节点)。\n\n"+ "你是食品科学家。提取食材状态(节点)。\n\n""提取规则:\n"- "- 识别食谱中的不同状态/阶段(原始、混合、加热、冷却、静置)。\n"- "- 描述每个状态下存在的食材。\n"- "- 记录物理形态(液体、固体、面团等)。\n"- "- 保持源文本中的确切名称和描述。\n"- "- 此阶段不描述状态之间的动作或转换。"+ "- 识别不同阶段的状态(原始、混合、熟制)。\n"+ "- 列出存在的组成物质。\n"+ "- 记录其物理形态。")_EDGE_PROMPT = (- "你是专业厨师。在获得食材状态清单的基础上,提取将一个状态转换为另一个状态的加工步骤(边)。\n\n"+ "你是食品科学家。提取加工步骤(边)。\n\n""提取规则:\n"- "- 将每个源状态连接到其目标状态,说明具体动作。\n"- "- 提取每个步骤的时间、温度和设备。\n"- "- 提取任何特殊参数(速度、压力)或感官线索。\n"- "- 保持严格的步骤顺序(步骤 1、步骤 2 等)。\n"- "- 仅连接提供列表中存在的状态。"+ "- 通过动作连接源状态与目标状态。\n"+ "- **process_conditions**: 合并记录时间、温度、设备等参数。\n"+ "- 保持精确的步骤顺序。\n"+ "- 仅连接存在的节点。")# ==============================================================================diff --git a/hyperextract/templates/zh/game/game_character_compendium.py b/hyperextract/templates/zh/game/game_character_compendium.pyindex a5befd3..965725a 100644--- a/hyperextract/templates/zh/game/game_character_compendium.py+++ b/hyperextract/templates/zh/game/game_character_compendium.py@@ -14,18 +14,25 @@ from hyperextract.types import AutoSet# Schema 定义# ==============================================================================+class GameCharacterSchema(BaseModel):"""游戏角色百科中单个角色的数据结构。"""character_name: str = Field(..., description="角色的标准名称,如'亚索'")- character_class: str = Field(..., description="角色职业/角色定位:'剑士'、'法师'、'射手'、'坦克'、'辅助'等")- background_story: Optional[str] = Field(None, description="角色的背景故事、起源和身世")- signature_abilities: Optional[str] = Field(None, description="该角色拥有的主要技能和招牌能力清单")- base_stats: Optional[str] = Field(None, description="基础属性:生命值、魔法值、攻击力、防御力、速度等数值")- recommended_playstyle: Optional[str] = Field(None, description="如何有效地使用该角色:位置、连击、装备搭配等")- origin_region: Optional[str] = Field(None, description="该角色来自的游戏世界区域")- faction_affiliation: Optional[str] = Field(None, description="该角色所属的阵营、队伍或组织")- voice_actor: Optional[str] = Field(None, description="该角色的官方配音演员信息")+ class_role: str = Field(+ ...,+ description="角色职业/定位(如'战士'、'法师')及玩法风格简述。",+ )+ affiliation: Optional[str] = Field(+ None, description="所属阵营、团队或出身地区。"+ )+ abilities: Optional[str] = Field(+ None,+ description="招牌技能、终极技能及核心基础数值属性。",+ )+ lore: Optional[str] = Field(+ None, description="背景故事、性格特质、配音演员等设定信息。"+ )# ==============================================================================@@ -37,14 +44,10 @@ _PROMPT = """你是一位游戏背景设定专家和角色指南作者。对于文本中提到的每个角色,提取:1. **character_name**:角色的官方名称-2. **character_class**:角色的职业/定位-3. **background_story**:角色的起源故事和背景-4. **signature_abilities**:该角色拥有的主要和特殊能力/技能-5. **base_stats**:核心数值属性:生命值、魔法值、攻击力、防御力等-6. **recommended_playstyle**:战略指导,如何有效地使用该角色-7. **origin_region**:角色来自的区域或世界地区-8. **faction_affiliation**:角色所属的队伍、组织或阵营-9. **voice_actor**:官方配音演员的名字(如提及)+2. **class_role**:角色的职业定位与玩法概述+3. **affiliation**:角色所属的组织、阵营或家乡+4. **abilities**:角色的核心技能、大招说明及关键数值+5. **lore**:角色的背景故事、身世细节、配音等设定仅提取文本中明确说明的信息。如果某个字段未提及,空置即可。全面捕捉所有角色详情,即使它们分散在文本中。@@ -57,6 +60,7 @@ _PROMPT = """你是一位游戏背景设定专家和角色指南作者。# 模板类# ==============================================================================+class GameCharacterCompendium(AutoSet[GameCharacterSchema]):"""适用于:角色背景故事、技能指南、官方角色资料、策略指南@@ -135,7 +139,7 @@ class GameCharacterCompendium(AutoSet[GameCharacterSchema]):def character_label_extractor(item: GameCharacterSchema) -> str:"""提取展示标签:角色名称带职业"""- class_label = f" ({item.character_class})" if item.character_class else ""+ class_label = f" ({item.class_role})" if item.class_role else ""return f"{item.character_name}{class_label}"super().show(diff --git a/hyperextract/templates/zh/game/game_item_compendium.py b/hyperextract/templates/zh/game/game_item_compendium.pyindex 19aab18..544a4ea 100644--- a/hyperextract/templates/zh/game/game_item_compendium.py+++ b/hyperextract/templates/zh/game/game_item_compendium.py@@ -18,16 +18,13 @@ class GameItemSchema(BaseModel):"""游戏物品图鉴中单个物品的数据结构。"""item_name: str = Field(..., description="物品的标准名称")- category: str = Field(..., description="物品分类:'武器'、'防具'、'消耗品'、'配饰'、'材料'等")- stat_bonuses: Optional[str] = Field(- None, description="物品提供的属性加成,如'攻击力+50,生命值+100'"+ category: str = Field(..., description="物品分类:'武器'、'防具'、'消耗品'、'材料'等")+ item_data: Optional[str] = Field(+ None, description="物品数值属性、合成配方及具体的伤害/防御效果。")- crafting_recipe: Optional[str] = Field(None, description="如何通过合成其他物品获得该物品")- drop_sources: Optional[str] = Field(- None, description="物品的获取方式:掉落怪物、NPC商店、任务奖励等"+ description: Optional[str] = Field(+ None, description="获取方式(掉落/商店)、适用职业及背景设定故事。")- suitable_heroes: Optional[str] = Field(None, description="最适合装备该物品的职业或角色")- lore_background: Optional[str] = Field(None, description="物品的游戏进度设定或背景故事")# ==============================================================================@@ -40,11 +37,8 @@ _PROMPT = """你是一位游戏设计师和游戏攻略作者,对游戏物品对于文本中提到的每个物品,提取:1. **item_name**:物品的标准名称2. **category**:物品的类型(武器、防具、消耗品等)-3. **stat_bonuses**:该物品提供的属性、伤害、防御或状态效果加成-4. **crafting_recipe**:玩家如何制作或合成该物品-5. **drop_sources**:物品的掉落来源、商人、任务奖励等-6. **suitable_heroes**:推荐哪些职业或角色使用该物品-7. **lore_background**:与该物品相关的游戏故事或设定+3. **item_data**:物品提供的属性加成、各种效果及合成公式信息+4. **description**:物品的来源渠道、推荐适用的职业角色及背景传说仅提取文本中明确提及的信息。如果某个字段没有描述,空置即可。重点是全面捕捉所有提到的物品及其详细信息。diff --git a/hyperextract/templates/zh/game/game_monster_compendium.py b/hyperextract/templates/zh/game/game_monster_compendium.pyindex 9a110b6..543ed86 100644--- a/hyperextract/templates/zh/game/game_monster_compendium.py+++ b/hyperextract/templates/zh/game/game_monster_compendium.py@@ -18,38 +18,26 @@ class GameMonsterSchema(BaseModel):"""游戏怪物百科中单个怪物的数据结构。"""monster_name: str = Field(..., description="怪物的标准名称,如'哥布林战士'")- monster_type: str = Field(..., description="怪物种族分类:'哥布林'、'龙'、'亡灵'、'野兽'等")- rarity_tier: Optional[str] = Field(None, description="怪物的稀有程度:'普通'、'精英'、'首领'、'传奇'等")- habitat: Optional[str] = Field(None, description="该怪物通常出现的地图区域")- combat_stats: Optional[str] = Field(None, description="战斗属性和数值:生命值、攻击力、防御力、魔抗等")- special_abilities: Optional[str] = Field(None, description="该怪物拥有的独特技能或特殊攻击方式")- elemental_weakness: Optional[str] = Field(None, description="该怪物克制的元素类型:火、冰、风、圣、暗等")- drop_table: Optional[str] = Field(None, description="打败该怪物掉落的物品及掉落概率")- respawn_timer: Optional[str] = Field(None, description="该怪物被击败后的复活周期")- encounter_difficulty: Optional[str] = Field(None, description="遭遇该怪物的推荐玩家等级或难度评估")+ type: str = Field(..., description="怪物种族分类及强度:'哥布林/普通'、'龙/首领'")+ habitat: Optional[str] = Field(None, description="通常出现的地图区域")+ abilities: Optional[str] = Field(None, description="战斗数值、特殊技能、弱点及难度评估等综合战斗信息")+ loot_and_lore: Optional[str] = Field(None, description="掉落物品、复活机制及背景故事")# ==============================================================================# 提取 Prompt# ==============================================================================-_PROMPT = """你是一位游戏怪物图鉴和刷怪攻略作者。-你的任务是从文本中提取游戏怪物的结构化信息。+_PROMPT = """你是一位游戏怪物图鉴作者。从文本中提取怪物的核心信息。-对于文本中提到的每个怪物,提取:-1. **monster_name**:怪物的官方名称-2. **monster_type**:怪物的种族或生物类型-3. **rarity_tier**:该怪物的稀有程度或强度等级-4. **habitat**:可以发现该怪物的位置或地图区域-5. **combat_stats**:战斗属性的数值(生命值、攻击力、防御力等)-6. **special_abilities**:该怪物拥有的独特或危险的能力-7. **elemental_weakness**:克制该怪物的元素类型-8. **drop_table**:打败该怪物可能掉落的物品和概率-9. **respawn_timer**:怪物被击败后复活所需的时间-10. **encounter_difficulty**:推荐的玩家等级或挑战难度评估+提取目标:+1. **monster_name**:怪物官方名称+2. **type**:种族及稀有度(如:亡灵/精英)+3. **habitat**:出没地点+4. **abilities**:合并战斗属性(HP/攻击)、技能、弱点和打法建议+5. **loot_and_lore**:合并掉落列表、刷新时间和背景描述-仅提取文本中明确提及的信息。如果某个字段未描述,空置即可。-全面捕捉所有怪物详情,即使分散在文本中。+仅提取明确提及的信息。### 源文本:"""@@ -60,39 +48,9 @@ _PROMPT = """你是一位游戏怪物图鉴和刷怪攻略作者。# ==============================================================================class GameMonsterCompendium(AutoSet[GameMonsterSchema]):- """适用于:怪物指南、图鉴条目、刷怪指南、补丁说明+ """适用于:怪物指南、图鉴条目、刷怪指南通过自动去重和合并来自多个来源的怪物信息来提取全面的游戏怪物数据库。-- 该模板特别适用于:- - 从分散的 Wiki 信息构建统一的怪物数据库- - 合并来自多个刷怪指南的怪物数据- - 整合属性信息和掉落表- - 通过合并来自多个来源的数据创建详细的怪物档案-- 示例:- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings- >>> from hyperextract.templates.zh.game import GameMonsterCompendium- >>>- >>> llm = ChatOpenAI(model="gpt-4", temperature=0)- >>> embedder = OpenAIEmbeddings()- >>>- >>> monsters = GameMonsterCompendium(- ... llm_client=llm,- ... embedder=embedder- ... )- >>>- >>> # 输入多个来源- >>> monsters.feed_text(- ... "哥布林战士是一个近战格斗者,拥有150生命值和45攻击力。"- ... "在黑暗森林区域发现,每5分钟复活一次。"- ... )- >>> monsters.feed_text(- ... "哥布林战士对火消伤害克制。它可以使用盾牌冲击和横扫攻击。"- ... )- >>>- >>> # 所有信息自动合并为单个哥布林战士档案- >>> monsters.show()"""def __init__(@@ -103,15 +61,6 @@ class GameMonsterCompendium(AutoSet[GameMonsterSchema]):chunk_overlap: int = 256,**kwargs: Any,):- """初始化游戏怪物百科模板。-- 参数:- llm_client:语言模型客户端,用于怪物提取(如 ChatOpenAI)- embedder:嵌入模型,用于语义索引(如 OpenAIEmbeddings)- chunk_size:单个文本块的最大字符数(默认2048)- chunk_overlap:相邻块之间的重叠字符数(默认256)- **kwargs:传递给 AutoSet 父类的其他参数- """super().__init__(item_schema=GameMonsterSchema,llm_client=llm_client,@@ -129,16 +78,8 @@ class GameMonsterCompendium(AutoSet[GameMonsterSchema]):top_k_for_search: int = 3,top_k_for_chat: int = 3,) -> None:- """展示游戏怪物百科为交互式知识库。-- 参数:- top_k_for_search:语义搜索返回的前 K 个结果数- top_k_for_chat:对话上下文中显示的前 K 个结果数- """-def monster_label_extractor(item: GameMonsterSchema) -> str:- """提取展示标签:怪物名称带种族"""- type_label = f" ({item.monster_type})" if item.monster_type else ""+ type_label = f" ({item.type})" if item.type else ""return f"{item.monster_name}{type_label}"super().show(diff --git a/hyperextract/templates/zh/history/cultural_artifact_registry.py b/hyperextract/templates/zh/history/cultural_artifact_registry.pyindex cfade04..4843944 100644--- a/hyperextract/templates/zh/history/cultural_artifact_registry.py+++ b/hyperextract/templates/zh/history/cultural_artifact_registry.py@@ -11,26 +11,21 @@ from hyperextract.types import AutoSetclass ArtifactSchema(BaseModel):artifact_name: str = Field(..., description="文物的官方名称")- material: Optional[str] = Field(None, description="主要材料成分")- excavation_year: Optional[str] = Field(None, description="发现年份")- excavation_location: Optional[str] = Field(None, description="出土地点")- current_museum: Optional[str] = Field(None, description="当前收藏地/博物馆")- dimensions: Optional[str] = Field(None, description="尺寸和重量规格")- symbolic_meaning: Optional[str] = Field(None, description="文化或宗教意义")- historical_period: Optional[str] = Field(None, description="历史时期/朝代")+ period: Optional[str] = Field(None, description="历史时期、朝代或大概年份")+ location: Optional[str] = Field(None, description="出土地点、发现处及当前所属博物馆")+ physical_traits: Optional[str] = Field(None, description="材质、尺寸、重量及工艺特征")+ significance: Optional[str] = Field(None, description="文化意义、用途描述及象征价值")-_PROMPT = """你是一位专业的考古学家和博物馆策展人。-从文本中提取全面的文物信息:-1. artifact_name:文物官方名称-2. material:材料成分-3. excavation_year:发现年份-4. excavation_location:出土地点-5. current_museum:当前位置/博物馆-6. dimensions:物理尺寸-7. symbolic_meaning:文化意义-8. historical_period:历史时期/朝代+_PROMPT = """你是一位专业的考古学家。从文本中提取文物信息。-仅提取文本中明确提及的信息。+字段指南:+1. **artifact_name**:文物名称+2. **period**:所属的历史时期+3. **location**:合并出土地点和目前馆藏地+4. **physical_traits**:描述材质、大小和制作工艺+5. **significance**:描述文物的历史价值、用途和象征意义++仅提取明确提及的信息。### 源文本:"""@@ -62,7 +57,7 @@ class CulturalArtifactRegistry(AutoSet[ArtifactSchema]):def show(self, *, top_k_for_search: int = 3, top_k_for_chat: int = 3) -> None:def label_extractor(item: ArtifactSchema) -> str:- period = f" ({item.historical_period})" if item.historical_period else ""+ period = f" ({item.period})" if item.period else ""return f"{item.artifact_name}{period}"super().show(item_label_extractor=label_extractor,diff --git a/hyperextract/templates/zh/history/diplomatic_event_hypergraph.py b/hyperextract/templates/zh/history/diplomatic_event_hypergraph.pyindex 29ca583..a87b1ff 100644--- a/hyperextract/templates/zh/history/diplomatic_event_hypergraph.py+++ b/hyperextract/templates/zh/history/diplomatic_event_hypergraph.py@@ -17,20 +17,19 @@ class DiplomaticEventSchema(BaseModel):hyperedge_id: str = Field(..., description="唯一标识符")event_type: str = Field(..., description="'条约'、'会议'、'联盟'等")event_name: str = Field(..., description="事件名称,如'凡尔赛条约'")- signing_date: Optional[str] = Field(None, description="事件日期")member_countries: List[str] = Field(default_factory=list, description="所有参与国")- key_terms: Optional[str] = Field(None, description="关键条款摘要")- leading_country: Optional[str] = Field(None, description="主导或发起国")+ agreement_details: Optional[str] = Field(None, description="签署日期及协议关键条款摘要。")+ outcome: Optional[str] = Field(None, description="该外交事件导致的操作、结果或主导国。")_PROMPT = """从文本中提取节点(国家)和超边(外交事件)。-超边连接参与单一事件的多个国家。+规则:将日期、条款合并至 **agreement_details**,将影响、结果及发起国合并至 **outcome**。### 源文本:"""_NODE_PROMPT = """提取文本中提到的所有国家/民族名称。"""-_EDGE_PROMPT = """提取涉及多个国家的外交事件。为每个事件在member_countries字段列出所有参与国。"""+_EDGE_PROMPT = """提取外交事件及其详细背景(日期、条款、结果)。仅连接存在的国家。"""class DiplomaticEventHypergraph(AutoHypergraph[CountrySchema, DiplomaticEventSchema]):"""适用于:条约、国际会议记录、外交史