How to Use Semantica Components Independently: A Modular Import Guide
You can import any Semantica submodule directly without loading the entire framework, thanks to a lazy-loading _ModuleProxy implementation in the top-level __init__.py that defers imports until first access.
The semantica-agi/semantica repository is organized as a single-entry-point package where functional areas—knowledge graphs, vector stores, and semantic extraction—live in isolated subpackages. This architecture lets you use Semantica components independently in microservices, notebooks, or data pipelines while maintaining a consistent namespace.
Understanding the Module Proxy Architecture
The framework implements lazy loading through a _ModuleProxy class defined in [semantica/__init__.py](https://github.com/semantica-agi/semantica/blob/main/semantica/__init__.py). When you access an attribute like semantica.kg or semantica.vector_store, the proxy's __getattr__ method intercepts the lookup and imports the real submodule only at that moment.
This design means:
- No upfront cost: Importing
semanticadoes not execute submodule code - True isolation: You pay the memory cost only for components you actually touch
- Clean namespace: All submodules remain accessible through the top-level package
Importing Knowledge Graph Components Independently
The Knowledge Graph (KG) API exposes GraphBuilder, CentralityCalculator, and GraphAnalyzer through [semantica/kg/__init__.py](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/__init__.py). Import only what you need for graph construction and analysis:
from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator
# Build a graph with entity merging enabled
builder = GraphBuilder(merge_entities=True)
kg = builder.build(
sources=[
{
"entities": [
{"id": "alice", "type": "Person"},
{"id": "bob", "type": "Person"},
],
"relationships": [
{"source": "alice", "target": "bob", "type": "knows"},
],
}
]
)
# Run analytics without touching vector stores or extraction pipelines
analyzer = GraphAnalyzer()
analysis = analyzer.analyze_graph(kg)
centrality_calc = CentralityCalculator()
degree_scores = centrality_calc.calculate_degree_centrality(kg)
print("Graph analysis:", analysis)
print("Degree centrality:", degree_scores)
Using the Vector Store in Isolation
The vector store subsystem in [semantica/vector_store/__init__.py](https://github.com/semantica-agi/semantica/blob/main/semantica/vector_store/__init__.py) provides VectorStore, FAISSStore, and HybridSearch classes, plus convenience functions store_vectors and search_vectors. Use these for embedding storage and retrieval without importing KG logic:
import numpy as np
from semantica.vector_store import VectorStore, store_vectors, search_vectors
# Initialize an in-memory FAISS backend (dimension = 768)
store = VectorStore(backend="faiss", dimension=768)
# Generate sample embeddings
vectors = np.random.rand(3, 768).astype("float32")
metadata = [{"title": "Doc A"}, {"title": "Doc B"}, {"title": "Doc C"}]
# Store vectors—returns generated UUIDs
vector_ids = store_vectors(vectors, metadata=metadata, method="default")
# Search for top-2 nearest neighbors
query = np.random.rand(1, 768).astype("float32")
results = search_vectors(query, k=2, method="default")
print("Stored IDs:", vector_ids)
print("Search results:", results)
Running Semantic Extraction Without the Full Framework
The semantic_extract subpackage provides SemanticExtractor and NamedEntityRecognizer through the same proxy mechanism. This allows text-only pipelines that ignore graph and vector dependencies:
from semantica.semantic_extract import SemanticExtractor, NamedEntityRecognizer
text = """
Semantica is an open-source framework that turns unstructured text into knowledge graphs.
It supports entity resolution, temporal reasoning and vector-store integration.
"""
# Extract subject-predicate-object triples
extractor = SemanticExtractor()
triples = extractor.extract_triplets(text)
# Perform named entity recognition
ner = NamedEntityRecognizer()
entities = ner.recognize(text)
print("Extracted triples:", triples)
print("Named entities:", entities)
Combining Select Components in Custom Workflows
Because each submodule maintains its own namespace, you can mix components à la carte. This example uses only KG construction and vector storage, omitting extraction logic:
from semantica.kg import GraphBuilder
from semantica.vector_store import VectorStore, store_vectors, search_vectors
import numpy as np
# 1. Build a knowledge graph
builder = GraphBuilder()
kg = builder.build(sources=[{"entities": [{"id": "node1", "type": "Concept"}], "relationships": []}])
# 2. Generate node embeddings (placeholder for your embedding logic)
node_embeddings = np.random.rand(10, 128).astype("float32")
# 3. Store in vector backend
store = VectorStore(backend="faiss", dimension=128)
ids = store_vectors(node_embeddings, metadata=[{"node_id": f"node_{i}"} for i in range(10)])
# 4. Query similar nodes
query_vec = np.random.rand(1, 128).astype("float32")
similar = search_vectors(query_vec, k=3)
print("Similar nodes:", similar)
Summary
- Single-entry-point design: The
_ModuleProxyinsemantica/__init__.pyenables lazy loading of submodules - Direct imports work:
from semantica.kg import GraphBuilderloads only the KG package, not the full framework - Component isolation: Use
VectorStorewithout KG dependencies, orSemanticExtractorwithout vector stores - Consistent API: All submodules expose clean
__init__.pyinterfaces that re-export public classes likeCentralityCalculatorandHybridSearch
Frequently Asked Questions
Does importing a single component load the entire Semantica framework?
No. The _ModuleProxy class in semantica/__init__.py intercepts attribute access and imports submodules only when first accessed. When you write from semantica.kg import GraphBuilder, Python loads only the semantica.kg package and its dependencies, leaving semantica.vector_store and other modules uninitialized.
Can I use the vector store without installing knowledge graph dependencies?
Yes. Because each functional area is a standalone subpackage with its own __init__.py, you can install and import semantica.vector_store independently. The FAISSStore and HybridSearch classes in semantica/vector_store/__init__.py do not import from semantica.kg, allowing isolated deployment in embedding-only microservices.
How does the proxy mechanism handle missing submodules?
The _ModuleProxy raises a standard AttributeError with a descriptive message if you attempt to access a non-existent submodule (e.g., semantica.nonexistent). This behaves identically to normal Python module attribute resolution, ensuring compatibility with IDEs and static analysis tools that rely on __getattr__ behavior.
Is it possible to extend Semantica with custom components using this architecture?
Yes. You can create a new subpackage (e.g., semantica/custom_ml) following the same pattern: define your classes in the subpackage and add a re-export in that subpackage's __init__.py. The top-level _ModuleProxy will automatically make it available via semantica.custom_ml when users first access that attribute, maintaining the lazy-loading contract.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →