Skip to content

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

feat: Add multiple examples demonstrating ListKnowledge and SetKnowledge functionalities

yifanfeng97c1422ce46373
diff --git a/examples/list_knowledge_multi_chunk_demo.py b/examples/list_knowledge_demo.py
similarity index 100%
rename from examples/list_knowledge_multi_chunk_demo.py
rename to examples/list_knowledge_demo.py
diff --git a/examples/list_operations_demo.py b/examples/list_operations_demo.py
new file mode 100644
index 0000000..132679d
--- /dev/null
+++ b/examples/list_operations_demo.py
@@ -0,0 +1,202 @@
+"""
+演示 ListKnowledge 的 Pythonic 列表操作
+
+这个示例展示了如何像使用 Python 原生 list 一样使用 ListKnowledge:
+- 索引访问和切片
+- 迭代和成员测试
+- 追加、插入和扩展
+- 删除和弹出元素
+- 查找和计数
+- 复制、反转和排序
+"""
+
+import sys
+from pathlib import Path
+
+# 添加项目根目录到 Python 路径
+project_root = Path(__file__).parent.parent
+sys.path.insert(0, str(project_root))
+
+import os
+from dotenv import load_dotenv
+from pydantic import BaseModel, Field
+from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+
+from hyperextract.knowledge.generic import ListKnowledge
+
+# 加载环境变量
+load_dotenv()
+
+
+# 定义一个简单的任务Schema
+class Task(BaseModel):
+ """项目任务"""
+
+ name: str = Field(description="任务名称")
+ priority: int = Field(description="优先级 (1-5)")
+ status: str = Field(description="状态: pending, in_progress, done")
+
+
+def main():
+ # 初始化 LLM 和 Embedder
+ llm = ChatOpenAI(
+ model="gpt-4o-mini",
+ api_key=os.getenv("OPENAI_API_KEY"),
+ base_url=os.getenv("OPENAI_BASE_URL"),
+ )
+
+ embedder = OpenAIEmbeddings(
+ api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_BASE_URL")
+ )
+
+ # 创建 ListKnowledge 实例
+ tasks = ListKnowledge(
+ item_schema=Task,
+ llm_client=llm,
+ embedder=embedder,
+ )
+
+ print("=" * 70)
+ print("ListKnowledge Pythonic 操作演示")
+ print("=" * 70)
+
+ # 1. 使用 append 添加任务
+ print("\n1. 使用 append() 添加任务:")
+ tasks.append(Task(name="实现用户登录", priority=5, status="done"))
+ tasks.append(Task(name="设计数据库", priority=4, status="done"))
+ tasks.append(Task(name="编写API文档", priority=3, status="in_progress"))
+ print(f" 已添加 {len(tasks)} 个任务")
+
+ # 2. 索引访问
+ print("\n2. 索引访问:")
+ print(f" 第一个任务: {tasks[0].name} (优先级 {tasks[0].priority})")
+ print(f" 最后一个任务: {tasks[-1].name} (状态: {tasks[-1].status})")
+
+ # 3. 切片
+ print("\n3. 切片操作:")
+ high_priority = tasks[:2]
+ print(f" 前两个高优先级任务:")
+ for task in high_priority:
+ print(f" - {task.name} (P{task.priority})")
+
+ # 4. 迭代
+ print("\n4. 遍历所有任务:")
+ for i, task in enumerate(tasks, 1):
+ print(f" {i}. {task.name} - {task.status}")
+
+ # 5. 使用列表推导式
+ print("\n5. 列表推导式 - 获取所有任务名称:")
+ task_names = [task.name for task in tasks]
+ print(f" {task_names}")
+
+ # 6. 成员测试
+ print("\n6. 成员测试 (in 操作符):")
+ test_task = Task(name="编写API文档", priority=3, status="in_progress")
+ print(f" 测试任务在列表中: {test_task in tasks}")
+
+ # 7. 插入任务
+ print("\n7. 使用 insert() 在开头插入紧急任务:")
+ tasks.insert(0, Task(name="修复生产BUG", priority=5, status="in_progress"))
+ print(f" 新的第一个任务: {tasks[0].name}")
+
+ # 8. 扩展多个任务
+ print("\n8. 使用 extend() 批量添加任务:")
+ new_tasks = [
+ Task(name="代码审查", priority=3, status="pending"),
+ Task(name="性能优化", priority=2, status="pending"),
+ ]
+ tasks.extend(new_tasks)
+ print(f" 现在共有 {len(tasks)} 个任务")
+
+ # 9. 查找和计数
+ print("\n9. 查找和计数:")
+ in_progress_count = sum(1 for t in tasks if t.status == "in_progress")
+ print(f" 进行中的任务数量: {in_progress_count}")
+
+ # 查找第一个 pending 任务的位置
+ for i, task in enumerate(tasks):
+ if task.status == "pending":
+ print(f" 第一个待处理任务位置: 索引 {i} - {task.name}")
+ break
+
+ # 10. 修改任务
+ print("\n10. 修改任务状态 (通过索引赋值):")
+ print(f" 修改前: {tasks[-1].name} - {tasks[-1].status}")
+ updated_task = tasks[-1]
+ updated_task.status = "done"
+ tasks[-1] = updated_task
+ print(f" 修改后: {tasks[-1].name} - {tasks[-1].status}")
+
+ # 11. 删除任务
+ print("\n11. 删除已完成的任务:")
+ print(f" 删除前共有 {len(tasks)} 个任务")
+ # 删除第一个任务
+ del tasks[0]
+ print(f" 删除后共有 {len(tasks)} 个任务")
+
+ # 12. Pop 操作
+ print("\n12. 使用 pop() 移除并返回任务:")
+ last_task = tasks.pop()
+ print(f" 弹出的任务: {last_task.name}")
+ print(f" 剩余 {len(tasks)} 个任务")
+
+ # 13. 复制
+ print("\n13. 创建任务列表的副本:")
+ tasks_backup = tasks.copy()
+ tasks_backup.append(Task(name="新任务", priority=1, status="pending"))
+ print(f" 原始列表: {len(tasks)} 个任务")
+ print(f" 副本列表: {len(tasks_backup)} 个任务")
+ print(" ✓ 副本是独立的")
+
+ # 14. 排序
+ print("\n14. 按优先级排序任务 (降序):")
+ tasks.sort(key=lambda t: t.priority, reverse=True)
+ print(" 排序后的任务列表:")
+ for task in tasks:
+ print(f" - P{task.priority}: {task.name}")
+
+ # 15. 反转
+ print("\n15. 反转任务列表:")
+ tasks.reverse()
+ print(" 反转后:")
+ for task in tasks:
+ print(f" - {task.name}")
+
+ # 16. 字符串表示
+ print("\n16. 字符串表示:")
+ print(f" repr: {repr(tasks)}")
+ print(f" str: {str(tasks)}")
+
+ # 17. 组合操作
+ print("\n17. 组合两个 ListKnowledge (+ 操作符):")
+ more_tasks = ListKnowledge(
+ item_schema=Task,
+ llm_client=llm,
+ embedder=embedder,
+ )
+ more_tasks.append(Task(name="部署到生产", priority=5, status="pending"))
+
+ combined = tasks + more_tasks
+ print(f" 原始任务: {len(tasks)} 个")
+ print(f" 新增任务: {len(more_tasks)} 个")
+ print(f" 组合后: {len(combined)} 个")
+
+ print("\n" + "=" * 70)
+ print("✨ 所有 Pythonic 操作演示完成!")
+ print("=" * 70)
+
+ # 总结
+ print("\n📝 主要特性总结:")
+ print(" ✓ 索引访问: tasks[0], tasks[-1]")
+ print(" ✓ 切片: tasks[1:3], tasks[:2]")
+ print(" ✓ 迭代: for task in tasks")
+ print(" ✓ 成员测试: task in tasks")
+ print(" ✓ 修改方法: append, extend, insert, remove, pop")
+ print(" ✓ 查询方法: index, count")
+ print(" ✓ 工具方法: copy, reverse, sort")
+ print(" ✓ 自动 schema 验证")
+ print(" ✓ 语义搜索能力 (继承自基类)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/set_knowledge_demo.py b/examples/set_knowledge_demo.py
new file mode 100644
index 0000000..cf3255f
--- /dev/null
+++ b/examples/set_knowledge_demo.py
@@ -0,0 +1,218 @@
+"""Set Knowledge Demo - Extracting unique skills from multiple job descriptions
+
+This example demonstrates how SetKnowledge automatically deduplicates
+extracted items based on a unique key field.
+"""
+
+import sys
+from pathlib import Path
+
+# 添加项目根目录到 Python 路径
+project_root = Path(__file__).parent.parent
+sys.path.insert(0, str(project_root))
+
+import os
+from pydantic import BaseModel, Field
+from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+
+from hyperextract.knowledge.generic.set import SetKnowledge, MergeItemStrategy
+
+
+# Define the schema for skills
+class SkillSchema(BaseModel):
+ """A skill mentioned in job descriptions"""
+
+ name: str = Field(
+ description="Name of the skill (e.g., 'Python', 'Machine Learning')"
+ )
+ category: str | None = Field(
+ None,
+ description="Category (e.g., 'Programming Language', 'Framework', 'Soft Skill')",
+ )
+ proficiency_level: str | None = Field(
+ None,
+ description="Required proficiency level if mentioned (e.g., 'Expert', 'Intermediate')",
+ )
+ description: str | None = Field(
+ None, description="Brief description or context of how the skill is used"
+ )
+
+
+def main():
+ # Initialize LLM and embeddings
+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
+ embedder = OpenAIEmbeddings(base_url=os.getenv("OPENAI_BASE_URL"))
+
+ # Create SetKnowledge with FIELD_MERGE strategy
+ # This means when the same skill appears multiple times,
+ # the new extraction will fill in any missing fields from the existing one
+ skills = SetKnowledge(
+ item_schema=SkillSchema,
+ llm_client=llm,
+ embedder=embedder,
+ unique_key="name", # Deduplicate based on skill name
+ merge_item_strategy=MergeItemStrategy.FIELD_MERGE,
+ prompt="""Extract all technical skills, frameworks, tools, and soft skills mentioned in the text.
+
+For each skill, provide:
+- name: The exact name of the skill
+- category: What type of skill it is
+- proficiency_level: If mentioned, the required level
+- description: Brief context about how it's used
+
+Be specific and extract all mentioned skills.""",
+ )
+
+ # Sample job descriptions (with overlapping skills)
+ job_descriptions = [
+ """
+ Senior Python Developer
+
+ We are seeking an expert Python developer with 5+ years of experience.
+
+ Requirements:
+ - Expert level Python programming
+ - Strong experience with FastAPI framework for building REST APIs
+ - Proficiency in PostgreSQL database design and optimization
+ - Experience with Docker for containerization
+ - Strong problem-solving and communication skills
+ - Experience with Git version control
+ """,
+ """
+ Full Stack Engineer
+
+ Join our dynamic team as a Full Stack Engineer!
+
+ Required Skills:
+ - Python for backend development (3+ years)
+ - React for frontend development
+ - Experience with FastAPI or Django
+ - PostgreSQL or MySQL database experience
+ - Docker and Kubernetes for deployment
+ - Excellent teamwork and communication abilities
+ - Git workflow knowledge
+ """,
+ """
+ Machine Learning Engineer
+
+ Looking for an ML Engineer to join our AI team.
+
+ Must Have:
+ - Advanced Python skills for ML development
+ - PyTorch or TensorFlow experience
+ - Strong understanding of machine learning algorithms
+ - Experience with Docker for model deployment
+ - PostgreSQL for data storage
+ - Git for code versioning
+ - Strong analytical and problem-solving skills
+ """,
+ ]
+
+ print("=" * 80)
+ print("SET KNOWLEDGE DEMO: Extracting Unique Skills from Job Descriptions")
+ print("=" * 80)
+
+ # Extract skills from all job descriptions
+ print("\n📄 Processing job descriptions...")
+ for i, job_desc in enumerate(job_descriptions, 1):
+ print(f"\n Processing job description {i}...")
+ skills.extract(job_desc)
+ print(f" ✓ Total unique skills so far: {len(skills)}")
+
+ # Display all unique skills
+ print("\n" + "=" * 80)
+ print(f"📊 EXTRACTED UNIQUE SKILLS: {len(skills)} total")
+ print("=" * 80)
+
+ # Group by category
+ skills_by_category = {}
+ for skill in skills.items:
+ category = skill.category or "Uncategorized"
+ if category not in skills_by_category:
+ skills_by_category[category] = []
+ skills_by_category[category].append(skill)
+
+ # Display organized results
+ for category, category_skills in sorted(skills_by_category.items()):
+ print(f"\n{category}:")
+ for skill in sorted(category_skills, key=lambda s: s.name):
+ print(f" • {skill.name}")
+ if skill.proficiency_level:
+ print(f" Level: {skill.proficiency_level}")
+ if skill.description:
+ print(f" Context: {skill.description}")
+
+ # Demonstrate set operations
+ print("\n" + "=" * 80)
+ print("🔍 DEMONSTRATING SET OPERATIONS")
+ print("=" * 80)
+
+ # Build index for semantic search
+ print("\nBuilding vector index for semantic search...")
+ skills.build_index()
+ print("✓ Index built successfully")
+
+ # Search for related skills
+ print("\n1. Semantic Search - Finding skills related to 'backend development':")
+ backend_skills = skills.search("backend development", top_k=5)
+ for skill in backend_skills:
+ print(f" • {skill.name}")
+ if skill.category:
+ print(f" Category: {skill.category}")
+
+ # Check if specific skills exist
+ print("\n2. Membership Testing:")
+ test_skills = ["Python", "Java", "Docker", "Rust"]
+ for skill_name in test_skills:
+ exists = skills.contains(skill_name)
+ status = "✓" if exists else "✗"
+ print(f" {status} {skill_name}: {'Found' if exists else 'Not found'}")
+
+ # Get specific skill details
+ print("\n3. Get Specific Skill Details:")
+ python_skill = skills.get("Python")
+ if python_skill:
+ print(f" Skill: {python_skill.name}")
+ print(f" Category: {python_skill.category}")
+ print(f" Level: {python_skill.proficiency_level or 'Not specified'}")
+ print(f" Description: {python_skill.description or 'No description'}")
+
+ # Save the extracted knowledge
+ print("\n" + "=" * 80)
+ print("💾 SAVING EXTRACTED KNOWLEDGE")
+ print("=" * 80)
+
+ save_path = "tmp/set_knowledge_demo"
+ skills.dump(save_path)
+ print(f"✓ Saved to: {save_path}")
+ print(" - state.json (structured data)")
+ print(" - faiss_index/ (vector index for semantic search)")
+
+ # Demonstrate loading
+ print("\n📂 Loading saved knowledge...")
+ loaded_skills = SetKnowledge(
+ item_schema=SkillSchema,
+ llm_client=llm,
+ embedder=embedder,
+ unique_key="name",
+ )
+ loaded_skills.load(save_path)
+ print(f"✓ Loaded {len(loaded_skills)} unique skills")
+
+ # Summary
+ print("\n" + "=" * 80)
+ print("📈 SUMMARY")
+ print("=" * 80)
+ print(f" Total unique skills extracted: {len(skills)}")
+ print(f" Job descriptions processed: {len(job_descriptions)}")
+ print(" Deduplication strategy: FIELD_MERGE")
+ print(" Unique key: 'name'")
+ print("\n ✓ Automatically deduplicated based on skill names")
+ print(" ✓ Merged information from multiple occurrences")
+ print(" ✓ Supports semantic search across all skills")
+ print(" ✓ Persistent storage with dump/load")
+ print("=" * 80)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/unit_knowledge_multi_chunk_demo.py b/examples/unit_knowledge_demo.py
similarity index 100%
rename from examples/unit_knowledge_multi_chunk_demo.py
rename to examples/unit_knowledge_demo.py
diff --git a/hyperextract/knowledge/base.py b/hyperextract/knowledge/base.py
index 186299a..a0fbf20 100644
--- a/hyperextract/knowledge/base.py
+++ b/hyperextract/knowledge/base.py
@@ -64,7 +64,9 @@ class BaseKnowledge(ABC, Generic[T]):
self.show_progress = show_progress
# Initialize prompt template and LLM chain for structured extraction
- self.prompt_template = ChatPromptTemplate.from_template(f"{self.prompt}{{chunk_text}}")
+ self.prompt_template = ChatPromptTemplate.from_template(
+ f"{self.prompt}{{chunk_text}}"
+ )
self.llm_with_schema = self.llm_client.with_structured_output(self._data_schema)
self.llm_chain_extract = self.prompt_template | self.llm_with_schema
@@ -85,6 +87,25 @@ class BaseKnowledge(ABC, Generic[T]):
"updated_at": datetime.now(),
}
+ def _create_new_instance(self) -> "BaseKnowledge[T]":
+ """Creates a new instance with the same configuration as this one.
+
+ Subclasses can override this method if they have special initialization requirements.
+
+ Returns:
+ A new knowledge instance with the same configuration.
+ """
+ return self.__class__(
+ data_schema=self._data_schema,
+ llm_client=self.llm_client,
+ embedder=self.embedder,
+ prompt=self.prompt,
+ chunk_size=self.chunk_size,
+ chunk_overlap=self.chunk_overlap,
+ max_workers=self.max_workers,
+ show_progress=self.show_progress,
+ )
+
@staticmethod
def _default_prompt() -> str:
"""Returns the default extraction prompt template."""
@@ -126,14 +147,14 @@ class BaseKnowledge(ABC, Generic[T]):
"""Clears the vector index without affecting the stored data."""
self._index = None
- # ==================== Extraction & Aggregation ====================
+ # ==================== Extraction & Merge ====================
@abstractmethod
def extract(self, text: str, *, store: bool = True) -> T:
- """Extracts structured knowledge from text with automatic chunking and aggregation.
+ """Extracts structured knowledge from text with automatic chunking and merging.
This is the main entry point for knowledge extraction. It handles the complete pipeline
- from text preprocessing to knowledge aggregation.
+ from text preprocessing to knowledge merging.
Extraction pipeline:
1. Determine if text chunking is needed based on length
@@ -141,7 +162,7 @@ class BaseKnowledge(ABC, Generic[T]):
3. Merge all extracted data using the merge() method
4. If store=True: merge with existing data and update internal state
5. If store=False: return extracted data without modifying internal state
- 6. Return the aggregated knowledge
+ 6. Return the merged knowledge
Args:
text: Input text to extract knowledge from (can be short or long).
@@ -150,7 +171,7 @@ class BaseKnowledge(ABC, Generic[T]):
- False: Temporary mode - return extracted data without modifying internal state
Returns:
- The extracted and aggregated knowledge data.
+ The extracted and merged knowledge data.
"""
pass
@@ -174,80 +195,6 @@ class BaseKnowledge(ABC, Generic[T]):
"""
pass
- def _create_new_instance(self) -> "BaseKnowledge[T]":
- """Creates a new instance with the same configuration as this one.
-
- Subclasses can override this method if they have special initialization requirements.
-
- Returns:
- A new knowledge instance with the same configuration.
- """
- return self.__class__(
- data_schema=self._data_schema,
- llm_client=self.llm_client,
- embedder=self.embedder,
- prompt=self.prompt,
- chunk_size=self.chunk_size,
- chunk_overlap=self.chunk_overlap,
- max_workers=self.max_workers,
- show_progress=self.show_progress,
- )
-
- def __add__(self, other: "BaseKnowledge[T]") -> "BaseKnowledge[T]":
- """Operator overload for '+' to merge two knowledge instances.
-
- Creates a new knowledge instance by merging the data from both instances.
- The new instance inherits configuration from the left operand (self).
-
- Usage:
- >>> kb1 = UnitKnowledge(PersonSchema, ...)
- >>> kb2 = UnitKnowledge(PersonSchema, ...)
- >>> kb3 = kb1 + kb2 # ✅ Same schema, creates merged instance
- >>>
- >>> kb4 = UnitKnowledge(CompanySchema, ...)
- >>> kb5 = kb1 + kb4 # ❌ TypeError: Different schemas
-
- Args:
- other: Another knowledge instance of the same type to merge with.
-
- Returns:
- A new knowledge instance containing merged data.
-
- Raises:
- TypeError: If other is not an instance of the same knowledge class or has different data schema.
- """
- # Check 1: Both must be instances of the same knowledge class
- if not isinstance(other, self.__class__):
- raise TypeError(
- f"Cannot add {type(other).__name__} to {type(self).__name__}. "
- f"Both operands must be instances of the same knowledge class."
- )
-
- # Check 2: Both must have the same data schema
- if self._data_schema != other._data_schema:
- raise TypeError(
- f"Cannot add knowledge instances with different data schemas. "
- f"Left schema: {self._data_schema.__name__}, "
- f"Right schema: {other._data_schema.__name__}. "
- f"Both operands must have the same data schema to be merged."
- )
-
- # Merge the data from both instances
- merged_data = self.merge([self._data, other._data])
-
- # Create a new instance with the same configuration
- new_instance = self._create_new_instance()
-
- # Set the merged data and update metadata
- new_instance._data = merged_data
- new_instance.metadata["created_at"] = min(
- self.metadata["created_at"], other.metadata["created_at"]
- )
- new_instance.metadata["updated_at"] = datetime.now()
- new_instance.clear_index() # Index needs to be rebuilt
-
- return new_instance
-
# ==================== Evolution ====================
def evolve(self, **kwargs) -> T:
@@ -297,18 +244,6 @@ class BaseKnowledge(ABC, Generic[T]):
"""
pass
- @abstractmethod
- def __len__(self) -> int:
- """Returns the number of knowledge items in the collection.
-
- Subclasses must implement this method to report their specific size metric.
- This enables using len() function on knowledge instances.
-
- Returns:
- The count of knowledge items.
- """
- pass
-
# ==================== Serialization ====================
@abstractmethod
@@ -340,3 +275,60 @@ class BaseKnowledge(ABC, Generic[T]):
folder_path: Source folder path containing saved knowledge.
"""
pass
+
+ # ==================== Operator Overloads ====================
+
+ def __add__(self, other: "BaseKnowledge[T]") -> "BaseKnowledge[T]":
+ """Operator overload for '+' to merge two knowledge instances.
+
+ Creates a new knowledge instance by merging the data from both instances.
+ The new instance inherits configuration from the left operand (self).
+
+ Usage:
+ >>> kb1 = UnitKnowledge(PersonSchema, ...)
+ >>> kb2 = UnitKnowledge(PersonSchema, ...)
+ >>> kb3 = kb1 + kb2 # ✅ Same schema, creates merged instance
+ >>>
+ >>> kb4 = UnitKnowledge(CompanySchema, ...)
+ >>> kb5 = kb1 + kb4 # ❌ TypeError: Different schemas
+
+ Args:
+ other: Another knowledge instance of the same type to merge with.
+
+ Returns:
+ A new knowledge instance containing merged data.
+
+ Raises:
+ TypeError: If other is not an instance of the same knowledge class or has different data schema.
+ """
+ # Check 1: Both must be instances of the same knowledge class
+ if not isinstance(other, self.__class__):
+ raise TypeError(
+ f"Cannot add {type(other).__name__} to {type(self).__name__}. "
+ f"Both operands must be instances of the same knowledge class."
+ )
+
+ # Check 2: Both must have the same data schema
+ if self._data_schema != other._data_schema:
+ raise TypeError(
+ f"Cannot add knowledge instances with different data schemas. "
+ f"Left schema: {self._data_schema.__name__}, "
+ f"Right schema: {other._data_schema.__name__}. "
+ f"Both operands must have the same data schema to be merged."
+ )
+
+ # Merge the data from both instances
+ merged_data = self.merge([self._data, other._data])
+
+ # Create a new instance with the same configuration
+ new_instance = self._create_new_instance()
+
+ # Set the merged data and update metadata
+ new_instance._data = merged_data
+ new_instance.metadata["created_at"] = min(
+ self.metadata["created_at"], other.metadata["created_at"]
+ )
+ new_instance.metadata["updated_at"] = datetime.now()
+ new_instance.clear_index() # Index needs to be rebuilt
+
+ return new_instance
diff --git a/hyperextract/knowledge/generic/__init__.py b/hyperextract/knowledge/generic/__init__.py
index a3d3851..2e4df7a 100644
--- a/hyperextract/knowledge/generic/__init__.py
+++ b/hyperextract/knowledge/generic/__init__.py
@@ -2,9 +2,12 @@
from .unit import UnitKnowledge
from .list import ListKnowledge, ItemListSchema
+from .set import SetKnowledge, MergeItemStrategy
__all__ = [
"UnitKnowledge",
"ListKnowledge",
"ItemListSchema",
+ "SetKnowledge",
+ "MergeItemStrategy",
]
diff --git a/hyperextract/knowledge/generic/list.py b/hyperextract/knowledge/generic/list.py
index 927adac..852345d 100644
--- a/hyperextract/knowledge/generic/list.py
+++ b/hyperextract/knowledge/generic/list.py
@@ -16,6 +16,7 @@ try:
from hyperextract.config import logger
except ImportError:
import logging
+
logger = logging.getLogger(__name__)
@@ -114,9 +115,9 @@ class ListKnowledge(BaseKnowledge[ItemListSchema[Item]], Generic[Item]):
def _create_new_instance(self) -> "ListKnowledge[Item]":
"""Creates a new instance with the same configuration as this one.
-
+
Overrides base class method to handle ListKnowledge's item_schema parameter.
-
+
Returns:
A new ListKnowledge instance with the same configuration.
"""
@@ -131,63 +132,6 @@ class ListKnowledge(BaseKnowledge[ItemListSchema[Item]], Generic[Item]):
show_progress=self.show_progress,
)
- def __add__(self, other):
- """Operator overload for '+' to combine knowledge instances.
-
- Supports multiple combination patterns:
- - ListKnowledge + ListKnowledge → ListKnowledge (merge lists)
- - ListKnowledge + UnitKnowledge → ListKnowledge (append unit to list)
-
- This enables chain operations like: unit1 + unit2 + unit3
-
- Args:
- other: Another ListKnowledge or UnitKnowledge with compatible schema.
-
- Returns:
- New ListKnowledge with combined items.
-
- Raises:
- TypeError: If schemas don't match or invalid operand type.
- """
- from .unit import UnitKnowledge
-
- # Case 1: ListKnowledge + ListKnowledge (call parent implementation)
- if isinstance(other, ListKnowledge):
- # Check schema compatibility
- if self.item_schema != other.item_schema:
- raise TypeError(
- f"Cannot add ListKnowledge instances with different schemas. "
- f"Left: {self.item_schema.__name__}, Right: {other.item_schema.__name__}"
- )
- # Use base class merge logic
- return super().__add__(other)
-
- # Case 2: ListKnowledge + UnitKnowledge → ListKnowledge (append unit)
- elif isinstance(other, UnitKnowledge):
- # Check schema compatibility
- if self.item_schema != other._data_schema:
- raise TypeError(
- f"Cannot add UnitKnowledge to ListKnowledge with different schemas. "
- f"List: {self.item_schema.__name__}, Unit: {other._data_schema.__name__}"
- )
-
- # Create new ListKnowledge with appended unit
- new_list = self._create_new_instance()
- new_list._data.items = self.items + [other._data]
-
- # Merge metadata
- new_list.metadata["created_at"] = min(
- self.metadata["created_at"], other.metadata["created_at"]
- )
- new_list.metadata["updated_at"] = datetime.now()
-
- return new_list
-
- else:
- raise TypeError(
- f"Unsupported operand type for +: 'ListKnowledge' and '{type(other).__name__}'"
- )
-
def extract(self, text: str, *, store: bool = True) -> ItemListSchema:
"""Extracts a list of items using LangChain native batch processing.
@@ -236,7 +180,7 @@ class ListKnowledge(BaseKnowledge[ItemListSchema[Item]], Generic[Item]):
self._data = self.merge([self._data, merged_data])
else:
self._data = merged_data
-
+
self.clear_index()
self.metadata["updated_at"] = datetime.now()
@@ -244,7 +188,7 @@ class ListKnowledge(BaseKnowledge[ItemListSchema[Item]], Generic[Item]):
logger.info(
f"Duration: {(datetime.now() - start_time).total_seconds():.2f} seconds"
)
-
+
# Return items list (either from stored data or temporary merged data)
return self.items if store else merged_data.items
@@ -332,10 +276,6 @@ class ListKnowledge(BaseKnowledge[ItemListSchema[Item]], Generic[Item]):
logger.info(f"Found {len(results)} results for query: {query[:50]}...")
return results
- def __len__(self) -> int:
- """Returns the number of elements in the list."""
- return len(self.items)
-
def dump(self, folder_path: str) -> Any:
"""Exports knowledge to a specified folder.
@@ -411,3 +351,555 @@ class ListKnowledge(BaseKnowledge[ItemListSchema[Item]], Generic[Item]):
self._index = None
logger.info(f"Loaded knowledge successfully with {len(self)} items")
+
+ # ==================== Pythonic Sequence Operations ====================
+
+ def __len__(self) -> int:
+ """Returns the number of elements in the list."""
+ return len(self.items)
+
+ def __getitem__(self, key):
+ """Support index access and slicing.
+
+ Args:
+ key: Integer index or slice object.
+
+ Returns:
+ - For integer index: Returns the Item at that position
+ - For slice: Returns a new ListKnowledge instance with sliced items
+
+ Raises:
+ IndexError: If index is out of range.
+ TypeError: If key is neither int nor slice.
+
+ Examples:
+ >>> knowledge[0] # First item
+ >>> knowledge[-1] # Last item
+ >>> knowledge[1:3] # New ListKnowledge with items [1:3]
+ >>> knowledge[:5] # First 5 items as new instance
+ """
+ if isinstance(key, int):
+ # Integer index: return Item directly
+ return self.items[key]
+ elif isinstance(key, slice):
+ # Slice: return new ListKnowledge instance
+ new_instance = self._create_new_instance()
+ new_instance._data.items = self.items[key]
+ new_instance.metadata["updated_at"] = datetime.now()
+ return new_instance
+ else:
+ raise TypeError(
+ f"List indices must be integers or slices, not {type(key).__name__}"
+ )
+
+ def __setitem__(self, index: int, item):
+ """Support index assignment.
+
+ Args:
+ index: Position to set (supports negative indexing).
+ item: The item to set at that position.
+
+ Raises:
+ TypeError: If item schema doesn't match.
+ IndexError: If index is out of range.
+
+ Examples:
+ >>> knowledge[0] = new_item
+ >>> knowledge[-1] = updated_item
+
+ Side Effects:
+ - Clears the vector index (needs rebuild)
+ - Updates metadata timestamp
+ """
+ self._validate_item_schema(item)
+ self._data.items[index] = item
+ self.clear_index()
+ self.metadata["updated_at"] = datetime.now()
+
+ def __add__(self, other):
+ """Operator overload for '+' to combine knowledge instances.
+
+ Supports multiple combination patterns:
+ - ListKnowledge + ListKnowledge → ListKnowledge (merge lists)
+ - ListKnowledge + UnitKnowledge → ListKnowledge (append unit to list)
+
+ This enables chain operations like: unit1 + unit2 + unit3
+
+ Args:
+ other: Another ListKnowledge or UnitKnowledge with compatible schema.
+
+ Returns:
+ New ListKnowledge with combined items.
+
+ Raises:
+ TypeError: If schemas don't match or invalid operand type.
+ """
+ from .unit import UnitKnowledge
+
+ # Case 1: ListKnowledge + ListKnowledge (call parent implementation)
+ if isinstance(other, ListKnowledge):
+ # Check schema compatibility
+ if self.item_schema != other.item_schema:
+ raise TypeError(
+ f"Cannot add ListKnowledge instances with different schemas. "
+ f"Left: {self.item_schema.__name__}, Right: {other.item_schema.__name__}"
+ )
+ # Manually merge without calling base class (to avoid _data_schema check)
+ # Create new instance with merged items
+ new_instance = self._create_new_instance()
+ new_instance._data.items = self.items + other.items
+ new_instance.metadata["created_at"] = self.metadata.get("created_at")
+ new_instance.metadata["updated_at"] = self.metadata.get("updated_at")
+ return new_instance
+
+ # Case 2: ListKnowledge + UnitKnowledge → ListKnowledge (append unit)
+ elif isinstance(other, UnitKnowledge):
+ # Check schema compatibility
+ if self.item_schema != other._data_schema:
+ raise TypeError(
+ f"Cannot add UnitKnowledge to ListKnowledge with different schemas. "
+ f"List: {self.item_schema.__name__}, Unit: {other._data_schema.__name__}"
+ )
+
+ # Create new ListKnowledge with appended unit
+ new_list = self._create_new_instance()
+ new_list._data.items = self.items + [other._data]
+
+ # Merge metadata
+ new_list.metadata["created_at"] = min(
+ self.metadata["created_at"], other.metadata["created_at"]
+ )
+ new_list.metadata["updated_at"] = datetime.now()
+
+ return new_list
+
+ else:
+ raise TypeError(
+ f"Unsupported operand type for +: 'ListKnowledge' and '{type(other).__name__}'"
+ )
+
+ def __delitem__(self, index: int):
+ """Support del operation for removing items by index.
+
+ Args:
+ index: Position to delete (supports negative indexing).
+
+ Raises:
+ IndexError: If index is out of range.
+
+ Examples:
+ >>> del knowledge[0] # Delete first item
+ >>> del knowledge[-1] # Delete last item
+
+ Side Effects:
+ - Clears the vector index (needs rebuild)
+ - Updates metadata timestamp
+ """
+ del self._data.items[index]
+ self.clear_index()
+ self.metadata["updated_at"] = datetime.now()
+
+ def __iter__(self):
+ """Support iteration over items.
+
+ Returns:
+ Iterator over items in the list.
+
+ Examples:
+ >>> for item in knowledge:
+ ... print(item.name)
+
+ >>> items_list = list(knowledge)
+ >>> names = [item.name for item in knowledge]
+ """
+ return iter(self.items)
+
+ def __contains__(self, item) -> bool:
+ """Support 'in' operator for membership testing.
+
+ Args:
+ item: The item to check for membership.
+
+ Returns:
+ True if item exists in the list, False otherwise.
+
+ Comparison Logic:
+ 1. Check if item's model_fields match any item's schema
+ 2. If schemas match, compare model_dump() equality
+
+ Examples:
+ >>> if person in knowledge:
+ ... print("Person already exists")
+ """
+ for existing_item in self.items:
+ if self._items_equal(existing_item, item):
+ return True
+ return False
+
+ def __repr__(self) -> str:
+ """Return detailed string representation.
+
+ Returns:
+ String in format: ClassName[ItemSchema](count items)
+
+ Examples:
+ >>> repr(knowledge)
+ 'ListKnowledge[PersonSchema](5 items)'
+ """
+ return (
+ f"{self.__class__.__name__}[{self.item_schema.__name__}]({len(self)} items)"
+ )
+
+ def __str__(self) -> str:
+ """Return human-readable string representation.
+
+ Returns:
+ Brief description of the knowledge instance.
+
+ Examples:
+ >>> str(knowledge)
+ 'ListKnowledge with 5 PersonSchema items'
+ """
+ return f"{self.__class__.__name__} with {len(self)} {self.item_schema.__name__} items"
+
+ # ==================== List Modification Methods ====================
+
+ def append(self, item) -> None:
+ """Append a single item to the end of the list.
+
+ Args:
+ item: The item to append.
+
+ Raises:
+ TypeError: If item schema doesn't match item_schema.
+
+ Examples:
+ >>> knowledge.append(PersonSchema(name="Alice", age=30))
+
+ Side Effects:
+ - Clears the vector index (needs rebuild)
+ - Updates metadata timestamp
+ """
+ self._validate_item_schema(item)
+ self._data.items.append(item)
+ self.clear_index()
+ self.metadata["updated_at"] = datetime.now()
+
+ def extend(self, items) -> None:
+ """Extend the list by appending multiple items.
+
+ Args:
+ items: Iterable of items to append. Can be:
+ - List of items
+ - Another ListKnowledge instance
+ - Any iterable yielding items
+
+ Raises:
+ TypeError: If any item's schema doesn't match item_schema.
+
+ Examples:
+ >>> knowledge.extend([person1, person2, person3])
+ >>> knowledge.extend(other_knowledge)
+
+ Side Effects:
+ - Clears the vector index (needs rebuild)
+ - Updates metadata timestamp
+ """
+ # Handle ListKnowledge instance
+ if isinstance(items, ListKnowledge):
+ if self.item_schema != items.item_schema:
+ raise TypeError(
+ f"Cannot extend with ListKnowledge of different schema. "
+ f"Expected: {self.item_schema.__name__}, "
+ f"Got: {items.item_schema.__name__}"
+ )
+ items_to_add = items.items
+ else:
+ items_to_add = list(items)
+
+ # Validate all items
+ for item in items_to_add:
+ self._validate_item_schema(item)
+
+ # Extend the list
+ self._data.items.extend(items_to_add)
+ self.clear_index()
+ self.metadata["updated_at"] = datetime.now()
+
+ def insert(self, index: int, item) -> None:
+ """Insert an item at a specific position.
+
+ Args:
+ index: Position to insert at (supports negative indexing).
+ item: The item to insert.
+
+ Raises:
+ TypeError: If item schema doesn't match item_schema.
+
+ Examples:
+ >>> knowledge.insert(0, new_person) # Insert at beginning
+ >>> knowledge.insert(-1, new_person) # Insert before last
+
+ Side Effects:
+ - Clears the vector index (needs rebuild)
+ - Updates metadata timestamp
+ """
+ self._validate_item_schema(item)
+ self._data.items.insert(index, item)
+ self.clear_index()
+ self.metadata["updated_at"] = datetime.now()
+
+ def remove(self, item) -> None:
+ """Remove the first occurrence of an item from the list.
+
+ Args:
+ item: The item to remove.
+
+ Raises:
+ ValueError: If item is not found in the list.
+
+ Comparison Logic:
+ Uses _items_equal() to find matching item.
+
+ Examples:
+ >>> knowledge.remove(person)
+
+ Side Effects:
+ - Clears the vector index (needs rebuild)
+ - Updates metadata timestamp
+ """
+ for i, existing_item in enumerate(self.items):
+ if self._items_equal(existing_item, item):
+ del self._data.items[i]
+ self.clear_index()
+ self.metadata["updated_at"] = datetime.now()
+ return
+
+ # Item not found
+ raise ValueError(f"{item} is not in list")
+
+ def pop(self, index: int = -1):
+ """Remove and return an item at the given position.
+
+ Args:
+ index: Position to pop (default: -1, last item).
+
+ Returns:
+ The removed item.
+
+ Raises:
+ IndexError: If list is empty or index is out of range.
+
+ Examples:
+ >>> last_item = knowledge.pop()
+ >>> first_item = knowledge.pop(0)
+
+ Side Effects:
+ - Clears the vector index (needs rebuild)
+ - Updates metadata timestamp
+ """
+ if not self.items:
+ raise IndexError("pop from empty list")
+
+ item = self._data.items.pop(index)
+ self.clear_index()
+ self.metadata["updated_at"] = datetime.now()
+ return item
+
+ # ==================== Query and Utility Methods ====================
+
+ def index(self, item, start: int = 0, stop: int = None) -> int:
+ """Return the index of the first occurrence of item.
+
+ Args:
+ item: The item to find.
+ start: Start searching from this position (default: 0).
+ stop: Stop searching at this position (default: end of list).
+
+ Returns:
+ The index of the first matching item.
+
+ Raises:
+ ValueError: If item is not found in the specified range.
+
+ Comparison Logic:
+ Uses _items_equal() to match items.
+
+ Examples:
+ >>> idx = knowledge.index(person)
+ >>> idx = knowledge.index(person, 5, 10) # Search in range [5:10]
+ """
+ items = self.items[start:stop]
+ for i, existing_item in enumerate(items):
+ if self._items_equal(existing_item, item):
+ return start + i
+
+ raise ValueError(f"{item} is not in list")
+
+ def count(self, item) -> int:
+ """Return the number of times item appears in the list.
+
+ Args:
+ item: The item to count.
+
+ Returns:
+ Number of occurrences.
+
+ Comparison Logic:
+ Uses _items_equal() to match items.
+
+ Examples:
+ >>> count = knowledge.count(person)
+ """
+ count = 0
+ for existing_item in self.items:
+ if self._items_equal(existing_item, item):
+ count += 1
+ return count
+
+ def copy(self) -> "ListKnowledge[Item]":
+ """Create a deep copy of this ListKnowledge instance.
+
+ Returns:
+ A new ListKnowledge instance with copied items and metadata.
+
+ Note:
+ The vector index is not copied; it needs to be rebuilt if needed.
+
+ Examples:
+ >>> backup = knowledge.copy()
+ >>> backup.append(new_item) # Original unchanged
+ """
+ new_instance = self._create_new_instance()
+ # Deep copy the data
+ new_instance._data = self._data.model_copy(deep=True)
+ # Copy metadata
+ new_instance.metadata = self.metadata.copy()
+ new_instance.metadata["updated_at"] = datetime.now()
+ return new_instance
+
+ def reverse(self) -> None:
+ """Reverse the items in place.
+
+ Examples:
+ >>> knowledge.reverse()
+
+ Side Effects:
+ - Rebuilds the vector index if it exists (to maintain consistency)
+ - Updates metadata timestamp
+
+ Note:
+ Does not call clear_index() since elements aren't modified,
+ but rebuilds index to maintain metadata order consistency.
+ """
+ self._data.items.reverse()
+ self.metadata["updated_at"] = datetime.now()
+
+ # Rebuild index if it exists to maintain consistency
+ if self._index is not None:
+ self._index = None
+ self.build_index()
+
+ def sort(self, key=None, reverse: bool = False) -> None:
+ """Sort the items in place.
+
+ Args:
+ key: Function to extract comparison key from each item.
+ Must be provided since Items may not be directly comparable.
+ reverse: If True, sort in descending order (default: False).
+
+ Raises:
+ TypeError: If key is not provided and items aren't comparable.
+
+ Examples:
+ >>> knowledge.sort(key=lambda x: x.name)
+ >>> knowledge.sort(key=lambda x: x.age, reverse=True)
+
+ Side Effects:
+ - Rebuilds the vector index if it exists (to maintain consistency)
+ - Updates metadata timestamp
+
+ Note:
+ Does not call clear_index() since elements aren't modified,
+ but rebuilds index to maintain metadata order consistency.
+ """
+ if key is None:
+ raise TypeError(
+ "sort() requires a 'key' function. "
+ "Example: knowledge.sort(key=lambda x: x.name)"
+ )
+
+ self._data.items.sort(key=key, reverse=reverse)
+ self.metadata["updated_at"] = datetime.now()
+
+ # Rebuild index if it exists to maintain consistency
+ if self._index is not None:
+ self._index = None
+ self.build_index()
+
+ # ==================== Helper Methods ====================
+
+ def _validate_item_schema(self, item) -> None:
+ """Validate that item's schema matches item_schema.
+
+ Args:
+ item: The item to validate.
+
+ Raises:
+ TypeError: If schemas don't match, with detailed field difference.
+ """
+ if not isinstance(item, BaseModel):
+ raise TypeError(
+ f"Item must be a Pydantic BaseModel instance. "
+ f"Got: {type(item).__name__}"
+ )
+
+ # Compare model_fields (schema structure)
+ item_fields = type(item).model_fields
+ expected_fields = self.item_schema.model_fields
+
+ if item_fields != expected_fields:
+ # Provide detailed error message
+ expected_field_names = set(expected_fields.keys())
+ got_field_names = set(item_fields.keys())
+
+ missing = expected_field_names - got_field_names
+ extra = got_field_names - expected_field_names
+
+ error_parts = [
+ f"Item schema mismatch. Expected {self.item_schema.__name__}, "
+ f"but got {type(item).__name__}."
+ ]
+
+ if missing:
+ error_parts.append(f"Missing fields: {sorted(missing)}")
+ if extra:
+ error_parts.append(f"Extra fields: {sorted(extra)}")
+
+ if not missing and not extra:
+ error_parts.append(
+ f"Expected fields: {sorted(expected_field_names)}, "
+ f"Got fields: {sorted(got_field_names)}"
+ )
+
+ raise TypeError(" ".join(error_parts))
+
+ def _items_equal(self, item1, item2) -> bool:
+ """Check if two items are equal.
+
+ Args:
+ item1, item2: Items to compare.
+
+ Returns:
+ True if items are equal, False otherwise.
+
+ Comparison Logic:
+ 1. Check if both have the same model_fields (schema)
+ 2. If schemas match, compare model_dump() equality
+ """
+ # Check schema compatibility
+ if type(item1).model_fields != type(item2).model_fields:
+ return False
+
+ # Compare data
+ return item1.model_dump() == item2.model_dump()
diff --git a/hyperextract/knowledge/generic/set.py b/hyperextract/knowledge/generic/set.py
index c7e861f..d99fa0a 100644
--- a/hyperextract/knowledge/generic/set.py
+++ b/hyperextract/knowledge/generic/set.py
@@ -1,18 +1,1266 @@
"""Set Knowledge Pattern - extracts a unique collection of objects from text.
-TODO: Implement SetKnowledge class with the following features:
- - Automatic deduplication based on content hash or embedding similarity
- - Set-based merge operations (union, intersection, difference)
- - Efficient membership testing
-
-Example usage:
- class Keyword(BaseModel):
- term: str
- category: str = ""
-
- knowledge = SetKnowledge(Keyword, llm, embedder)
- knowledge.extract(text) # Automatically deduplicates
+Provides automatic deduplication based on a user-specified unique key field.
+Supports multiple merge strategies including LLM-powered intelligent merging.
"""
-# TODO: Implement SetKnowledge[Item] class
-# Consider inheritance: SetKnowledge(ListKnowledge[Item]) or SetKnowledge(BaseKnowledge[...])
+import json
+from typing import List, Any, Type, TypeVar, Generic, Dict, Optional
+from datetime import datetime
+from pathlib import Path
+from enum import Enum
+from pydantic import BaseModel, Field, create_model
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from langchain_core.prompts import ChatPromptTemplate
+from langchain_core.documents import Document
+
+from ..base import BaseKnowledge
+
+try:
+ from hyperextract.config import logger
+except ImportError:
+ import logging
+
+ logger = logging.getLogger(__name__)
+
+
+Item = TypeVar("Item", bound=BaseModel)
+
+
+class ItemSetSchema(BaseModel, Generic[Item]):
+ """Generic schema container for set-based knowledge patterns."""
+
+ items: List[Item] = Field(default_factory=list, description="Set of unique items")
+
+
+class MergeItemStrategy(str, Enum):
+ """Merge strategy for handling duplicate items.
+
+ Strategies:
+ KEEP_OLD: Keep the existing item, discard the new one
+ KEEP_NEW: Keep the new item, discard the existing one (default)
+ FIELD_MERGE: Merge fields from both items (new fills old's None fields)
+ LLM_MERGE: Use LLM to intelligently merge both items
+ """
+
+ KEEP_OLD = "keep_old"
+ KEEP_NEW = "keep_new"
+ FIELD_MERGE = "field_merge"
+ LLM_MERGE = "llm_merge"
+
+
+class SetKnowledge(BaseKnowledge[ItemSetSchema[Item]], Generic[Item]):
+ """Set Knowledge Pattern - extracts a unique collection of objects.
+
+ This pattern automatically deduplicates items based on a user-specified
+ unique key field. Provides flexible merge strategies including LLM-powered
+ intelligent merging for handling duplicates.
+
+ Key characteristics:
+ - Extraction target: A unique collection of structured objects
+ - Deduplication: Based on unique_key field (user-specified)
+ - Merge strategy: Configurable (keep_old/keep_new/field_merge/llm_merge)
+ - Internal storage: Dict for O(1) lookup and deduplication
+ - External interface: List (via items property)
+ - Set operations: union (|), intersection (&), difference (-)
+
+ Comparison with ListKnowledge:
+ - ListKnowledge: Allows duplicates, simple append merge
+ - SetKnowledge: Automatic deduplication, intelligent merge strategies
+
+ Example:
+ >>> class KeywordSchema(BaseModel):
+ ... term: str
+ ... category: str | None = None
+ ... frequency: int | None = None
+ >>>
+ >>> keywords = SetKnowledge(
+ ... item_schema=KeywordSchema,
+ ... llm_client=llm,
+ ... embedder=embedder,
+ ... unique_key="term",
+ ... merge_item_strategy="field_merge"
+ ... )
+ >>> keywords.extract("Python is great. Python is powerful.")
+ >>> len(keywords) # Only 1 item (deduplicated)
+ 1
+ """
+
+ def __init__(
+ self,
+ item_schema: Type[Item],
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ unique_key: str,
+ merge_item_strategy: MergeItemStrategy = MergeItemStrategy.KEEP_NEW,
+ prompt: str = "",
+ chunk_size: int = 2000,
+ chunk_overlap: int = 200,
+ max_workers: int = 10,
+ show_progress: bool = True,
+ llm_batch_size: int = 10,
+ **kwargs,
+ ):
+ """Initialize SetKnowledge with unique key and merge strategy.
+
+ Args:
+ item_schema: Pydantic BaseModel subclass for individual items.
+ llm_client: Language model client for extraction and merging.
+ embedder: Embedding model for vector indexing.
+ unique_key: Field name to use as unique identifier (required).
+ merge_item_strategy: Strategy for merging duplicate items (default: KEEP_NEW).
+ prompt: Custom extraction prompt.
+ chunk_size: Maximum characters per chunk for long texts.
+ chunk_overlap: Overlapping characters between adjacent chunks.
+ max_workers: Maximum concurrent extraction tasks.
+ show_progress: Whether to log progress information.
+ llm_batch_size: Batch size for LLM merge operations (for LLM_MERGE strategy).
+ **kwargs: Additional arguments passed to parent class.
+
+ Raises:
+ ValueError: If unique_key field does not exist in item_schema.
+ TypeError: If unique_key field type is not hashable.
+ """
+ # Validate unique_key before initialization
+ self._validate_unique_key(item_schema, unique_key)
+
+ # Store item_schema
+ self.item_schema = item_schema
+
+ # Create ItemSetSchema container dynamically (similar to ListKnowledge's ItemListSchema)
+ container_name = f"{item_schema.__name__}Set"
+ self.item_set_schema = create_model(
+ container_name,
+ items=(
+ List[item_schema],
+ Field(default_factory=list, description="Set of unique items"),
+ ),
+ )
+
+ # Call BaseKnowledge.__init__ (not ListKnowledge)
+ super().__init__(
+ data_schema=self.item_set_schema,
+ llm_client=llm_client,
+ embedder=embedder,
+ prompt=prompt or self._default_prompt(),
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ show_progress=show_progress,
+ **kwargs,
+ )
+
+ # SetKnowledge-specific attributes
+ self.unique_key = unique_key
+ self.merge_item_strategy = merge_item_strategy
+ self.llm_batch_size = llm_batch_size
+
+ # Internal storage: Dict for O(1) deduplication
+ self._items_dict: Dict[Any, Item] = {}
+
+ # Create LLM merge chain (if using LLM_MERGE strategy)
+ self._merge_chain = (
+ self._create_merge_chain()
+ if merge_item_strategy == MergeItemStrategy.LLM_MERGE
+ else None
+ )
+
+ # ==================== Override Instance Creation ====================
+
+ def _create_new_instance(self) -> "SetKnowledge[Item]":
+ """Creates a new instance with the same configuration.
+
+ Overrides parent method to include SetKnowledge-specific parameters.
+
+ Returns:
+ New SetKnowledge instance.
+ """
+ return self.__class__(
+ item_schema=self.item_schema,
+ llm_client=self.llm_client,
+ embedder=self.embedder,
+ unique_key=self.unique_key,
+ merge_item_strategy=self.merge_item_strategy,
+ prompt=self.prompt,
+ chunk_size=self.chunk_size,
+ chunk_overlap=self.chunk_overlap,
+ max_workers=self.max_workers,
+ show_progress=self.show_progress,
+ llm_batch_size=self.llm_batch_size,
+ )
+
+ # ==================== Validation ====================
+
+ @staticmethod
+ def _default_prompt() -> str:
+ """Returns the default extraction prompt for set-based extraction."""
+ return (
+ "You are an expert knowledge extraction assistant. "
+ "Extract all unique items from the text into a set. "
+ "Be comprehensive and ensure no item is missed. "
+ "Extract all items without adding information not present in the text.\n\n"
+ "### Source Text:\n"
+ )
+
+ @staticmethod
+ def _validate_unique_key(item_schema: Type[Item], unique_key: str):
+ """Validates that unique_key exists in schema and is hashable.
+
+ Args:
+ item_schema: The Pydantic schema to validate.
+ unique_key: The field name to validate.
+
+ Raises:
+ ValueError: If unique_key field does not exist.
+ TypeError: If unique_key field type is known to be unhashable.
+ """
+ # Check field existence
+ if unique_key not in item_schema.model_fields:
+ available_fields = list(item_schema.model_fields.keys())
+ raise ValueError(
+ f"unique_key '{unique_key}' not found in {item_schema.__name__}. "
+ f"Available fields: {available_fields}"
+ )
+
+ # Check field type (basic unhashable type detection)
+ field_info = item_schema.model_fields[unique_key]
+ field_type = field_info.annotation
+
+ # Extract actual type from Optional/Union if present
+ import typing
+
+ if (
+ hasattr(typing, "get_origin")
+ and typing.get_origin(field_type) is typing.Union
+ ):
+ args = typing.get_args(field_type)
+ field_type = args[0] if args else field_type
+
+ # Check for known unhashable types
+ unhashable_types = (list, dict, set, List, Dict)
+ if field_type in unhashable_types:
+ raise TypeError(
+ f"unique_key field '{unique_key}' has unhashable type {field_type}. "
+ f"unique_key must be a hashable type (str, int, tuple, etc.)"
+ )
+
+ # ==================== LLM Merge Chain ====================
+
+ def _create_merge_chain(self):
+ """Creates an LLM chain for intelligently merging duplicate items.
+
+ Subclasses can override this method to customize the merge prompt.
+
+ Returns:
+ LangChain chain for merging items.
+ """
+ merge_template = """You are an expert at merging structured data.
+Given two instances of the same item (identified by the same unique key),
+intelligently merge their fields into one complete item.
+
+Merging rules:
+1. Keep the unique key field unchanged
+2. For other fields: prefer non-null values
+3. If both items have values for a field, choose the more complete/accurate one
+4. Combine text fields if appropriate (e.g., descriptions)
+
+Item A (existing):
+{item_existing}
+
+Item B (incoming):
+{item_incoming}
+
+Please merge these two items intelligently and return the merged result."""
+
+ merge_prompt = ChatPromptTemplate.from_template(merge_template)
+ return merge_prompt | self.llm_client.with_structured_output(self.item_schema)
+
+ # ==================== Properties ====================
+
+ @property
+ def items(self) -> List[Item]:
+ """Returns the internal items as a list (for external interface compatibility).
+
+ Converts the internal dictionary values to a list.
+
+ Returns:
+ List of unique items.
+ """
+ return list(self._items_dict.values())
+
+ @property
+ def keys(self) -> List[Any]:
+ """Returns all unique key values.
+
+ Returns:
+ List of unique key values.
+ """
+ return list(self._items_dict.keys())
+
+ def __len__(self) -> int:
+ """Returns the number of unique items in the set."""
+ return len(self._items_dict)
+
+ def __contains__(self, key: Any) -> bool:
+ """Checks if a unique key exists in the set.
+
+ Args:
+ key: The unique key value to check.
+
+ Returns:
+ True if key exists, False otherwise.
+ """
+ return key in self._items_dict
+
+ def __repr__(self) -> str:
+ """Returns a developer-friendly representation."""
+ return f"SetKnowledge[{self.item_schema.__name__}]({len(self)} unique items)"
+
+ def __str__(self) -> str:
+ """Returns a user-friendly string representation."""
+ return f"SetKnowledge with {len(self)} unique {self.item_schema.__name__} items"
+
+ def __iter__(self):
+ """Enables iteration over all items in the set.
+
+ Returns:
+ Iterator over all unique items.
+
+ Examples:
+ >>> for skill in skills:
+ ... print(skill.name)
+ >>> names = [s.name for s in skills]
+ """
+ return iter(self.items)
+
+ # ==================== Core Override Methods ====================
+
+ def clear(self):
+ """Clears all items from the set."""
+ self._data = self.item_set_schema()
+ self._items_dict.clear()
+ self.clear_index()
+ self.metadata["updated_at"] = datetime.now()
+
+ def extract(self, text: str, *, store: bool = True):
+ """Extracts a set of unique items using LLM with automatic deduplication.
+
+ Args:
+ text: Input text to extract items from.
+ store: Whether to store extracted knowledge internally.
+
+ Returns:
+ The set of extracted unique items.
+ """
+ start_time = datetime.now()
+
+ # Determine if chunking is needed
+ if len(text) <= self.chunk_size:
+ # Short text: extract in one pass
+ if self.show_progress:
+ logger.info(f"Processing single text (length: {len(text)})...")
+
+ extracted_data = self.llm_chain_extract.invoke({"chunk_text": text})
+ extracted_data_list = [extracted_data]
+
+ else:
+ # Long text: extract by chunking
+ chunks = self.text_splitter.split_text(text)
+ logger.info(f"Split text into {len(chunks)} chunks")
+
+ if self.show_progress:
+ logger.info(f"Processing {len(chunks)} chunk(s)...")
+
+ inputs = [{"chunk_text": chunk} for chunk in chunks]
+ extracted_data_list = self.llm_chain_extract.batch(
+ inputs, config={"max_concurrency": self.max_workers}
+ )
+
+ if self.show_progress:
+ logger.info(f"Extracted {len(extracted_data_list)} chunks")
+
+ logger.info("Merging extracted knowledge...")
+ merged_data = self.merge(extracted_data_list)
+
+ # If store=True, merge with existing data and update internal state
+ if store:
+ if self._data and len(self.items) > 0:
+ self._data = self.merge([self._data, merged_data])
+ else:
+ self._data = merged_data
+
+ self.clear_index()
+ self.metadata["updated_at"] = datetime.now()
+
+ logger.info("Knowledge extraction completed")
+ logger.info(
+ f"Duration: {(datetime.now() - start_time).total_seconds():.2f} seconds"
+ )
+
+ # Return items list
+ return self.items if store else merged_data.items
+
+ def build_index(self):
+ """Builds independent vector index for each unique item."""
+ items = self.items
+ if not items:
+ logger.warning("No items to index")
+ return
+
+ if self._index is not None:
+ return
+
+ documents = []
+ for idx, item in enumerate(items):
+ # Serialize each Item as a Document
+ content = item.model_dump_json() # Use JSON string as content
+ documents.append(
+ Document(
+ page_content=content,
+ metadata={"raw": item.model_dump(), "index": idx},
+ )
+ )
+
+ if documents:
+ try:
+ from langchain_community.vectorstores import FAISS
+
+ self._index = FAISS.from_documents(documents, self.embedder)
+ logger.info(f"Built FAISS index with {len(documents)} items")
+ except ImportError:
+ logger.error("FAISS not available. Install with: pip install faiss-cpu")
+ raise
+
+ def search(self, query: str, top_k: int = 3) -> List[Any]:
+ """Searches items in the set using semantic similarity.
+
+ Args:
+ query: Search query string.
+ top_k: Number of results to return.
+
+ Returns:
+ List of relevant items.
+ """
+ if not self.items:
+ logger.warning("No items to search")
+ return []
+
+ if self._index is None:
+ raise Exception("Vector store not initialized")
+
+ docs = self._index.similarity_search(query, k=top_k)
+ results = []
+ for doc in docs:
+ # Attempt to restore as object
+ try:
+ raw = doc.metadata.get("raw", {})
+ item = self.item_schema.model_validate(raw)
+ results.append(item)
+ except Exception as e:
+ logger.warning(f"Failed to restore item: {e}")
+ results.append(doc.metadata.get("raw"))
+
+ logger.info(f"Found {len(results)} results for query: {query[:50]}...")
+ return results
+
+ def merge(self, data_list: List[ItemSetSchema[Item]]) -> ItemSetSchema[Item]:
+ """Merges multiple data containers with automatic deduplication.
+
+ Overrides parent's merge to implement set semantics:
+ 1. Collect all items from all containers
+ 2. For each item, check if unique_key already exists
+ 3. If duplicate, call merge_item() to resolve
+ 4. Return deduplicated result
+
+ For LLM_MERGE strategy, batches duplicate pairs for efficient processing.
+
+ Args:
+ data_list: List of container objects to merge.
+
+ Returns:
+ Merged ItemSetSchema with deduplicated items.
+ """
+ # Collect all items and track duplicates for batch LLM merge
+ merge_pairs = [] # [(existing, incoming, key), ...]
+
+ for data in data_list:
+ for item in data.items:
+ # Get unique key value
+ key_value = self._get_key_value(item)
+ if key_value is None:
+ continue
+
+ if key_value in self._items_dict:
+ # Duplicate found
+ if self.merge_item_strategy == MergeItemStrategy.LLM_MERGE:
+ # Collect for batch processing
+ merge_pairs.append(
+ (self._items_dict[key_value], item, key_value)
+ )
+ else:
+ # Merge immediately with non-LLM strategies
+ merged = self.merge_item(self._items_dict[key_value], item)
+ if merged is not None:
+ self._items_dict[key_value] = merged
+ else:
+ # New item
+ self._items_dict[key_value] = item.model_copy(deep=True)
+
+ # Batch process LLM merges if any
+ if merge_pairs and self.merge_item_strategy == MergeItemStrategy.LLM_MERGE:
+ merged_results = self._batch_merge_with_llm(merge_pairs)
+ # Update items_dict with merged results
+ self._items_dict.update(merged_results)
+
+ # Update internal _data to match _items_dict
+ self._data.items = list(self._items_dict.values())
+
+ logger.info(
+ f"Merged into {len(self._items_dict)} unique items "
+ f"(strategy: {self.merge_item_strategy.value})"
+ )
+
+ return self._data
+
+ def merge_item(self, existing: Item, incoming: Item) -> Optional[Item]:
+ """Merges two duplicate items based on the configured strategy.
+
+ This method can be overridden by subclasses to implement custom merge logic.
+
+ Args:
+ existing: The existing item in the set.
+ incoming: The incoming item to merge.
+
+ Returns:
+ Merged item, or None to skip this item.
+ """
+ if self.merge_item_strategy == MergeItemStrategy.KEEP_OLD:
+ return existing
+
+ elif self.merge_item_strategy == MergeItemStrategy.KEEP_NEW:
+ return incoming
+
+ elif self.merge_item_strategy == MergeItemStrategy.FIELD_MERGE:
+ # Field-level merge: existing's non-None values override incoming
+ return incoming.model_copy(update=existing.model_dump(exclude_none=True))
+
+ elif self.merge_item_strategy == MergeItemStrategy.LLM_MERGE:
+ # LLM merge (should be handled by batch processing in merge())
+ # Fallback to single merge if called directly
+ return self._merge_item_with_llm(existing, incoming)
+
+ else:
+ logger.warning(
+ f"Unknown merge strategy: {self.merge_item_strategy}, using KEEP_NEW"
+ )
+ return incoming
+
+ def _get_key_value(self, item: Item) -> Optional[Any]:
+ """Extracts the unique key value from an item.
+
+ Args:
+ item: The item to extract key from.
+
+ Returns:
+ The unique key value, or None if invalid.
+ """
+ try:
+ key_value = getattr(item, self.unique_key)
+
+ # Validate key value
+ if key_value is None:
+ logger.warning(
+ f"Item has None value for unique_key '{self.unique_key}', skipping"
+ )
+ return None
+
+ # Verify hashability
+ hash(key_value)
+ return key_value
+
+ except TypeError:
+ logger.error(
+ f"Value {key_value} for unique_key '{self.unique_key}' is not hashable"
+ )
+ return None
+ except AttributeError:
+ logger.error(f"Item missing unique_key field '{self.unique_key}'")
+ return None
+
+ # ==================== LLM Merge Methods ====================
+
+ def _batch_merge_with_llm(self, merge_pairs: List[tuple]) -> Dict[Any, Item]:
+ """Batch processes LLM merges for efficiency.
+
+ Args:
+ merge_pairs: List of (existing, incoming, key_value) tuples to merge.
+
+ Returns:
+ Dictionary mapping key_value to merged items.
+ """
+ results = {}
+
+ if not self._merge_chain:
+ logger.warning("LLM merge chain not initialized, falling back to KEEP_NEW")
+ for existing, incoming, key_value in merge_pairs:
+ results[key_value] = incoming
+ return results
+
+ total_pairs = len(merge_pairs)
+ logger.info(f"Batch merging {total_pairs} duplicate items with LLM...")
+
+ # Process in batches
+ for i in range(0, total_pairs, self.llm_batch_size):
+ batch = merge_pairs[i : i + self.llm_batch_size]
+
+ # Prepare batch inputs
+ inputs = [
+ {
+ "item_existing": existing.model_dump_json(indent=2),
+ "item_incoming": incoming.model_dump_json(indent=2),
+ }
+ for existing, incoming, _ in batch
+ ]
+
+ try:
+ # Batch invoke LLM
+ merged_results = self._merge_chain.batch(inputs)
+
+ # Collect merged results
+ for (existing, incoming, key_value), merged in zip(
+ batch, merged_results
+ ):
+ if merged:
+ results[key_value] = merged
+ logger.debug(f"Successfully merged item with key '{key_value}'")
+ else:
+ logger.warning(
+ f"LLM merge returned None for key '{key_value}', keeping incoming"
+ )
+ results[key_value] = incoming
+
+ except Exception as e:
+ logger.error(f"Batch LLM merge failed: {e}, falling back to KEEP_NEW")
+ # Fallback: keep incoming items
+ for existing, incoming, key_value in batch:
+ results[key_value] = incoming
+
+ return results
+
+ def _merge_item_with_llm(self, existing: Item, incoming: Item) -> Optional[Item]:
+ """Uses LLM to intelligently merge two duplicate items (single merge).
+
+ Args:
+ existing: The existing item.
+ incoming: The incoming item to merge.
+
+ Returns:
+ Merged item, or None on failure.
+ """
+ if not self._merge_chain:
+ logger.warning("LLM merge chain not initialized")
+ return incoming
+
+ try:
+ merged = self._merge_chain.invoke(
+ {
+ "item_existing": existing.model_dump_json(indent=2),
+ "item_incoming": incoming.model_dump_json(indent=2),
+ }
+ )
+ logger.debug("Successfully merged item with LLM")
+ return merged
+ except Exception as e:
+ logger.error(f"LLM merge failed: {e}")
+ return incoming # Fallback to incoming item
+
+ # ==================== Serialization ====================
+
+ def dump(self, folder_path: str | Path):
+ """Exports knowledge to a specified folder.
+
+ Saves both the items and the SetKnowledge-specific metadata.
+
+ Args:
+ folder_path: Target folder path for saving.
+ """
+ folder = Path(folder_path)
+ folder.mkdir(parents=True, exist_ok=True)
+
+ # Save structured data
+ data = {
+ "schema_name": self.item_set_schema.__name__,
+ "item_schema_name": self.item_schema.__name__,
+ "item_schema": self.item_schema.model_json_schema(),
+ "unique_key": self.unique_key,
+ "merge_item_strategy": self.merge_item_strategy.value,
+ "data": self.data.model_dump(),
+ "metadata": {
+ k: str(v) if isinstance(v, datetime) else v
+ for k, v in self.metadata.items()
+ },
+ }
+
+ json_str = json.dumps(data, indent=2, ensure_ascii=False, default=str)
+ data_file = folder / "state.json"
+ with open(data_file, "w", encoding="utf-8") as f:
+ f.write(json_str)
+ logger.info(f"Saved data to {data_file}")
+
+ # Save vector index
+ if self._index is not None:
+ index_path = str(folder / "faiss_index")
+ self._index.save_local(index_path)
+ logger.info(f"Saved FAISS index to {index_path}")
+ else:
+ logger.warning("No index to save")
+
+ def load(self, folder_path: str | Path):
+ """Loads knowledge from a specified folder.
+
+ Args:
+ folder_path: Source folder path containing saved knowledge.
+ """
+ folder = Path(folder_path)
+ if not folder.is_dir():
+ raise ValueError(f"Folder does not exist: {folder_path}")
+
+ # Load structured data
+ data_file = folder / "state.json"
+ if not data_file.is_file():
+ raise ValueError(f"Data file not found: {data_file}")
+
+ with open(data_file, "r", encoding="utf-8") as f:
+ data = json.load(f)
+ logger.info(f"Loaded data from {data_file}")
+
+ self._data = self.item_set_schema.model_validate(data.get("data", {}))
+
+ # Rebuild items_dict from _data.items (not self.items property!)
+ self._items_dict = {}
+ for item in self._data.items:
+ key_value = self._get_key_value(item)
+ if key_value is not None:
+ self._items_dict[key_value] = item
+
+ # Update metadata
+ if "metadata" in data:
+ self.metadata.update(data["metadata"])
+ self.metadata["updated_at"] = datetime.now()
+
+ # Load vector index
+ index_path = str(folder / "faiss_index")
+ if Path(index_path).exists():
+ try:
+ from langchain_community.vectorstores import FAISS
+
+ self._index = FAISS.load_local(
+ index_path, self.embedder, allow_dangerous_deserialization=True
+ )
+ logger.info(f"Loaded FAISS index from {index_path}")
+ except Exception as e:
+ logger.warning(f"Failed to load FAISS index: {e}")
+ self._index = None
+ else:
+ logger.warning("No index file found, will rebuild on next search")
+ self._index = None
+
+ logger.info(f"Loaded knowledge successfully with {len(self)} unique items")
+
+ # ==================== Set-Specific Methods ====================
+
+ def add(self, item: Item) -> None:
+ """Adds a single item to the set with automatic deduplication.
+
+ Args:
+ item: The item to add.
+ """
+ key_value = self._get_key_value(item)
+ if key_value is None:
+ return
+
+ if key_value in self._items_dict:
+ # Merge with existing
+ merged = self.merge_item(self._items_dict[key_value], item)
+ if merged:
+ self._items_dict[key_value] = merged
+ else:
+ # Add new
+ self._items_dict[key_value] = item.model_copy(deep=True)
+
+ # Update _data
+ self._data.items = list(self._items_dict.values())
+ self.clear_index()
+
+ def remove(self, key: Any) -> Optional[Item]:
+ """Removes an item by its unique key value.
+
+ Args:
+ key: The unique key value to remove.
+
+ Returns:
+ The removed item, or None if not found.
+ """
+ removed = self._items_dict.pop(key, None)
+ if removed:
+ self._data.items = list(self._items_dict.values())
+ self.clear_index()
+ logger.debug(f"Removed item with key '{key}'")
+ return removed
+
+ def contains(self, key: Any) -> bool:
+ """Checks if an item with the given key exists in the set.
+
+ Args:
+ key: The unique key value to check.
+
+ Returns:
+ True if key exists, False otherwise.
+ """
+ return key in self._items_dict
+
+ def get(self, key: Any, default: Optional[Item] = None) -> Optional[Item]:
+ """Gets an item by its unique key value.
+
+ Args:
+ key: The unique key value to retrieve.
+ default: Default value if key not found.
+
+ Returns:
+ The item if found, otherwise default.
+ """
+ return self._items_dict.get(key, default)
+
+ def update(self, items: List[Item]) -> None:
+ """Batch adds multiple items.
+
+ Args:
+ items: List of items to add.
+ """
+ for item in items:
+ self.add(item)
+
+ def discard(self, key: Any) -> None:
+ """Removes an item by its unique key value, silently ignoring if not found.
+
+ Unlike remove(), this method does not raise an error if the key does not exist.
+
+ Args:
+ key: The unique key value to remove.
+
+ Examples:
+ >>> skills.discard("Python") # No error if not found
+
+ Side Effects:
+ - Clears the vector index (needs rebuild)
+ - Updates metadata timestamp
+ """
+ removed = self._items_dict.pop(key, None)
+ if removed:
+ self._data.items = list(self._items_dict.values())
+ self.clear_index()
+ self.metadata["updated_at"] = datetime.now()
+
+ def pop(self) -> Item:
+ """Removes and returns an arbitrary item from the set.
+
+ Args:
+ None
+
+ Returns:
+ The removed item.
+
+ Raises:
+ KeyError: If the set is empty.
+
+ Examples:
+ >>> skill = skills.pop()
+ >>> print(f"Removed: {skill.name}")
+
+ Side Effects:
+ - Clears the vector index (needs rebuild)
+ - Updates metadata timestamp
+ """
+ if not self._items_dict:
+ raise KeyError("pop from an empty SetKnowledge")
+
+ key = next(iter(self._items_dict))
+ item = self._items_dict.pop(key)
+ self._data.items = list(self._items_dict.values())
+ self.clear_index()
+ self.metadata["updated_at"] = datetime.now()
+
+ return item
+
+ def copy(self) -> "SetKnowledge[Item]":
+ """Creates a deep copy of the set.
+
+ Returns:
+ A new SetKnowledge instance with copies of all items.
+
+ Examples:
+ >>> backup = skills.copy()
+ >>> backup.add(new_skill)
+ >>> # Original skills unchanged
+ """
+ new_set = self._create_new_instance()
+ new_set._items_dict = {
+ key: item.model_copy(deep=True) for key, item in self._items_dict.items()
+ }
+ new_set._data.items = list(new_set._items_dict.values())
+ new_set.metadata = self.metadata.copy()
+ new_set.metadata["created_at"] = datetime.now()
+
+ return new_set
+
+ # ==================== Set Operations ====================
+
+ def __or__(self, other: "SetKnowledge[Item]") -> "SetKnowledge[Item]":
+ """Union operation: set1 | set2.
+
+ Returns a new set containing all items from both sets.
+
+ Args:
+ other: Another SetKnowledge instance.
+
+ Returns:
+ New SetKnowledge with union of items.
+ """
+ if not isinstance(other, SetKnowledge):
+ raise TypeError(
+ f"Unsupported operand type for |: 'SetKnowledge' and '{type(other).__name__}'"
+ )
+
+ if self.item_schema != other.item_schema:
+ raise TypeError(
+ f"Cannot union SetKnowledge instances with different schemas. "
+ f"Left: {self.item_schema.__name__}, Right: {other.item_schema.__name__}"
+ )
+
+ # Create new instance
+ new_set = self._create_new_instance()
+ new_set._items_dict = self._items_dict.copy()
+
+ # Add items from other (merge duplicates)
+ for key, item in other._items_dict.items():
+ if key in new_set._items_dict:
+ merged = new_set.merge_item(new_set._items_dict[key], item)
+ if merged:
+ new_set._items_dict[key] = merged
+ else:
+ new_set._items_dict[key] = item.model_copy(deep=True)
+
+ new_set._data.items = list(new_set._items_dict.values())
+ new_set.metadata["updated_at"] = datetime.now()
+
+ return new_set
+
+ def __and__(self, other: "SetKnowledge[Item]") -> "SetKnowledge[Item]":
+ """Intersection operation: set1 & set2.
+
+ Returns a new set containing only items present in both sets.
+
+ Args:
+ other: Another SetKnowledge instance.
+
+ Returns:
+ New SetKnowledge with intersection of items.
+ """
+ if not isinstance(other, SetKnowledge):
+ raise TypeError(
+ f"Unsupported operand type for &: 'SetKnowledge' and '{type(other).__name__}'"
+ )
+
+ if self.item_schema != other.item_schema:
+ raise TypeError(
+ f"Cannot intersect SetKnowledge instances with different schemas. "
+ f"Left: {self.item_schema.__name__}, Right: {other.item_schema.__name__}"
+ )
+
+ # Create new instance
+ new_set = self._create_new_instance()
+
+ # Only keep items present in both sets
+ for key in self._items_dict:
+ if key in other._items_dict:
+ # Merge the two versions
+ merged = new_set.merge_item(
+ self._items_dict[key], other._items_dict[key]
+ )
+ if merged:
+ new_set._items_dict[key] = merged
+
+ new_set._data.items = list(new_set._items_dict.values())
+ new_set.metadata["updated_at"] = datetime.now()
+
+ return new_set
+
+ def __sub__(self, other: "SetKnowledge[Item]") -> "SetKnowledge[Item]":
+ """Difference operation: set1 - set2.
+
+ Returns a new set containing items in self but not in other.
+
+ Args:
+ other: Another SetKnowledge instance.
+
+ Returns:
+ New SetKnowledge with difference of items.
+ """
+ if not isinstance(other, SetKnowledge):
+ raise TypeError(
+ f"Unsupported operand type for -: 'SetKnowledge' and '{type(other).__name__}'"
+ )
+
+ if self.item_schema != other.item_schema:
+ raise TypeError(
+ f"Cannot subtract SetKnowledge instances with different schemas. "
+ f"Left: {self.item_schema.__name__}, Right: {other.item_schema.__name__}"
+ )
+
+ # Create new instance
+ new_set = self._create_new_instance()
+
+ # Only keep items not in other
+ for key, item in self._items_dict.items():
+ if key not in other._items_dict:
+ new_set._items_dict[key] = item.model_copy(deep=True)
+
+ new_set._data.items = list(new_set._items_dict.values())
+ new_set.metadata["updated_at"] = datetime.now()
+
+ return new_set
+
+ def __xor__(self, other: "SetKnowledge[Item]") -> "SetKnowledge[Item]":
+ """Symmetric difference operation: set1 ^ set2.
+
+ Returns a new set containing items in either set but not in both.
+
+ Args:
+ other: Another SetKnowledge instance.
+
+ Returns:
+ New SetKnowledge with symmetric difference of items.
+ """
+ if not isinstance(other, SetKnowledge):
+ raise TypeError(
+ f"Unsupported operand type for ^: 'SetKnowledge' and '{type(other).__name__}'"
+ )
+
+ if self.item_schema != other.item_schema:
+ raise TypeError(
+ f"Cannot compute symmetric difference of SetKnowledge instances with different schemas. "
+ f"Left: {self.item_schema.__name__}, Right: {other.item_schema.__name__}"
+ )
+
+ # Create new instance
+ new_set = self._create_new_instance()
+
+ # Add items only in self
+ for key, item in self._items_dict.items():
+ if key not in other._items_dict:
+ new_set._items_dict[key] = item.model_copy(deep=True)
+
+ # Add items only in other
+ for key, item in other._items_dict.items():
+ if key not in self._items_dict:
+ new_set._items_dict[key] = item.model_copy(deep=True)
+
+ new_set._data.items = list(new_set._items_dict.values())
+ new_set.metadata["updated_at"] = datetime.now()
+
+ return new_set
+
+ # ==================== Named Set Operations ====================
+
+ def union(self, other: "SetKnowledge[Item]") -> "SetKnowledge[Item]":
+ """Union operation (named method)."""
+ return self | other
+
+ def intersection(self, other: "SetKnowledge[Item]") -> "SetKnowledge[Item]":
+ """Intersection operation (named method)."""
+ return self & other
+
+ def difference(self, other: "SetKnowledge[Item]") -> "SetKnowledge[Item]":
+ """Difference operation (named method)."""
+ return self - other
+
+ def symmetric_difference(self, other: "SetKnowledge[Item]") -> "SetKnowledge[Item]":
+ """Symmetric difference operation (named method)."""
+ return self ^ other
+
+ # ==================== Set Comparison Operations ====================
+
+ def __eq__(self, other: Any) -> bool:
+ """Equality comparison: set1 == set2.
+
+ Two sets are equal if they have the same schema, unique_key, and key set.
+ Note: Does not compare item contents, only keys.
+
+ Args:
+ other: Another object to compare with.
+
+ Returns:
+ True if both sets have the same keys, False otherwise.
+
+ Examples:
+ >>> skills1 == skills2 # True if same keys
+ """
+ if not isinstance(other, SetKnowledge):
+ return False
+
+ if self.item_schema != other.item_schema:
+ return False
+
+ if self.unique_key != other.unique_key:
+ return False
+
+ return set(self._items_dict.keys()) == set(other._items_dict.keys())
+
+ def __ne__(self, other: Any) -> bool:
+ """Inequality comparison: set1 != set2.
+
+ Returns:
+ True if sets are not equal, False otherwise.
+ """
+ return not self.__eq__(other)
+
+ def __le__(self, other: "SetKnowledge[Item]") -> bool:
+ """Subset comparison: set1 <= set2.
+
+ Args:
+ other: Another SetKnowledge instance.
+
+ Returns:
+ True if self is a subset of other (all keys in self are in other).
+
+ Raises:
+ TypeError: If other is not a SetKnowledge or has different schema.
+
+ Examples:
+ >>> skills1 <= skills2 # True if skills1 is subset of skills2
+ """
+ if not isinstance(other, SetKnowledge):
+ return NotImplemented
+
+ if self.item_schema != other.item_schema:
+ raise TypeError(
+ f"Cannot compare SetKnowledge instances with different schemas. "
+ f"Left: {self.item_schema.__name__}, Right: {other.item_schema.__name__}"
+ )
+
+ return set(self._items_dict.keys()).issubset(set(other._items_dict.keys()))
+
+ def __lt__(self, other: "SetKnowledge[Item]") -> bool:
+ """Proper subset comparison: set1 < set2.
+
+ Args:
+ other: Another SetKnowledge instance.
+
+ Returns:
+ True if self is a proper subset of other (subset and not equal).
+
+ Examples:
+ >>> skills1 < skills2 # True if skills1 is proper subset
+ """
+ if not isinstance(other, SetKnowledge):
+ return NotImplemented
+
+ return self <= other and self != other
+
+ def __ge__(self, other: "SetKnowledge[Item]") -> bool:
+ """Superset comparison: set1 >= set2.
+
+ Args:
+ other: Another SetKnowledge instance.
+
+ Returns:
+ True if self is a superset of other (all keys in other are in self).
+
+ Examples:
+ >>> skills1 >= skills2 # True if skills1 is superset of skills2
+ """
+ if not isinstance(other, SetKnowledge):
+ return NotImplemented
+
+ if self.item_schema != other.item_schema:
+ raise TypeError(
+ f"Cannot compare SetKnowledge instances with different schemas. "
+ f"Left: {self.item_schema.__name__}, Right: {other.item_schema.__name__}"
+ )
+
+ return set(self._items_dict.keys()).issuperset(set(other._items_dict.keys()))
+
+ def __gt__(self, other: "SetKnowledge[Item]") -> bool:
+ """Proper superset comparison: set1 > set2.
+
+ Args:
+ other: Another SetKnowledge instance.
+
+ Returns:
+ True if self is a proper superset of other (superset and not equal).
+
+ Examples:
+ >>> skills1 > skills2 # True if skills1 is proper superset
+ """
+ if not isinstance(other, SetKnowledge):
+ return NotImplemented
+
+ return self >= other and self != other
+
+ def issubset(self, other: "SetKnowledge[Item]") -> bool:
+ """Test whether every key in the set is in other.
+
+ Args:
+ other: Another SetKnowledge instance.
+
+ Returns:
+ True if self is a subset of other.
+
+ Examples:
+ >>> skills1.issubset(skills2)
+ """
+ return self <= other
+
+ def issuperset(self, other: "SetKnowledge[Item]") -> bool:
+ """Test whether every key in other is in the set.
+
+ Args:
+ other: Another SetKnowledge instance.
+
+ Returns:
+ True if self is a superset of other.
+
+ Examples:
+ >>> skills1.issuperset(skills2)
+ """
+ return self >= other
+
+ def isdisjoint(self, other: "SetKnowledge[Item]") -> bool:
+ """Test whether the set has no keys in common with other.
+
+ Args:
+ other: Another SetKnowledge instance.
+
+ Returns:
+ True if the two sets have no keys in common.
+
+ Raises:
+ TypeError: If other is not a SetKnowledge or has different schema.
+
+ Examples:
+ >>> skills1.isdisjoint(skills2) # True if no common skills
+ """
+ if not isinstance(other, SetKnowledge):
+ raise TypeError(
+ f"isdisjoint() argument must be SetKnowledge, not {type(other).__name__}"
+ )
+
+ if self.item_schema != other.item_schema:
+ raise TypeError(
+ f"Cannot compare SetKnowledge instances with different schemas. "
+ f"Left: {self.item_schema.__name__}, Right: {other.item_schema.__name__}"
+ )
+
+ return set(self._items_dict.keys()).isdisjoint(set(other._items_dict.keys()))
diff --git a/hyperextract/knowledge/generic/unit.py b/hyperextract/knowledge/generic/unit.py
index 0e2bae0..cf613c7 100644
--- a/hyperextract/knowledge/generic/unit.py
+++ b/hyperextract/knowledge/generic/unit.py
@@ -15,6 +15,7 @@ try:
from hyperextract.config import logger
except ImportError:
import logging
+
logger = logging.getLogger(__name__)
@@ -130,11 +131,13 @@ class UnitKnowledge(BaseKnowledge[T]):
# If store=True, merge with existing data and update internal state
if store:
- if self._data and any(v is not None for v in self._data.model_dump().values()):
+ if self._data and any(
+ v is not None for v in self._data.model_dump().values()
+ ):
self._data = self.merge([self._data, merged_data])
else:
self._data = merged_data
-
+
self.clear_index()
self.metadata["updated_at"] = datetime.now()
@@ -142,7 +145,7 @@ class UnitKnowledge(BaseKnowledge[T]):
logger.info(
f"Duration: {(datetime.now() - start_time).total_seconds():.2f} seconds"
)
-
+
return self._data if store else merged_data
def merge(self, data_list: List[T]) -> T:
@@ -164,101 +167,6 @@ class UnitKnowledge(BaseKnowledge[T]):
return result
- def __add__(self, other):
- """Operator overload for '+' to combine UnitKnowledge instances into ListKnowledge.
-
- When two UnitKnowledge instances are added, they are combined into a ListKnowledge
- containing both objects as separate items. This enables intuitive collection building.
-
- Usage:
- >>> unit1 = UnitKnowledge(PersonSchema, ...)
- >>> unit2 = UnitKnowledge(PersonSchema, ...)
- >>> person_list = unit1 + unit2 # → ListKnowledge[PersonSchema]
- >>>
- >>> # Chain operations
- >>> unit3 = UnitKnowledge(PersonSchema, ...)
- >>> person_list = unit1 + unit2 + unit3 # → ListKnowledge with 3 items
-
- Args:
- other: Another UnitKnowledge with the same data schema, or ListKnowledge.
-
- Returns:
- ListKnowledge containing both objects as items.
-
- Raises:
- TypeError: If schemas don't match or invalid operand type.
- """
- from .list import ListKnowledge
-
- # Case 1: UnitKnowledge + UnitKnowledge → ListKnowledge
- if isinstance(other, UnitKnowledge):
- # Check schema compatibility
- if self._data_schema != other._data_schema:
- raise TypeError(
- f"Cannot add UnitKnowledge instances with different schemas. "
- f"Left: {self._data_schema.__name__}, Right: {other._data_schema.__name__}"
- )
-
- # Create new ListKnowledge
- list_kb = ListKnowledge(
- item_schema=self._data_schema,
- llm_client=self.llm_client,
- embedder=self.embedder,
- prompt=self.prompt,
- chunk_size=self.chunk_size,
- chunk_overlap=self.chunk_overlap,
- max_workers=self.max_workers,
- show_progress=self.show_progress,
- )
-
- # Set items from both units
- list_kb._data.items = [self._data, other._data]
-
- # Merge metadata
- list_kb.metadata["created_at"] = min(
- self.metadata["created_at"], other.metadata["created_at"]
- )
- list_kb.metadata["updated_at"] = datetime.now()
-
- return list_kb
-
- # Case 2: UnitKnowledge + ListKnowledge → ListKnowledge (for reverse order)
- elif isinstance(other, ListKnowledge):
- # Check schema compatibility
- if self._data_schema != other.item_schema:
- raise TypeError(
- f"Cannot add UnitKnowledge to ListKnowledge with different schemas. "
- f"Unit: {self._data_schema.__name__}, List: {other.item_schema.__name__}"
- )
-
- # Create new ListKnowledge with unit prepended
- new_list = ListKnowledge(
- item_schema=self._data_schema,
- llm_client=self.llm_client,
- embedder=self.embedder,
- prompt=self.prompt,
- chunk_size=self.chunk_size,
- chunk_overlap=self.chunk_overlap,
- max_workers=self.max_workers,
- show_progress=self.show_progress,
- )
-
- # Prepend self to other's items
- new_list._data.items = [self._data] + other.items
-
- # Merge metadata
- new_list.metadata["created_at"] = min(
- self.metadata["created_at"], other.metadata["created_at"]
- )
- new_list.metadata["updated_at"] = datetime.now()
-
- return new_list
-
- else:
- raise TypeError(
- f"Unsupported operand type for +: 'UnitKnowledge' and '{type(other).__name__}'"
- )
-
# ==================== Indexing & Query ====================
def build_index(self):
@@ -317,10 +225,6 @@ class UnitKnowledge(BaseKnowledge[T]):
logger.info(f"Found {len(results)} results for query: {query[:50]}...")
return results
- def __len__(self) -> int:
- """Returns 1 since UnitKnowledge represents a single knowledge unit."""
- return 1
-
# ==================== Serialization ====================
def dump(self, folder_path: str | Path):
@@ -419,3 +323,100 @@ class UnitKnowledge(BaseKnowledge[T]):
self._index = None
logger.info(f"Loaded knowledge successfully with {len(self)} unit(s)")
+
+ # ==================== Operators ====================
+
+ def __add__(self, other):
+ """Operator overload for '+' to combine UnitKnowledge instances into ListKnowledge.
+
+ When two UnitKnowledge instances are added, they are combined into a ListKnowledge
+ containing both objects as separate items. This enables intuitive collection building.
+
+ Usage:
+ >>> unit1 = UnitKnowledge(PersonSchema, ...)
+ >>> unit2 = UnitKnowledge(PersonSchema, ...)
+ >>> person_list = unit1 + unit2 # → ListKnowledge[PersonSchema]
+ >>>
+ >>> # Chain operations
+ >>> unit3 = UnitKnowledge(PersonSchema, ...)
+ >>> person_list = unit1 + unit2 + unit3 # → ListKnowledge with 3 items
+
+ Args:
+ other: Another UnitKnowledge with the same data schema, or ListKnowledge.
+
+ Returns:
+ ListKnowledge containing both objects as items.
+
+ Raises:
+ TypeError: If schemas don't match or invalid operand type.
+ """
+ from .list import ListKnowledge
+
+ # Case 1: UnitKnowledge + UnitKnowledge → ListKnowledge
+ if isinstance(other, UnitKnowledge):
+ # Check schema compatibility
+ if self._data_schema != other._data_schema:
+ raise TypeError(
+ f"Cannot add UnitKnowledge instances with different schemas. "
+ f"Left: {self._data_schema.__name__}, Right: {other._data_schema.__name__}"
+ )
+
+ # Create new ListKnowledge
+ list_kb = ListKnowledge(
+ item_schema=self._data_schema,
+ llm_client=self.llm_client,
+ embedder=self.embedder,
+ prompt=self.prompt,
+ chunk_size=self.chunk_size,
+ chunk_overlap=self.chunk_overlap,
+ max_workers=self.max_workers,
+ show_progress=self.show_progress,
+ )
+
+ # Set items from both units
+ list_kb._data.items = [self._data, other._data]
+
+ # Merge metadata
+ list_kb.metadata["created_at"] = min(
+ self.metadata["created_at"], other.metadata["created_at"]
+ )
+ list_kb.metadata["updated_at"] = datetime.now()
+
+ return list_kb
+
+ # Case 2: UnitKnowledge + ListKnowledge → ListKnowledge (for reverse order)
+ elif isinstance(other, ListKnowledge):
+ # Check schema compatibility
+ if self._data_schema != other.item_schema:
+ raise TypeError(
+ f"Cannot add UnitKnowledge to ListKnowledge with different schemas. "
+ f"Unit: {self._data_schema.__name__}, List: {other.item_schema.__name__}"
+ )
+
+ # Create new ListKnowledge with unit prepended
+ new_list = ListKnowledge(
+ item_schema=self._data_schema,
+ llm_client=self.llm_client,
+ embedder=self.embedder,
+ prompt=self.prompt,
+ chunk_size=self.chunk_size,
+ chunk_overlap=self.chunk_overlap,
+ max_workers=self.max_workers,
+ show_progress=self.show_progress,
+ )
+
+ # Prepend self to other's items
+ new_list._data.items = [self._data] + other.items
+
+ # Merge metadata
+ new_list.metadata["created_at"] = min(
+ self.metadata["created_at"], other.metadata["created_at"]
+ )
+ new_list.metadata["updated_at"] = datetime.now()
+
+ return new_list
+
+ else:
+ raise TypeError(
+ f"Unsupported operand type for +: 'UnitKnowledge' and '{type(other).__name__}'"
+ )