Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.
docs: 更新中英文模板开发手册内容与结构
yifanfeng97db7868344e26
diff --git a/hyperextract/templates/en/INSTRUCTION.md b/hyperextract/templates/en/INSTRUCTION.mdindex db6bb88..4461823 100644--- a/hyperextract/templates/en/INSTRUCTION.md+++ b/hyperextract/templates/en/INSTRUCTION.md@@ -1,306 +1,437 @@-# Hyper-Extract Template Development & Master Prompt Protocol+# Hyper-Extract Knowledge Template Definition Manual-This document defines the standard workflow for implementing domain-specific knowledge extraction templates in the `Hyper-Extract` framework.+This document defines the standard-specific knowledge extraction templates workflow for implementing domain in the `Hyper-Extract` framework.-## 0. Core Protocol: Source-First+---++## 0. Core Protocol: Read the Source++Before writing any code, you **MUST**:+1. **Identify the Base Class**: Choose the appropriate base class from the mapping table below.+2. **Read the Source**: Use tools to read the Python source code of the chosen base class in `hyperextract/types/` directory.++----Before writing any code, you MUST:-1. **Identify the Base Class**: Choose the appropriate base class from the mapping table below.-2. **Read the Source**: Use tools to read the Python source code of the chosen base class (located in `hyperextract/types/`).- * *Reason*: Source code is the source of truth for `__init__` parameters, `show` method signatures, and generic constraints.+## 1. Design Phase-## 1. Design Phase: Feasibility & Selection+### 1.1 Document-First Protocol-### Document-First ProtocolBefore designing any template, you **MUST** answer the following:-* **What is the target document?**: Which core document type(s) in this domain is the template designed for? (e.g., Annual Reports, SOP Manuals, Court Filings, HACCP Safety Plans).-* **Is the logic structure native to the text?**: Does this structure naturally exist in the original document, or is it artificially imposed? (Reject designs for "imagined knowledge structures").+* **What is the target document?**: Which core document type(s) in this domain is the template designed for? (e.g., Annual Reports, SOP Manuals, Court Rulings).+* **Is the logic structure native to the text?**: Does this structure naturally exist in the original document, or is it artificially imposed?* **Is extraction evidence clear?**: Are there explicit linguistic cues in the text that allow the LLM to extract accurately?Never design templates for abstract knowledge graphs disconnected from real documents. Templates must map the **inherent logical structures** of actual text.-### The Extractability Rule-Before designing a Schema, ask yourself:-* **Evidence Availability**: Does the input text explicitly contain evidence for this field? (Do not design fields for dynamic data typically found in external databases).-* **Structural Fit**: What is the most natural form for this data? (e.g., Unordered repeating patterns, unique set, or complex N-ary relations?)--### Mapping Table for Base Class Selection+### 1.2 AutoType Selection Mapping Table| Data Nature | Recommended Base Class | Source Code Location | Key Constraints || :--- | :--- | :--- | :--- || **Single Object** (Summary/Meta) | `AutoModel` | `hyperextract/types/model.py` | One object per document || **Pattern Collection** (Repeating) | `AutoList` | `hyperextract/types/list.py` | No deduplication. Extracts all instances found. |-| **Key-Based Accumulator** (Glossary) | `AutoSet` | `hyperextract/types/set.py` | Information Accumulation by Exact Key; requires `key_extractor` |-| **Binary Graph** (Entity-Relation) | `AutoGraph` | `hyperextract/types/graph.py` | Standard binary relationships |-| **Temporal Graph** (Timestamps) | `AutoTemporalGraph` | `hyperextract/types/temporal_graph.py` | Edges MUST have time fields |-| **Spatial Graph** (Locations) | `AutoSpatialGraph` | `hyperextract/types/spatial_graph.py` | Nodes/Edges MUST have location/coords |-| **Spatio-Temporal Graph** | `AutoSpatioTemporalGraph` | `hyperextract/types/spatio_temporal_graph.py` | Tracks movement and evolution in space/time |-| **N-ary/Complex Events** | `AutoHypergraph` | `hyperextract/types/hypergraph.py` | Hyperedge connects N nodes |-----+| **Key-Based Accumulator** (Glossary) | `AutoSet` | `hyperextract/types/set.py` | Information accumulation by exact key; requires `key_extractor` |+| **Standard Graph** (Entity-Relation) | `AutoGraph` | `hyperextract/types/graph.py` | Standard binary relationships |+| **Temporal Graph** (With Time) | `AutoTemporalGraph` | `hyperextract/types/temporal_graph.py` | Edges support flexible time formats |+| **Spatial Graph** (With Location) | `AutoSpatialGraph` | `hyperextract/types/spatial_graph.py` | Edges support flexible location formats |+| **Spatio-Temporal Graph** | `AutoSpatioTemporalGraph` | `hyperextract/types/spatio_temporal_graph.py` | Supports both flexible time and location |+| **N-ary/Complex Events** | `AutoHypergraph` | `hyperextract/types/hypergraph.py` | Models complex relationships among multiple entities |-## 1.1 Special Guidance: AutoSet (Key-Based Accumulation)+### 1.3 AutoHypergraph Application Scenarios-The `AutoSet` base class is designed for building **deduplicated, enriched knowledge collections** through **exact key matching**.-It is fundamentally different from `AutoList` (which has no deduplication) and from semantic clustering/embedding-based merging.+#### Core Definition+Hyperedges are used to model complex relationships among multiple entities, breaking through the limitations of traditional binary relationships by connecting multiple related entities through a single hyperedge.-### How AutoSet Works+#### Core Value+- Describes events or stories involving multiple entities participating together+- Maintains event integrity, avoiding information loss from splitting into multiple binary relationships+- Better aligns with human cognition of "events" (multiple participants, multiple elements)-**Core Mechanism**:-- Defines a `key_extractor` function that maps each item to a unique identifier (e.g., `key_extractor=lambda x: x.name.strip().lower()`).-- When `feed_text()` is called, the framework extracts items and groups them by their keys.-- **All items with the same key are automatically merged into one comprehensive entry**.-- The **`embedder` parameter is NOT used for merging logic**; it is only used for semantic search and knowledge graph visualization.+#### Typical Application Scenarios+- **Meeting Scenario**: Connect attendees, topics, location, time, decision outcomes+- **Transaction Scenario**: Connect buyer, seller, product, amount, time, location+- **Case Scenario**: Connect suspects, victims, witnesses, time, location, evidence+- **Competition Scenario**: Connect teams, players, event items, time, location, results-**Example Scenario**:-```python-from hyperextract.templates.food.culinary_dish import CulinaryDishSet+----dishes = CulinaryDishSet(llm_client=..., embedder=...)+## 2. Schema Design Specifications-# Text 1: Extract basic dish info-dishes.feed_text("Kung Pao Chicken is a Sichuan dish with peanuts and chilies.")-# Result: {name: "kung pao chicken", cuisine: "Sichuan", primary_ingredients: "peanuts, chilies"}+### 2.1 Core Principles+- **Field Count Control**: No more than 10 core fields+- **All Fields Must Have `description`**+- **Code Identifiers in English**: Class names, variable names, method names must be in English+- **All Descriptions in English**: For templates in the `en` directory, all field descriptions, comments, and Prompts MUST be in English-# Text 2: Add complementary details about the same dish-dishes.feed_text("Kung Pao Chicken is stir-fried rapidly, creating a sweet and spicy flavor.")-# Auto-merged: {name: "kung pao chicken", cuisine: "Sichuan", primary_ingredients: "peanuts, chilies", flavor_profile: "sweet and spicy"}+### 2.2 Naming Conventions+- Class names: `PascalCase` (e.g., `FinancialReportGraph`)+- Variable/Method names: `camelCase` (e.g., `nodeLabelExtractor`)-dishes.show() # Shows the merged, enriched entry+### 2.3 Example+```python+class FinancialEntity(BaseModel):+ """Financial entity node"""+ name: str = Field(description="Entity name, such as company name, product name, department name")+ category: str = Field(description="Entity type: company, product, department")+ description: str = Field(description="Brief description", default="")++class FinancialRelation(BaseModel):+ """Financial relation edge"""+ source: str = Field(description="Source entity")+ target: str = Field(description="Target entity")+ relationType: str = Field(description="Relation type: investment, acquisition, cooperation, competition")+ timeInfo: Optional[str] = Field(+ description="Time info, unified format is YYYY-MM-DD (e.g., 2023-06-15)",+ default=None+ )```-**Key Design Principles**:-1. **Exact Key Matching**: The `key_extractor` defines what makes items "the same". Only items with identical keys are merged.-2. **Information Accumulation**: Merging combines and enriches all attributes from multiple mentions of the same item.-3. **No Semantic Similarity**: Unlike clustering, AutoSet does NOT group similar-but-different items (e.g., "Kung Pao Chicken" and "Gong Bao Chicken" with different keys remain separate).-4. **LLM Responsibility**: The LLM's extraction prompt should normalize/standardize names to ensure correct grouping by key.+### 2.4 Spatio-Temporal Format Consistency Principle-**Embedder Role**:-- **NOT used for deduplication**. The `embedder` is used for:- - Semantic retrieval during chat/search queries- - Visualizing relationships in the knowledge graph- - Future question-answering capabilities+#### Within a Single Template: Strict Consistency+Within the same knowledge template, time formats and spatial formats must be strictly consistent. All extracted spatio-temporal information must be standardized and unified during the information extraction phase to ensure data standardization and consistency, avoiding confusion during LLM processing.----+**Important Note**: The standard format used by the template MUST be explicitly specified in the Prompt. The LLM must be required to convert all time/spatial information to the specified standard format for output, rather than preserving the various expressions from the original text.-## 2. Implementation Rules+#### Across Different Templates: Flexible Adaptation+Time and spatial formats across different knowledge templates can be flexibly defined based on specific domain requirements, but each template must unify one standard format. Here are format suggestions for common domains (for reference only):+- **History Domain**: Suggested format is year (e.g., "2023") or dynasty (e.g., "Qing Dynasty")+- **Finance Domain**: Suggested format is YYYY-MM-DD (e.g., "2023-06-15")+- **Cooking Domain**: Suggested format is MM:SS (e.g., "30:00")+- **Geography Domain**: Suggested format is Province-City-District (e.g., "Beijing-Chaoyang")-### A. Prompt Definition-* **Mandatory Constant**: Define `_PROMPT` (a multi-line string) outside the class.-* **Content**: Clearly define the expert persona and extraction logic. Mention specific formatting rules if necessary.-* **Graph/Hypergraph Two-Stage Support**: If your template inherits from `AutoGraph`, `AutoHypergraph`, `AutoTemporalGraph`, `AutoSpatialGraph`, or `AutoSpatioTemporalGraph`, you **MUST define three separate prompts** to support both extraction modes:- 1. `_PROMPT`: For "one_stage" (extract Nodes & Edges simultaneously, faster).- 2. `_NODE_PROMPT`: For "two_stage" step 1 (extract Nodes only, foundations).- 3. `_EDGE_PROMPT`: For "two_stage" step 2 (extract Edges/Hyperedges given existing Nodes, more precise).-- Pass these to `super().__init__` as:- ```python- super().__init__(- ...,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- ...- )- ```--### B. Class Structure-* **Schemas**: All Pydantic fields MUST include a `description` attribute. This is vital for the LLM to understand the target.-* **Documentation**:- * **Class Docstring**:- * **Mandatory Declaration (First Line)**: At the **very beginning** of the class docstring, you **MUST** declare the **applicable document types** using this format:- ```- Applicable to: [List specific document types, e.g., "SEC 10-K Item 1A, Prospectus Filings"]- ```- * High-level functional description.- * A usage **Example** showing how to instantiate and use the template.- * **Method Docstrings**: The `__init__` and `show` methods MUST include standard Google-style docstrings with detailed `Args` descriptions for every parameter.-* **Parameter Accuracy**: Verify that every argument in your `__init__` exists in the base class. Common mistake: `extraction_mode` exists in `AutoGraph` but NOT in `AutoSet`.-* **Initialization**: Explicitly list parameters (`llm_client`, `embedder`, etc.) and pass the prompt to `super().__init__(..., prompt=_TEMPLATE_PROMPT, ...)`.-* **Visualization (`show`)**: YOU MUST override the `show` method.- * **Parameter Constraint**: **DO NOT** include `label_extractor` parameters (e.g., `node_label_extractor`) in the template's `show` method signature.- * **Implementation**: You should define the best **frontend visualization labels** and their extraction logic for your specific Schema internally within `show` and pass them to `super().show(...)`. This ensures users get the best visualization out-of-the-box by simply calling `template.show()`.+**Note**: Format selection should be based on the actual information density and domain conventions of the target document, not over-design.----## 3. Standard Skeleton+## 3. AutoType Specific Specifications-```python-from typing import Any, Callable-from langchain_core.language_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from pydantic import BaseModel, Field-from hyperextract.types import ... # Import relevant base class+### 3.1 AutoTemporalGraph (Temporal Graph)-# 1. Define Schemas-class ItemSchema(BaseModel):- name: str = Field(..., description="Name of the entity")- ...+#### Required Extractors+- `node_key_extractor`: Unique entity identifier (e.g., `lambda x: x.name`)+- `edge_key_extractor`: Core relation identifier (excluding time)+- `time_in_edge_extractor`: Function to extract time from Edge+- `nodes_in_edge_extractor`: Function to extract source/target nodes from Edge-# 2. Define Prompt-_PROMPT = """-You are an expert in [Domain]. Your task is to extract [Structure] from text...-"""+#### Observation Time Parameter+- User can specify, or defaults to current date+- Used for resolving relative time expressions-# 3. Define Class-class MyTemplate(AutoType[ItemSchema]): # Replace with actual base class (AutoList, AutoSet, etc.)- """Google Style Docstring."""+#### Prompt Must Include Time Resolution Rules+```+### Time Format Requirements+All time information must be unified to "YYYY-MM-DD" format (e.g., 2023-06-15).- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- chunk_size: int = 2048,- **kwargs: Any- ):- super().__init__(- item_schema=ItemSchema,- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- chunk_size=chunk_size,- **kwargs- )+### Time Resolution Rules+Current Observation Date: {observation_time}- def show(- self,- *,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,- ):- # Define frontend visualization labels internally- def my_label_extractor(item: ItemSchema) -> str:- return item.name+1. Relative time resolution (based on observation date):+ - "last year" → year before {observation_time}, formatted as YYYY-01-01+ - "last month" → month before {observation_time}, formatted as YYYY-MM-01+ - "June 2023" → 2023-06-15- super().show(- item_label_extractor=my_label_extractor,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,- )+2. Exact time → convert to YYYY-MM-DD format+3. Missing time → leave empty```-----## 4. Runtime Behavior & Usage Guide+### 3.2 AutoSpatialGraph (Spatial Graph)-### Automatic Extraction+#### Required Extractors+- `node_key_extractor`, `edge_key_extractor`+- `location_in_edge_extractor`: Function to extract location from Edge+- `nodes_in_edge_extractor`-After calling the `feed_text()` method, the Hyper-Extract framework will **automatically and immediately** process the text and execute knowledge extraction:+#### Prompt Must Include Location Resolution Rules+```+### Location Resolution Rules+Current Observation Location: {observation_location}-```python-template = MyTemplate(llm_client=..., embedder=...)+1. Relative location resolution (based on observation location):+ - "here", "local" → {observation_location}+ - "nearby", "adjacent" → vicinity of {observation_location}+ - "north of here" → north of {observation_location}++2. Exact location → keep as-is+3. Missing location → leave empty+```-# 1. Input text-template.feed_text("Your input text here...")+----# 2. Framework handles it automatically! No need to call extract()-# - Text automatically chunked-# - Schemas automatically extracted-# - Deduplication and relationships established automatically+### 3.3 AutoSet (Key-Based Accumulator)-# 3. Directly view results or visualize-print(template.items) # View extracted items-template.show() # Visualize knowledge graph-```+- Must define `key_extractor` (exact key matching, not semantic similarity)+- Embedder is only used for semantic retrieval, not for merging logic-**Key Points**:-- `feed_text()` action automatically triggers the full extraction pipeline-- **No need to call `extract()` method** (this is an internal implementation detail)-- Supports method chaining: `template.feed_text(...).show()`-- Supports accumulation: multiple calls to `feed_text()` accumulate knowledge+----### Custom Extraction Mode+## 4. Prompt Construction Specifications-For `AutoGraph` series templates, you can choose the extraction strategy during initialization:+### 4.1 Fully Predefined+- Users do not need to write any Prompt+- All Prompts are predefined and encapsulated-```python-# One-stage: Extract nodes and edges simultaneously (faster)-template = MyGraph(llm_client=..., embedder=..., extraction_mode="one_stage")+### 4.2 Graph Types Require 3 Prompts+| Prompt | Usage |+|-------|------|+| `_PROMPT` | one_stage mode: extract nodes and edges simultaneously |+| `_NODE_PROMPT` | two_stage step 1: extract nodes only |+| `_EDGE_PROMPT` | two_stage step 2: extract edges based on known nodes |-# Two-stage: Extract nodes first, then edges (more accurate)-template = MyGraph(llm_client=..., embedder=..., extraction_mode="two_stage")-```+---++## 5. Parameter Management Specifications++### 5.1 Standard Exposed Parameters+| Parameter | Type | Required | Description |+|-----|------|------|------|+| `llm_client` | `BaseChatModel` | ✓ | LLM client |+| `embedder` | `Embeddings` | ✓ | Embedding model |+| `extraction_mode` | `str` | ✗ | Extraction mode (graph types only), default `"two_stage"` |+| `verbose` | `bool` | ✗ | Verbose logging, default `False` |+### 5.2 Optional Class-Specific Parameters+| Parameter | Applicable Types | Description |+|-----|---------|------|+| `observation_time` | `AutoTemporalGraph`, `AutoSpatioTemporalGraph` | Observation time, defaults to current date if not specified |+| `observation_location` | `AutoSpatialGraph`, `AutoSpatioTemporalGraph` | Observation location |+| `max_workers` | All types | Maximum worker threads |++### 5.3 Hidden Parameters (Passed via **kwargs)+- `chunk_size`, `chunk_overlap`+- `node_strategy_or_merger`, `edge_strategy_or_merger`+- Other technical parameters----## 4. Runtime Behavior & Usage Guide+## 6. Show Function Design Specifications-### Automatic Extraction+```python+def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+):+ """+ Display the knowledge graph.++ Args:+ top_k_for_search: Number of nodes/edges returned for semantic search, default is 3+ top_k_for_chat: Number of nodes/edges used for Q&A, default is 3+ """+ def nodeLabelExtractor(node: MyNode) -> str:+ return node.name # Simple label, not unique identifier, friendly for display++ def edgeLabelExtractor(edge: MyEdge) -> str:+ return edge.relationType++ super().show(+ node_label_extractor=nodeLabelExtractor,+ edge_label_extractor=edgeLabelExtractor,+ top_k_for_search=top_k_for_search,+ top_k_for_chat=top_k_for_chat,+ )+```-After calling the `feed_text()` method, the Hyper-Extract framework will **automatically and immediately** process the text and execute knowledge extraction:+---++## 7. Standard Example Skeleton```python-template = MyTemplate(llm_client=..., embedder=...)+from typing import Any, Callable, Optional+from datetime import datetime+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from pydantic import BaseModel, Field+from hyperextract.types import AutoTemporalGraph++# ==============================================================================+# 1. Schema (English identifiers, ≤ 10 fields, English descriptions)+# ==============================================================================++class FinancialEntity(BaseModel):+ """Financial entity node"""+ name: str = Field(description="Entity name, such as company name, product name, department name")+ category: str = Field(description="Entity type: company, product, department")+ description: str = Field(description="Brief description", default="")++class FinancialRelation(BaseModel):+ """Financial relation edge"""+ source: str = Field(description="Source entity")+ target: str = Field(description="Target entity")+ relationType: str = Field(description="Relation type: investment, acquisition, cooperation, competition")+ timeInfo: Optional[str] = Field(+ description="Time info, unified format is YYYY-MM-DD (e.g., 2023-06-15)",+ default=None+ )+ details: str = Field(description="Detailed description", default="")-# 1. Input text-template.feed_text("Your input text here...")+# ==============================================================================+# 2. Predefined Prompts (All in English)+# ==============================================================================-# 2. Framework handles it automatically! No need to call extract()-# - Text automatically chunked-# - Schemas automatically extracted-# - Deduplication and relationships established automatically+_NODE_PROMPT = """+You are a professional financial analyst. Extract all key entities as nodes.-# 3. Directly view results or visualize-print(template.items) # View extracted items-template.show() # Visualize knowledge graph-```+### Extraction Rules+1. Extract all entities such as companies, products, departments+2. Assign type for each entity: company, product, department+3. Keep entity names consistent with the source text+4. **NEVER extract time or location as independent nodes**-**Key Points**:-- `feed_text()` action automatically triggers the full extraction pipeline-- **No need to call `extract()` method** (this is an internal implementation detail)-- Supports method chaining: `template.feed_text(...).show()`-- Supports accumulation: multiple calls to `feed_text()` accumulate knowledge+### Source Text:+"""-### Custom Extraction Mode+_EDGE_PROMPT = """+You are a professional financial analyst. Extract relationships between given entities.-For `AutoGraph` series templates, you can choose the extraction strategy during initialization:+### Time Format Requirements+All time information must be unified to "YYYY-MM-DD" format (e.g., 2023-06-15).-```python-# One-stage: Extract nodes and edges simultaneously (faster)-template = MyGraph(llm_client=..., embedder=..., extraction_mode="one_stage")+### Time Resolution Rules+Current Observation Date: {observation_time}-# Two-stage: Extract nodes first, then edges (more accurate)-template = MyGraph(llm_client=..., embedder=..., extraction_mode="two_stage")-```+1. Relative time resolution (based on observation date):+ - "last year" → year before {observation_time}, formatted as YYYY-01-01+ - "last month" → month before {observation_time}, formatted as YYYY-MM-01+ - "June 2023" → 2023-06-15-## 4. Runtime Behavior & Usage+2. Exact time → convert to YYYY-MM-DD format+3. Missing time → leave empty-### Automatic Extraction+### Constraints+1. Only extract edges from the known entity list below+2. Do NOT create entities not listed-Once the `feed_text()` method is called, the Hyper-Extract framework **automatically and immediately** processes the text and executes the knowledge extraction pipeline:+### Known Entity List:+"""-```python-template = MyTemplate(llm_client=..., embedder=...)+_PROMPT = """+You are a professional financial analyst. Extract entities and their relationships from text.-# 1. Input Text-template.feed_text("Your input text here...")+### Node Extraction Rules+1. Extract all entities such as companies, products, departments+2. **NEVER extract time or location as independent nodes**-# 2. Framework handles extraction automatically! No need to call extract()-# - Automatic Text Chunking-# - Automatic Schema Extraction-# - Automatic Deduplication / Relation Building+### Relationship Extraction Rules+Current Observation Date: {observation_time}-# 3. View Results or Visualize-print(template.items) # Access extracted items-template.show() # Visualize the graph-```+### Time Format Requirements+All time information must be unified to "YYYY-MM-DD" format (e.g., 2023-06-15).-**Key Points**:-- The `feed_text()` action automatically triggers the complete extraction pipeline.-- **Do NOT call the `extract()` method manually** (this is an internal implementation detail).-- Supports chain calling: `template.feed_text(...).show()`-- Supports accumulation: Multiple calls to `feed_text()` will accumulate knowledge.+1. Resolve relative time and convert to standard format+2. Convert exact time to YYYY-MM-DD format+3. Leave empty when time is missing-### Custom Extraction Mode+### Source Text:+"""-For `AutoGraph` family templates, you can choose the extraction strategy during initialization:+# ==============================================================================+# 3. Template Class+# ==============================================================================-```python-# One Stage: Extract Nodes and Edges simultaneously (Faster)-template = MyGraph(llm_client=..., embedder=..., extraction_mode="one_stage")+class FinancialReportGraph(AutoTemporalGraph[FinancialEntity, FinancialRelation]):+ """+ Applicable Documents: SEC 10-K/10-Q annual reports, quarterly reports++ Functionality:+ Extracts companies, products, departments and their relationships (investment, acquisition, cooperation, etc.)+ from financial reports, supporting flexible time formats.++ Usage Example:+ >>> template = FinancialReportGraph(llm_client=llm, embedder=embedder)+ >>> template.feed_text("...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ observation_time: str | None = None,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ Initialize financial report graph template.++ Args:+ llm_client: LLM client for knowledge extraction+ embedder: Embedding model for semantic search+ extraction_mode: Extraction mode, can be "one_stage" (extract nodes and edges simultaneously)+ or "two_stage" (extract nodes first, then edges), default is "two_stage"+ observation_time: Observation time for resolving relative time expressions,+ defaults to current date if not specified+ max_workers: Maximum worker threads, default is 10+ verbose: Enable verbose logging, default is False+ **kwargs: Other technical parameters passed to base class+ """+ if observation_time is None:+ observation_time = datetime.now().strftime("%Y-%m-%d")++ super().__init__(+ node_schema=FinancialEntity,+ edge_schema=FinancialRelation,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: f"{x.source}|{x.relationType}|{x.target}",+ time_in_edge_extractor=lambda x: x.timeInfo or "",+ nodes_in_edge_extractor=lambda x: (x.source, x.target),+ llm_client=llm_client,+ embedder=embedder,+ observation_time=observation_time,+ extraction_mode=extraction_mode,+ 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_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ Display the knowledge graph.++ Args:+ top_k_for_search: Number of nodes/edges returned for semantic search, default is 3+ top_k_for_chat: Number of nodes/edges used for Q&A, default is 3+ """+ def nodeLabelExtractor(node: FinancialEntity) -> str:+ return node.name++ def edgeLabelExtractor(edge: FinancialRelation) -> str:+ return edge.relationType++ super().show(+ node_label_extractor=nodeLabelExtractor,+ edge_label_extractor=edgeLabelExtractor,+ top_k_for_search=top_k_for_search,+ top_k_for_chat=top_k_for_chat,+ )+```++---++## 8. Runtime Behavior Description-# Two Stage: Extract Nodes first, then Edges (Higher Precision)-template = MyGraph(llm_client=..., embedder=..., extraction_mode="two_stage")+After calling `feed_text()`, the framework automatically processes the text and executes knowledge extraction:+```python+template = MyTemplate(llm_client=..., embedder=...)+template.feed_text("...") # Auto-trigger extraction+template.show() # Visualization```++Key Points:+- `feed_text()` automatically triggers the full pipeline, no need to call `extract()`+- Supports method chaining: `template.feed_text(...).show()`+- Supports accumulation: multiple calls to `feed_text()` accumulate knowledgediff --git a/hyperextract/templates/zh/INSTRUCTION.md b/hyperextract/templates/zh/INSTRUCTION.mdindex e56f4dc..44bf771 100644--- a/hyperextract/templates/zh/INSTRUCTION.md+++ b/hyperextract/templates/zh/INSTRUCTION.md@@ -1,30 +1,29 @@-# Hyper-Extract 模板开发与 Master Prompt 协议+# Hyper-Extract 知识模板定义手册本文档定义了在 `Hyper-Extract` 框架中实现特定领域知识抽取模板的标准工作流。-## 0. 核心协议:阅读源码 (Source-First Protocol)+---++## 0. 核心协议:阅读源码在编写任何代码之前,你**必须**:-1. **明确基类**:根据需求从下表中选择合适的基类。-2. **强制读码**:使用工具读取 `hyperextract/types/` 目录中对应基类的 Python 源码文件。- * *原因*:具体的 `__init__` 参数、`show` 方法签名和泛型约束以源码为准。+1. **明确基类**:根据需求从下表中选择合适的基类。+2. **强制读码**:使用工具读取 `hyperextract/types/` 目录中对应基类的 Python 源码文件。++----## 1. 设计阶段:可行性与选型+## 1. 设计阶段++### 1.1 文档源优先-### 文档源优先 (Document-First Protocol)在设计任何模板前,你**必须**明确回答以下问题:-* **目标文档是什么?**:该模板是为该领域的哪类核心文档而设计?(如年报、SOP 手册、法律判决书、食品安全计划书)。-* **文本逻辑是否原生?**:该结构是否在原始文档中自然存在,而非人为设计?(拒绝为"想当然的知识"设计结构)。+* **目标文档是什么?**:该模板是为该领域的哪类核心文档而设计?(如年报、SOP 手册、法律判决书)。+* **文本逻辑是否原生?**:该结构是否在原始文档中自然存在,而非人为设计?* **提取证据清晰吗?**:文本中是否有显式的线索让 LLM 能够准确提取?绝不设计为空中楼阁的知识图谱。模板必须映射真实文本的**已有逻辑结构**。-### 可提取性原则 (Extractability)-在设计 Schema 前自问:-* **证据可用性**:输入文本是否显式包含该字段的证据?(拒绝为外部数据库才有的动态数据设计字段)。-* **结构适配**:数据最自然的存在形式是什么?是无序重复、唯一集合还是复杂的多元关系?--### 选型映射表 (Mapping Table)+### 1.2 AutoType 选型映射表| 数据特性 | 推荐基类 | 核心源码位置 | 关键约束 || :--- | :--- | :--- | :--- |@@ -32,134 +31,364 @@| **模式集合** (重复提取) | `AutoList` | `hyperextract/types/list.py` | 不去重。提取文本中出现的所有模式实例 || **键值累加器** (术语/清单) | `AutoSet` | `hyperextract/types/set.py` | 按精确键累加信息,需定义 `key_extractor` || **标准图谱** (实体-关系) | `AutoGraph` | `hyperextract/types/graph.py` | 标准二元关系 |-| **时序图谱** (含时间戳) | `AutoTemporalGraph` | `hyperextract/types/temporal_graph.py` | 边必须包含时间字段 |-| **空间关系图谱** | `AutoSpatialGraph` | `hyperextract/types/spatial_graph.py` | 节点/边需包含位置坐标信息 |-| **时空演变图谱** | `AutoSpatioTemporalGraph` | `hyperextract/types/spatio_temporal_graph.py` | 同时描述空间移动与时间演变 |-| **多元/复杂事件** | `AutoHypergraph` | `hyperextract/types/hypergraph.py` | 超边连接 N 个节点 |+| **时序图谱** (含时间) | `AutoTemporalGraph` | `hyperextract/types/temporal_graph.py` | 边支持灵活时间格式 |+| **空间关系图谱** | `AutoSpatialGraph` | `hyperextract/types/spatial_graph.py` | 边支持灵活位置格式 |+| **时空演变图谱** | `AutoSpatioTemporalGraph` | `hyperextract/types/spatio_temporal_graph.py` | 同时支持灵活时间和位置 |+| **多元/复杂事件** | `AutoHypergraph` | `hyperextract/types/hypergraph.py` | 建模多个实体间的复杂关联关系 |----+### 1.3 AutoHypergraph 应用场景说明-## 1.1 特别说明:AutoSet(基于键值的信息累加)+#### 核心定义+超边用于建模多个实体间的复杂关联关系,突破传统二元关系的限制,通过单一超边连接多个相关实体。-`AutoSet` 基类专为构建**去重、富集的知识库**而设计,采用**精确键值匹配**机制。-它**完全不同于** `AutoList`(无去重)和基于语义聚类/嵌入相似度的合并方式。+#### 核心价值+- 描述多个实体共同参与的事件或故事+- 保持事件的完整性,避免拆分成多个二元关系造成信息丢失+- 更符合人类认知中的"事件"概念(多参与者、多要素)-### AutoSet 工作原理+#### 典型应用场景+- **会议场景**:连接参会者、议题、地点、时间、决策结果+- **交易场景**:连接买方、卖方、产品、金额、时间、地点+- **案件场景**:连接嫌疑人、受害者、证人、时间、地点、证据+- **赛事场景**:连接参赛队伍、选手、比赛项目、时间、地点、结果-**核心机制**:-- 定义一个 `key_extractor` 函数将每个条目映射到唯一标识符(如 `key_extractor=lambda x: x.name.strip().lower()`)。-- 调用 `feed_text()` 时,框架提取条目**并按键值分组**。-- **所有键值相同的条目自动合并为一条综合条目**。-- `embedder` 参数**不用于合并逻辑**,仅用于语义检索和知识图谱可视化。+---++## 2. Schema 设计规范++### 2.1 核心原则+- **字段数量控制**:不超过 10 个核心字段+- **所有字段必须有 `description`**+- **代码标识符全英文**:类名、变量名、方法名必须使用英文+- **描述全中文**:对于 `zh` 目录下的模板,所有字段描述、注释、Prompt 必须使用中文-**场景示例**:+### 2.2 命名规范+- 类名:`PascalCase`(如 `FinancialReportGraph`)+- 变量/方法名:`camelCase`(如 `nodeLabelExtractor`)++### 2.3 示例```python-from hyperextract.templates.food.culinary_dish import CulinaryDishSet+class FinancialEntity(BaseModel):+ """财务实体节点"""+ name: str = Field(description="实体名称,如公司名、产品名、部门名")+ category: str = Field(description="实体类型:公司、产品、部门")+ description: str = Field(description="简要描述", default="")++class FinancialRelation(BaseModel):+ """财务关系边"""+ source: str = Field(description="源实体")+ target: str = Field(description="目标实体")+ relationType: str = Field(description="关系类型:投资、收购、合作、竞争")+ timeInfo: Optional[str] = Field(+ description="时间信息,统一格式为年-月-日(如 2023-06-15)",+ default=None+ )+```-dishes = CulinaryDishSet(llm_client=..., embedder=...)+### 2.4 时空格式一致性原则-# 文本 1:提取菜肴基础信息-dishes.feed_text("宫保鸡丁是四川菜,用花生和干辣椒制作。")-# 结果:{name: "宫保鸡丁", cuisine: "四川", primary_ingredients: "花生,干辣椒"}+#### 单个模板内:严格一致+在同一个知识模板内部,时间格式和空间格式必须保持严格一致。所有提取出的时空信息应在信息提取阶段即完成标准化统一处理,确保数据的规范性和一致性,避免大模型处理时产生混乱。-# 文本 2:添加关于同一菜肴的补充信息-dishes.feed_text("宫保鸡丁是大火快速炒制,整体风味是甜辣鲜香。")-# 自动合并:{name: "宫保鸡丁", cuisine: "四川", primary_ingredients: "花生,干辣椒", flavor_profile: "甜辣鲜香"}+**重要说明**:在 Prompt 中必须明确指定该模板采用的标准格式,要求 LLM 将所有时间/空间信息统一转换为该标准格式输出,而非保留原文的多种表达。-dishes.show() # 显示合并后的富集条目+#### 不同模板间:灵活适配+不同知识模板之间的时间和空间格式可以根据具体领域需求灵活定义,但每个模板内部必须统一一种标准格式。以下是一些常见领域的格式建议(仅供参考):+- **历史领域**:建议格式为年份(如 "2023")或朝代(如 "清朝")+- **金融领域**:建议格式为年-月-日(如 "2023-06-15")+- **食谱领域**:建议格式为分:秒(如 "30:00")+- **地理领域**:建议格式为省-市-区(如 "北京-朝阳")++**注意**:格式的选择应基于目标文档的实际信息密度和领域惯例,而非过度设计。++---++## 3. 各 AutoType 特殊规范++### 3.1 AutoTemporalGraph(时序图谱)++#### 必须定义的提取器+- `node_key_extractor`: 实体唯一标识(如 `lambda x: x.name`)+- `edge_key_extractor`: 关系核心标识(不包含时间)+- `time_in_edge_extractor`: 从 Edge 中提取时间的函数+- `nodes_in_edge_extractor`: 从 Edge 中提取源/目标节点++#### Observation Time 参数+- 用户可指定,或自动默认当前日期+- 用于解析相对时间表达++#### Prompt 必须包含时间解析规则```+### 时间解析规则+当前观察日期: {observation_time}-**关键设计原则**:-1. **精确键值匹配**:`key_extractor` 定义什么是"同一个条目"。**只有**键值完全相同的条目才会合并。-2. **信息累加**:合并时**融合并丰富**来自多个信息源的所有属性。-3. **非语义相似性**:不同于聚类,AutoSet **不会**将语义相近但键值不同的条目分组(如"宫保鸡丁"和"宫爆鸡丁"如果被标准化为不同名称,会保持分离)。-4. **LLM 责任**:提取 Prompt 应确保名称标准化,以便 LLM 正确归组到同一键值下。+1. 相对时间解析(基于观察日期):+ - "去年" → {observation_time} 的前一年+ - "上月" → {observation_time} 的前一个月+ - "本季度" → {observation_time} 所在季度+ - "近期" → {observation_time} 最近 3 个月-**Embedder 的角色**:-- **不用于去重逻辑**,`embedder` 用于:- - 聊天/搜索查询时的语义检索- - 知识图谱中关系的可视化展示- - 未来的问答能力+2. 精确时间 → 保持原样+3. 时间缺失 → 留空,不要猜测+```----## 2. 实现规范 (Implementation Rules)+### 3.2 AutoSpatialGraph(空间图谱)++#### 必须定义的提取器+- `node_key_extractor`, `edge_key_extractor`+- `location_in_edge_extractor`: 从 Edge 中提取位置+- `nodes_in_edge_extractor`++#### Prompt 必须包含位置解析规则+```+### 位置解析规则+当前观察位置: {observation_location}++1. 相对位置解析(基于观察位置):+ - "这里"、"本地" → {observation_location}+ - "附近"、"相邻" → {observation_location} 周边+ - "北边" → {observation_location} 北方-### A. Prompt 定义-* **强制常数**:必须在类外部定义 `_PROMPT`(多行字符串)。-* **内容要求**:明确定义专家角色、提取逻辑。如果某些字段有特定的提取格式要求,请在 Prompt 中强调。-* **图谱/超图双阶段支持**:如果模板继承自 `AutoGraph`、`AutoHypergraph`、`AutoTemporalGraph`、`AutoSpatialGraph` 或 `AutoSpatioTemporalGraph`,你**必须定义三个独立的 Prompt** 以支持所有提取模式:- 1. `_PROMPT`: 用于 "one_stage"(同时提取节点和边,速度快)。- 2. `_NODE_PROMPT`: 用于 "two_stage" 第一步(仅提取节点,打基础)。- 3. `_EDGE_PROMPT`: 用于 "two_stage" 第二步(基于已有节点提取边/超边,更精准)。+2. 精确位置 → 保持原样+3. 位置缺失 → 留空+```++---++### 3.3 AutoSet(键值累加器)++- 必须定义 `key_extractor`(精确键值匹配,非语义相似)+- Embedder 仅用于语义检索,不用于合并逻辑++---++## 4. Prompt 构建规范++### 4.1 完全预定义+- 用户无需编写任何 Prompt+- 所有 Prompt 预先定义并封装++### 4.2 图类型需定义 3 个 Prompt+| Prompt | 用途 |+|-------|------|+| `_PROMPT` | one_stage 模式:同时提取节点和边 |+| `_NODE_PROMPT` | two_stage 第一步:仅提取节点 |+| `_EDGE_PROMPT` | two_stage 第二步:基于已知节点提取边 |++---++## 5. 参数管理规范++### 5.1 标准暴露参数+| 参数 | 类型 | 必填 | 说明 |+|-----|------|------|------|+| `llm_client` | `BaseChatModel` | ✓ | LLM 客户端 |+| `embedder` | `Embeddings` | ✓ | 嵌入模型 |+| `extraction_mode` | `str` | ✗ | 提取模式(仅图类型),默认 `"two_stage"` |+| `verbose` | `bool` | ✗ | 详细日志,默认 `False` |++### 5.2 可选特定类参数+| 参数 | 适用类型 | 说明 |+|-----|---------|------|+| `observation_time` | `AutoTemporalGraph`, `AutoSpatioTemporalGraph` | 观察时间,未指定时默认当前日期 |+| `observation_location` | `AutoSpatialGraph`, `AutoSpatioTemporalGraph` | 观察位置 |+| `max_workers` | 所有类型 | 最大工作线程数 |++### 5.3 隐藏参数(通过 **kwargs 传递)+- `chunk_size`, `chunk_overlap`+- `node_strategy_or_merger`, `edge_strategy_or_merger`+- 等其他技术参数++---++## 6. Show 函数设计规范++```python+def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+):+ """+ 展示知识图谱。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def nodeLabelExtractor(node: MyNode) -> str:+ return node.name # 简明 label,非唯一标识,展示友好- 在 `super().__init__` 中分别传递:- ```python- super().__init__(- ...,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- ...+ def edgeLabelExtractor(edge: MyEdge) -> str:+ return edge.relationType++ super().show(+ node_label_extractor=nodeLabelExtractor,+ edge_label_extractor=edgeLabelExtractor,+ top_k_for_search=top_k_for_search,+ top_k_for_chat=top_k_for_chat,)- ```--### B. 类结构-* **Schema**:所有 Pydantic 字段必须包含 `description` 属性,这是 LLM 理解抽取目标的关键。-* **文档注释 (Documentation)**:- * **类文档字符串 (Class Docstring)**:- * **强制声明(第一行)**:在类文档字符串的**最开头**,你**必须**用下列格式声明该模板的**适用文档类型**:- ```- Applicable to: [List specific document types, e.g., "SEC 10-K Item 1A, Prospectus Filings"]- ```- * 高层功能描述。- * 一个展示如何初始化和使用的 **示例 (Example)**。- * **方法文档字符串 (Method Docstring)**:`__init__` 和 `show` 方法必须包含标准的 Google 风格文档字符串,详细说明每个参数 (`Args`)。-* **参数准确性 (Parameter Accuracy)**:确保 `__init__` 中的每一个参数都在基类中存在。常见错误:`extraction_mode` 仅存在于 `AutoGraph` 系列中,**不存在**于 `AutoSet` 或 `AutoList` 中。-* **初始化 (`__init__`)**:显式列参数(`llm_client`, `embedder` 等),并正确调用 `super().__init__(..., prompt=_TEMPLATE_PROMPT, ...)`。-* **可视化 (`show`)**:必须覆盖 `show` 方法。- * **参数约束**:**禁止**在模板类的 `show` 方法签名中包含 `label_extractor` 参数。- * **实现要求**:你应该在 `show` 内部定义最适合该 Schema 的 **前端展示标签** 的提取函数,然后传给 `super().show(...)`。这样用户只需调用 `template.show()` 即可获得最佳效果。+```----## 3. 标准示例骨架 (Example Skeleton)+## 7. 标准示例骨架```python-from typing import Any, Callable+from typing import Any, Callable, Optional+from datetime import datetimefrom langchain_core.language_models import BaseChatModelfrom langchain_core.embeddings import Embeddingsfrom pydantic import BaseModel, Field-from hyperextract.types import ... # 导入对应基类+from hyperextract.types import AutoTemporalGraph++# ==============================================================================+# 1. Schema (英文标识符,≤ 10 个字段,全中文描述)+# ==============================================================================++class FinancialEntity(BaseModel):+ """财务实体节点"""+ name: str = Field(description="实体名称,如公司名、产品名、部门名")+ category: str = Field(description="实体类型:公司、产品、部门")+ description: str = Field(description="简要描述", default="")++class FinancialRelation(BaseModel):+ """财务关系边"""+ source: str = Field(description="源实体")+ target: str = Field(description="目标实体")+ relationType: str = Field(description="关系类型:投资、收购、合作、竞争")+ timeInfo: Optional[str] = Field(+ description="时间信息,统一格式为年-月-日(如 2023-06-15)",+ default=None+ )+ details: str = Field(description="详细描述", default="")-# 1. 定义 Schema-class ItemSchema(BaseModel):- name: str = Field(..., description="实体的名称")- ...+# ==============================================================================+# 2. 预定义 Prompt(全中文)+# ==============================================================================++_NODE_PROMPT = """+你是一位专业的财报分析专家。请从文本中提取所有关键实体作为节点。++### 提取规则+1. 提取所有公司、产品、部门等实体+2. 为每个实体指定类型:公司、产品、部门+3. 保持实体名称与原文一致+4. **禁止将时间或地点作为独立节点提取**++### 源文本:+"""++_EDGE_PROMPT = """+你是一位专业的财报分析专家。请从给定实体列表中提取实体之间的关系。++### 时间格式要求+所有时间信息必须统一转换为「年-月-日」格式(如 2023-06-15)。++### 时间解析规则+当前观察日期: {observation_time}++1. 相对时间解析(基于观察日期):+ - "去年" → {observation_time} 的前一年,格式化为 YYYY-01-01+ - "上月" → {observation_time} 的前一个月,格式化为 YYYY-MM-01+ - "2023年6月" → 2023-06-15++2. 精确时间 → 转换为年-月-日格式+3. 时间缺失 → 留空++### 约束条件+1. 仅从下方已知实体列表中提取边+2. 不要创建未列出的实体++### 已知实体列表:+"""-# 2. 定义 Prompt_PROMPT = """-你是一位[领域]专家。你的任务是从文本中提取[结构化知识]...+你是一位专业的财报分析专家。请从文本中提取实体和它们之间的关系。++### 节点提取规则+1. 提取所有公司、产品、部门等实体+2. **禁止将时间或地点作为独立节点提取**++### 关系提取规则+当前观察日期: {observation_time}++### 时间格式要求+所有时间信息必须统一转换为「年-月-日」格式(如 2023-06-15)。++1. 解析相对时间并转换为标准格式+2. 精确时间转换为年-月-日格式+3. 时间缺失时留空++### 源文本:"""-# 3. 定义模板类-class MyTemplate(AutoType[ItemSchema]): # 替换为 AutoList, AutoSet 等- """Google Style 类文档字符串。"""+# ==============================================================================+# 3. 模板类+# ==============================================================================++class FinancialReportGraph(AutoTemporalGraph[FinancialEntity, FinancialRelation]):+ """+ 适用文档: SEC 10-K/10-Q 财报、年报、季度报告++ 功能介绍:+ 从财报文档中提取公司、产品、部门等实体,以及它们之间的投资、收购、合作等关系,+ 支持灵活的时间格式。++ Example:+ >>> template = FinancialReportGraph(llm_client=llm, embedder=embedder)+ >>> template.feed_text("...")+ >>> template.show()+ """def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- chunk_size: int = 2048,- **kwargs: Any+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ observation_time: str | None = None,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,):+ """+ 初始化财报知识图谱模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ observation_time: 观察时间,用于解析相对时间表达,+ 如未指定则使用当前日期+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ if observation_time is None:+ observation_time = datetime.now().strftime("%Y-%m-%d")+super().__init__(- item_schema=ItemSchema,+ node_schema=FinancialEntity,+ edge_schema=FinancialRelation,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: f"{x.source}|{x.relationType}|{x.target}",+ time_in_edge_extractor=lambda x: x.timeInfo or "",+ nodes_in_edge_extractor=lambda x: (x.source, x.target),llm_client=llm_client,embedder=embedder,+ observation_time=observation_time,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,prompt=_PROMPT,- chunk_size=chunk_size,- **kwargs+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,)def show(@@ -167,99 +396,40 @@ class MyTemplate(AutoType[ItemSchema]): # 替换为 AutoList, AutoSet 等*,top_k_for_search: int = 3,top_k_for_chat: int = 3,- ):- # 在内部定义展示逻辑- def my_label_extractor(item: ItemSchema) -> str:- return item.name-+ ):+ """+ 展示知识图谱。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def nodeLabelExtractor(node: FinancialEntity) -> str:+ return node.name++ def edgeLabelExtractor(edge: FinancialRelation) -> str:+ return edge.relationType+super().show(- item_label_extractor=my_label_extractor, # 传给基类+ node_label_extractor=nodeLabelExtractor,+ edge_label_extractor=edgeLabelExtractor,top_k_for_search=top_k_for_search,top_k_for_chat=top_k_for_chat,)```-----## 4. 运行时行为与使用说明 (Runtime Behavior & Usage)--### 自动提取 (Automatic Extraction)--调用 feed_text() 方法后,Hyper-Extract 框架会**自动并立即**处理文本并执行知识抽取:--\\python-template = MyTemplate(llm_client=..., embedder=...)--# 1. 输入文本-template.feed_text('你的输入文本...')--# 2. 框架自动处理!无需显式调用 extract()-- - 文本自动分块- - Schema 自动抽取- - 去重/关系建立自动完成--# 3. 直接查看结果或可视化-print(template.items) # 查看提取的项目-template.show() # 可视化知识图谱-\-**关键点**:-- feed_text() 动作会自动触发完整的提取流水线-- **不需要调用 extract() 方法**(这是内部实现细节)-- 支持链式调用:template.feed_text(...).show()-- 支持累积:多次调用 feed_text() 会累加知识--### 自定义提取模式 (Custom Extraction Mode)--对于 AutoGraph 系列模板,可在初始化时选择提取策略:--\\python-- 一阶段:同时提取节点和边(速度快)-template = MyGraph(llm_client=..., embedder=..., extraction_mode='one_stage')--- 二阶段:先提取节点,再提取边(精度高)-template = MyGraph(llm_client=..., embedder=..., extraction_mode='two_stage')-\-------## 4. 运行时行为与使用说明 (Runtime Behavior & Usage)--### 自动提取 (Automatic Extraction)--调用 `feed_text()` 方法后,Hyper-Extract 框架会**自动并立即**处理文本并执行知识抽取:+## 8. 运行时行为说明+调用 `feed_text()` 后,框架会自动处理文本并执行知识抽取:```pythontemplate = MyTemplate(llm_client=..., embedder=...)--# 1. 输入文本-template.feed_text("你的输入文本...")--# 2. 框架自动处理!无需显式调用 extract()-# - 文本自动分块-# - Schema 自动抽取-# - 去重/关系建立自动完成--# 3. 直接查看结果或可视化-print(template.items) # 查看提取的项目-template.show() # 可视化知识图谱+template.feed_text("...") # 自动触发提取+template.show() # 可视化```-**关键点**:-- `feed_text()` 动作会自动触发完整的提取流水线-- **不需要调用 `extract()` 方法**(这是内部实现细节)+关键点:+- `feed_text()` 自动触发完整流水线,无需调用 `extract()`- 支持链式调用:`template.feed_text(...).show()`-- 支持累积:多次调用 `feed_text()` 会累加知识--### 自定义提取模式 (Custom Extraction Mode)--对于 `AutoGraph` 系列模板,可在初始化时选择提取策略:--```python-# 一阶段:同时提取节点和边(速度快)-template = MyGraph(llm_client=..., embedder=..., extraction_mode="one_stage")--# 二阶段:先提取节点,再提取边(精度高)-template = MyGraph(llm_client=..., embedder=..., extraction_mode="two_stage")-```+- 支持累积:多次调用 `feed_text()` 累加知识