Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Refactor: Rename LLMEnhancer to LLMExtraction

KaifAhmad15fc188b9eb2c
diff --git a/cookbook/advanced/01_Advanced_Extraction.ipynb b/cookbook/advanced/01_Advanced_Extraction.ipynb
index 2ee96170..c99762e1 100644
--- a/cookbook/advanced/01_Advanced_Extraction.ipynb
+++ b/cookbook/advanced/01_Advanced_Extraction.ipynb
@@ -37,23 +37,60 @@
"\n",
"---\n",
"\n",
- "## Workflow: Event Detection \u2192 Coreference Resolution \u2192 Triplet Extraction \u2192 Semantic Analysis \u2192 Network Extraction \u2192 LLM Enhancement \u2192 Validation\n"
+ "## Workflow: Event Detection → Coreference Resolution → Triplet Extraction → Semantic Analysis → Network Extraction → LLM Enhancement → Validation\n"
]
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 1,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n"
+ ]
+ }
+ ],
"source": [
- "!pip install semantica\n"
+ "!pip install -q semantica"
]
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 2,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "<div style='font-family: monospace;'><h4>🧠 Semantica - 📊 Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>✅</td><td>Semantica is extracting</td><td>🎯 semantic_extract</td><td>EventDetector</td><td>-</td><td>0.01s</td></tr><tr><td>✅</td><td>Semantica is extracting</td><td>🎯 semantic_extract</td><td>CoreferenceResolver</td><td>-</td><td>0.01s</td></tr><tr><td>✅</td><td>Semantica is extracting</td><td>🎯 semantic_extract</td><td>TripletExtractor</td><td>-</td><td>1.32s</td></tr><tr><td>✅</td><td>Semantica is extracting</td><td>🎯 semantic_extract</td><td>NERExtractor</td><td>-</td><td>0.51s</td></tr><tr><td>✅</td><td>Semantica is extracting</td><td>🎯 semantic_extract</td><td>RelationExtractor</td><td>-</td><td>0.00s</td></tr><tr><td>✅</td><td>Semantica is extracting</td><td>🎯 semantic_extract</td><td>SemanticNetworkExtractor</td><td>-</td><td>1.21s</td></tr></table></div>"
+ ],
+ "text/plain": [
+ "<IPython.core.display.HTML object>"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Detected 1 events\n",
+ " Event: founded - founded\n"
+ ]
+ }
+ ],
"source": [
"from semantica.semantic_extract import (\n",
" EventDetector, CoreferenceResolver, TripletExtractor,\n",
@@ -81,9 +118,17 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 3,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Resolved 0 coreference chains\n"
+ ]
+ }
+ ],
"source": [
"coreference_resolver = CoreferenceResolver()\n",
"\n",
@@ -103,9 +148,24 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 4,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "DEBUG: Entity map keys: ['apple inc.', 'steve jobs', '1976', 'tim cook']\n",
+ "DEBUG: Match found! Subject='Apple Inc.', Object='Steve Jobs'\n",
+ "DEBUG: Subject Entity found: True, Object Entity found: True\n",
+ "DEBUG: Match found! Subject='Steve Jobs', Object='1976'\n",
+ "DEBUG: Subject Entity found: True, Object Entity found: True\n",
+ "Extracted 2 triplets\n",
+ " (Apple Inc., founded_by, Steve Jobs)\n",
+ " (Steve Jobs, located_in, 1976)\n"
+ ]
+ }
+ ],
"source": [
"triplet_extractor = TripletExtractor()\n",
"\n",
@@ -127,9 +187,17 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 5,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Analyzed semantic roles: 6\n"
+ ]
+ }
+ ],
"source": [
"semantic_analyzer = SemanticAnalyzer()\n",
"\n",
@@ -149,9 +217,23 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 6,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "DEBUG: Entity map keys: ['apple inc.', 'steve jobs', '1976', 'tim cook']\n",
+ "DEBUG: Match found! Subject='Apple Inc.', Object='Steve Jobs'\n",
+ "DEBUG: Subject Entity found: True, Object Entity found: True\n",
+ "DEBUG: Match found! Subject='Steve Jobs', Object='1976'\n",
+ "DEBUG: Subject Entity found: True, Object Entity found: True\n",
+ "Extracted semantic network with 4 nodes\n",
+ "Edges: 2\n"
+ ]
+ }
+ ],
"source": [
"semantic_network_extractor = SemanticNetworkExtractor()\n",
"\n",
@@ -172,9 +254,21 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 7,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "ename": "AttributeError",
+ "evalue": "'LLMEnhancer' object has no attribute 'enhance_extractions'",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)",
+ "Cell \u001b[1;32mIn[7], line 3\u001b[0m\n\u001b[0;32m 1\u001b[0m llm_enhancer \u001b[38;5;241m=\u001b[39m LLMEnhancer()\n\u001b[1;32m----> 3\u001b[0m enhanced_extractions \u001b[38;5;241m=\u001b[39m \u001b[43mllm_enhancer\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43menhance_extractions\u001b[49m(events, text)\n\u001b[0;32m 5\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mEnhanced \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlen\u001b[39m(enhanced_extractions)\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m extractions\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n",
+ "\u001b[1;31mAttributeError\u001b[0m: 'LLMEnhancer' object has no attribute 'enhance_extractions'"
+ ]
+ }
+ ],
"source": [
"llm_enhancer = LLMEnhancer()\n",
"\n",
@@ -226,10 +320,24 @@
}
],
"metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
"language_info": {
- "name": "python"
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.11.9"
}
},
"nbformat": 4,
"nbformat_minor": 2
-}
\ No newline at end of file
+}
diff --git a/docs/concepts.md b/docs/concepts.md
index 99a01e30..f1ffda0e 100644
--- a/docs/concepts.md
+++ b/docs/concepts.md
@@ -345,7 +345,7 @@ graph LR
```python
from semantica.semantic_extract import (
NamedEntityRecognizer,
- LLMEnhancer,
+ LLMExtraction,
create_provider
)
diff --git a/docs/reference/semantic_extract.md b/docs/reference/semantic_extract.md
index 0679dfad..06238390 100644
--- a/docs/reference/semantic_extract.md
+++ b/docs/reference/semantic_extract.md
@@ -38,8 +38,8 @@
Extract Subject-Predicate-Object triplets for Knowledge Graphs
-- :material-robot:{ .lg .middle } **LLM Enhancement**
-
+- :material-robot:{ .lg .middle } **LLM Extraction**
+
---
Use LLMs to improve extraction quality and handle complex schemas
@@ -340,9 +340,9 @@ print(f"Nodes: {len(network.nodes)}")
print(f"Edges: {len(network.edges)}")
```
-### LLMEnhancer
+### LLMExtraction
-Enhances extraction results using Large Language Models.
+LLM-based extraction and enhancement. (Alias: `LLMEnhancer`)
**Parameters:**
@@ -355,16 +355,17 @@ Enhances extraction results using Large Language Models.
| Method | Description |
|--------|-------------|
+| `enhance_extractions(extractions, text)` | Enhance generic extractions |
| `enhance_entities(text, entities)` | Improve entity accuracy and details |
| `enhance_relations(text, relations)` | Improve relation detection |
**Example:**
```python
-from semantica.semantic_extract import LLMEnhancer
+from semantica.semantic_extract import LLMExtraction
-enhancer = LLMEnhancer(provider="openai", model="gpt-4")
-enhanced_entities = enhancer.enhance_entities(text, entities)
+extractor = LLMExtraction(provider="openai", model="gpt-4")
+enhanced_entities = extractor.enhance_entities(text, entities)
```
---
diff --git a/semantica/semantic_extract/__init__.py b/semantica/semantic_extract/__init__.py
index ce346fee..787ad5a9 100644
--- a/semantica/semantic_extract/__init__.py
+++ b/semantica/semantic_extract/__init__.py
@@ -25,7 +25,7 @@ Main Classes:
- TripletExtractor: RDF triplet extraction (include_temporal, include_provenance)
- SemanticAnalyzer: Semantic analysis engine
- SemanticNetworkExtractor: Semantic network construction
- - LLMEnhancer: LLM-based enhancement
+ - LLMExtraction: LLM-based extraction and enhancement
- ExtractionValidator: Quality validation
Example Usage:
@@ -64,7 +64,7 @@ from .event_detector import (
TemporalEventProcessor,
)
from .extraction_validator import ExtractionValidator, ValidationResult
-from .llm_enhancer import LLMEnhancer, LLMResponse
+from .llm_extraction import LLMEnhancer, LLMExtraction, LLMResponse
from .methods import get_entity_method, get_relation_method, get_triplet_method
from .named_entity_recognizer import (
CustomEntityDetector,
@@ -156,6 +156,7 @@ __all__ = [
"SemanticEdge",
"SemanticNetwork",
# LLM Enhancement
+ "LLMExtraction",
"LLMEnhancer",
"LLMResponse",
# Validation
diff --git a/semantica/semantic_extract/llm_enhancer.py b/semantica/semantic_extract/llm_extraction.py
similarity index 79%
rename from semantica/semantic_extract/llm_enhancer.py
rename to semantica/semantic_extract/llm_extraction.py
index 8ee06447..c57d7450 100644
--- a/semantica/semantic_extract/llm_enhancer.py
+++ b/semantica/semantic_extract/llm_extraction.py
@@ -1,7 +1,7 @@
"""
-LLM Enhancement Module
+LLM Extraction Module
-This module provides LLM-based extraction enhancement capabilities using multiple
+This module provides LLM-based extraction and enhancement capabilities using multiple
language model providers to improve entity and relation extraction quality through
post-processing and refinement.
@@ -38,23 +38,23 @@ Key Features:
- Structured prompt generation for enhancement tasks
Main Classes:
- - LLMEnhancer: Main LLM enhancement coordinator
+ - LLMExtraction: Main LLM extraction coordinator
- LLMResponse: LLM response representation dataclass
Example Usage:
- >>> from semantica.semantic_extract import LLMEnhancer
+ >>> from semantica.semantic_extract import LLMExtraction
>>> # Using OpenAI
- >>> enhancer = LLMEnhancer(provider="openai", model="gpt-4")
- >>> enhanced_entities = enhancer.enhance_entities(text, entities)
- >>> enhanced_relations = enhancer.enhance_relations(text, relations)
+ >>> extractor = LLMExtraction(provider="openai", model="gpt-4")
+ >>> enhanced_entities = extractor.enhance_entities(text, entities)
+ >>> enhanced_relations = extractor.enhance_relations(text, relations)
>>>
>>> # Using Gemini
- >>> enhancer = LLMEnhancer(provider="gemini", model="gemini-pro")
- >>> enhanced_entities = enhancer.enhance_entities(text, entities)
+ >>> extractor = LLMExtraction(provider="gemini", model="gemini-pro")
+ >>> enhanced_entities = extractor.enhance_entities(text, entities)
>>>
>>> # Using Ollama (local)
- >>> enhancer = LLMEnhancer(provider="ollama", model="llama2")
- >>> enhanced_entities = enhancer.enhance_entities(text, entities)
+ >>> extractor = LLMExtraction(provider="ollama", model="llama2")
+ >>> enhanced_entities = extractor.enhance_entities(text, entities)
Author: Semantica Contributors
License: MIT
@@ -81,12 +81,12 @@ class LLMResponse:
metadata: Dict[str, Any]
-class LLMEnhancer:
- """LLM-based extraction enhancer."""
+class LLMExtraction:
+ """LLM-based extraction and enhancement."""
def __init__(self, provider: str = "openai", **config):
"""
- Initialize LLM enhancer.
+ Initialize LLM extraction.
Args:
provider: LLM provider ("openai", "gemini", "groq", "anthropic", "ollama", "huggingface_llm")
@@ -95,7 +95,7 @@ class LLMEnhancer:
- api_key: API key (from environment if not provided)
- temperature: Temperature for generation
"""
- self.logger = get_logger("llm_enhancer")
+ self.logger = get_logger("llm_extraction")
self.config = config
self.progress_tracker = get_progress_tracker()
@@ -110,6 +110,38 @@ class LLMEnhancer:
self.logger.warning(f"Failed to initialize {provider} provider: {e}")
self.provider = None
+ def enhance_extractions(
+ self, extractions: List[Any], text: str, **options
+ ) -> List[Any]:
+ """
+ Enhance generic extractions (entities, relations, etc.).
+
+ Args:
+ extractions: List of extractions
+ text: Input text
+ **options: Enhancement options
+
+ Returns:
+ list: Enhanced extractions
+ """
+ if not extractions:
+ return []
+
+ # Determine type based on first element
+ first = extractions[0]
+
+ # Check for Entity
+ if hasattr(first, "text") and hasattr(first, "label") and hasattr(first, "start_char"):
+ return self.enhance_entities(text, extractions, **options)
+
+ # Check for Relation
+ if hasattr(first, "subject") and hasattr(first, "predicate") and hasattr(first, "object"):
+ return self.enhance_relations(text, extractions, **options)
+
+ # Default/Event fallback (mock implementation for now)
+ self.logger.warning("Extraction type not fully supported for enhancement. Returning original.")
+ return extractions
+
def enhance_entities(
self, text: str, entities: List[Entity], **options
) -> List[Entity]:
@@ -126,7 +158,7 @@ class LLMEnhancer:
"""
tracking_id = self.progress_tracker.start_tracking(
module="semantic_extract",
- submodule="LLMEnhancer",
+ submodule="LLMExtraction",
message="Enhancing entities using LLM",
)
@@ -264,3 +296,7 @@ Return the enhanced relation list in JSON format."""
# Simplified parsing - in practice would parse JSON
# For now, return original relations
return original_relations
+
+
+# Alias for backward compatibility
+LLMEnhancer = LLMExtraction
diff --git a/semantica/semantic_extract/semantic_analyzer.py b/semantica/semantic_extract/semantic_analyzer.py
index 16d0c06c..3a56b7cc 100644
--- a/semantica/semantic_extract/semantic_analyzer.py
+++ b/semantica/semantic_extract/semantic_analyzer.py
@@ -192,6 +192,10 @@ class SemanticAnalyzer:
"""
return self.role_labeler.label_roles(text, **options)
+ def analyze_semantic_roles(self, text: str, **options) -> List[SemanticRole]:
+ """Alias for label_semantic_roles."""
+ return self.label_semantic_roles(text, **options)
+
def cluster_semantically(
self, texts: List[str], **options
) -> List[SemanticCluster]:
diff --git a/semantica/semantic_extract/semantic_network_extractor.py b/semantica/semantic_extract/semantic_network_extractor.py
index 53d5d9b3..da2d02f8 100644
--- a/semantica/semantic_extract/semantic_network_extractor.py
+++ b/semantica/semantic_extract/semantic_network_extractor.py
@@ -77,6 +77,14 @@ class SemanticNode:
properties: Dict[str, Any] = field(default_factory=dict)
metadata: Dict[str, Any] = field(default_factory=dict)
+ def get(self, key: str, default: Any = None) -> Any:
+ """Get attribute value like a dictionary."""
+ return getattr(self, key, default)
+
+ def __getitem__(self, key: str) -> Any:
+ """Get item like a dictionary."""
+ return getattr(self, key)
+
@dataclass
class SemanticEdge:
@@ -88,6 +96,14 @@ class SemanticEdge:
properties: Dict[str, Any] = field(default_factory=dict)
metadata: Dict[str, Any] = field(default_factory=dict)
+ def get(self, key: str, default: Any = None) -> Any:
+ """Get attribute value like a dictionary."""
+ return getattr(self, key, default)
+
+ def __getitem__(self, key: str) -> Any:
+ """Get item like a dictionary."""
+ return getattr(self, key)
+
@dataclass
class SemanticNetwork:
@@ -97,6 +113,14 @@ class SemanticNetwork:
edges: List[SemanticEdge]
metadata: Dict[str, Any] = field(default_factory=dict)
+ def get(self, key: str, default: Any = None) -> Any:
+ """Get attribute value like a dictionary."""
+ return getattr(self, key, default)
+
+ def __getitem__(self, key: str) -> Any:
+ """Get item like a dictionary."""
+ return getattr(self, key)
+
class SemanticNetworkExtractor:
"""Semantic network extractor for structured networks."""
@@ -316,6 +340,7 @@ class SemanticNetworkExtractor:
Args:
network: Semantic network
+ **options: Analysis options
Returns:
dict: Network analysis
diff --git a/semantica/semantic_extract/triplet_extractor.py b/semantica/semantic_extract/triplet_extractor.py
index e000ede6..7387f035 100644
--- a/semantica/semantic_extract/triplet_extractor.py
+++ b/semantica/semantic_extract/triplet_extractor.py
@@ -84,6 +84,14 @@ class Triplet:
confidence: float = 1.0
metadata: Dict[str, Any] = field(default_factory=dict)
+ def get(self, key: str, default: Any = None) -> Any:
+ """Get attribute value like a dictionary."""
+ return getattr(self, key, default)
+
+ def __getitem__(self, key: str) -> Any:
+ """Get item like a dictionary."""
+ return getattr(self, key)
+
class TripletExtractor:
"""RDF triplet extraction handler."""