Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
docs: Update context and embeddings reference docs with grid cards
KaifAhmad19445d96fff5b
diff --git a/docs/reference/context.md b/docs/reference/context.mdindex 3e304aca..6b3ab2e5 100644--- a/docs/reference/context.md+++ b/docs/reference/context.md@@ -10,11 +10,39 @@ The **Context Module** provides agents with a persistent, searchable, and struct### Key Capabilities-* **Hierarchical Memory**: A two-tier memory system that mimics human memory (Short-term "Working" Memory + Long-term "Episodic" Memory).-* **GraphRAG**: Combines unstructured vector search with structured knowledge graph traversal for richer context.-* **Hybrid Retrieval**: Intelligently blends results from keyword matching, vector similarity, and graph connections.-* **Token Management**: Automatically prunes short-term memory to fit within LLM context windows using token-based constraints.-* **Entity Linking**: Resolves ambiguities by linking text mentions to unique entities in the knowledge graph.+<div class="grid cards" markdown>++- :material-brain:{ .lg .middle } **Hierarchical Memory**++ ---++ Mimics human memory with a fast, token-limited Short-Term buffer and infinite Long-Term vector storage.++- :material-graph-outline:{ .lg .middle } **GraphRAG**++ ---++ Combines unstructured vector search with structured knowledge graph traversal for deep contextual understanding.++- :material-scale-balance:{ .lg .middle } **Hybrid Retrieval**++ ---++ Intelligently blends Keyword (BM25), Vector (Dense), and Graph (Relational) scores for optimal relevance.++- :material-lightning-bolt:{ .lg .middle } **Token Management**++ ---++ Automatic FIFO and importance-based pruning to keep context within LLM window limits.++- :material-link-variant:{ .lg .middle } **Entity Linking**++ ---++ Resolves ambiguities by linking text mentions to unique entities in the knowledge graph.++</div>---@@ -42,6 +70,29 @@ The high-level facade that unifies all context operations. It routes data to the* *Reranking*: Merges and ranks results based on relevance scores.* *Context Window Optimization*: Returns results that fit within the agent's context window.+#### **Code Example**+```python+from semantica.context import AgentContext+from semantica.vector_store import VectorStore++# 1. Initialize+vs = VectorStore(backend="faiss", dimension=768)+context = AgentContext(+ vector_store=vs,+ token_limit=2000+)++# 2. Store Memory+context.store(+ "User is working on a React project.",+ conversation_id="session_1",+ user_id="user_123"+)++# 3. Retrieve Context+results = context.retrieve("What is the user building?")+```+---### 2. AgentMemory (The Storage Engine)@@ -67,6 +118,21 @@ Manages the storage and lifecycle of memory items. It implements the **Hierarchi* `_prune_short_term_memory()`: Internal algorithm that enforces token and count limits.* `get_conversation_history()`: Retrieves a chronological list of interactions for a specific session.+#### **Code Example**+```python+# Accessing via AgentContext+memory = context.memory++# Get conversation history+history = memory.get_conversation_history("session_1")+for item in history:+ print(f"[{item.timestamp}] {item.content}")++# Get statistics+stats = memory.get_statistics()+print(f"Stored Memories: {stats['total_memories']}")+```+---### 3. ContextGraph (The Knowledge Structure)@@ -88,6 +154,39 @@ Manages the structured relationships between entities. It provides the "World Mo* `get_neighbors(node_id, hops)`: Returns connected nodes within a specified distance.* `query(query_str)`: Performs keyword-based search specifically on graph nodes.+#### **Code Example**+```python+from semantica.context import ContextGraph++graph = ContextGraph()++# Add Nodes+graph.add_nodes([+ {+ "id": "Python",+ "type": "Language",+ "properties": {"paradigm": "OO"}+ },+ {+ "id": "FastAPI",+ "type": "Framework",+ "properties": {"language": "Python"}+ }+])++# Add Edges+graph.add_edges([+ {+ "source": "FastAPI",+ "target": "Python",+ "type": "WRITTEN_IN"+ }+])++# Find Neighbors+neighbors = graph.get_neighbors("FastAPI", hops=1)+```+---### 4. ContextRetriever (The Search Engine)@@ -104,6 +203,44 @@ The retrieval logic that powers the `retrieve()` command. It implements the **Hy* Formula: `Final_Score = (Vector_Score * (1 - α)) + (Graph_Score * α)`* Allows tuning the balance between semantic similarity and structural relevance.+#### **Code Example**+```python+# The retriever is automatically used by AgentContext.retrieve()+# But can be accessed directly if needed:++retriever = context.retriever++# Perform a manual retrieval+results = retriever.retrieve(+ query="web frameworks",+ max_results=5+)+```++---++### 5. EntityLinker (The Connector)+Resolves text mentions to unique entities and assigns URIs.++#### **Key Methods**+* `link_entities(source, target, type)`: Creates a link between two entities.+* `assign_uri(entity_name, type)`: Generates a consistent URI for an entity.++#### **Code Example**+```python+from semantica.context import EntityLinker++linker = EntityLinker(knowledge_graph=graph)++# Link two entities+linker.link_entities(+ source_entity_id="Python",+ target_entity_id="Programming",+ link_type="IS_A",+ confidence=0.95+)+```+---## ⚙️ Configuration & Tuning@@ -159,3 +296,34 @@ class MemoryItem:"weight": 0.8}```++---++## 🧩 Advanced Usage++### Method Registry (Extensibility)+Register custom implementations for graph building, memory management, or retrieval.++#### **Code Example**+```python+from semantica.context import registry++def custom_graph_builder(entities, relationships):+ # Custom logic to build graph+ return "my_graph_structure"++# Register the new method+registry.register("graph", "custom_builder", custom_graph_builder)+```++### Configuration Manager+Programmatically manage configuration settings.++#### **Code Example**+```python+from semantica.context.config import context_config++# Update configuration at runtime+context_config.set("retention_days", 60)+context_config.set("hybrid_alpha", 0.8)+```diff --git a/docs/reference/embeddings.md b/docs/reference/embeddings.mdindex 614d857b..7e0338be 100644--- a/docs/reference/embeddings.md+++ b/docs/reference/embeddings.md@@ -1,162 +1,145 @@-# Embeddings+# Embeddings Module Reference> **Text embedding generation with multiple model support.**----## 🎯 Overview+## 🎯 System Overview++The **Embeddings Module** provides a unified interface for generating vector representations of text. It abstracts away the complexity of different providers (OpenAI, HuggingFace, FastEmbed) and ensures consistent formatting for vector databases.++### Key Capabilities<div class="grid cards" markdown>-- :material-text-box:{ .lg .middle } **Text Embeddings**+- :material-power-plug:{ .lg .middle } **Multi-Provider Support**---- Sentence-transformers, OpenAI, BGE, and FastEmbed model support+ Seamlessly switch between Sentence Transformers, FastEmbed, OpenAI, and BGE models.-- :material-vector-square:{ .lg .middle } **Vector Databases**+- :material-api:{ .lg .middle } **Unified Interface**---- Specialized managers for vector database integration (FAISS, Pinecone, Qdrant, etc.)+ Single API for all embedding backends with consistent normalization and output formatting.-- :material-graph:{ .lg .middle } **Graph Databases**+- :material-rocket-launch:{ .lg .middle } **Efficient Batching**---- Specialized managers for graph database integration (Neo4j, NetworkX, etc.)+ Optimized batch processing and pooling strategies for high-throughput embedding generation.-- :material-compress:{ .lg .middle } **Pooling Strategies**+- :material-database-check:{ .lg .middle } **Vector DB Ready**---- Mean, Max, CLS, Attention, and Hierarchical pooling for aggregation+ Automatic formatting and validation for FAISS, Pinecone, Qdrant, and Weaviate.</div>-!!! tip "When to Use"- - **Semantic Search**: Converting text to vectors for similarity search- - **Clustering**: Grouping similar documents- - **Classification**: Using embeddings as features for ML models- - **RAG**: Embedding chunks for retrieval- - **Vector Databases**: Preparing embeddings for FAISS, Pinecone, Qdrant, etc.- - **Graph Databases**: Creating node and edge embeddings for Neo4j, KuzuDB, FalkorDB, etc.-------## ⚙️ Algorithms Used--### Generation-- **Transformer Encoding**: BERT/RoBERTa based models for text (sentence-transformers).-- **FastEmbed Encoding**: Fast and efficient embedding generation using FastEmbed library.-- **Provider Adapters**: OpenAI, BGE, Llama, and FastEmbed adapters for different providers.--### Pooling-- **Mean Pooling**: Arithmetic mean across embedding dimension.-- **Max Pooling**: Element-wise maximum across embedding dimension.-- **CLS Token Pooling**: First token/embedding extraction (for transformer models).-- **Attention-based Pooling**: Softmax-weighted sum using dot product attention scores.-- **Hierarchical Pooling**: Two-level pooling (chunk-level then global-level mean pooling).-----## Main Classes+## 🏗️ Architecture Components-### EmbeddingGenerator+### 1. EmbeddingGenerator (The Orchestrator)+The main entry point for generating embeddings. It manages the active model and routes requests to the appropriate provider adapter.-Unified interface for text embedding generation.+#### **Constructor Parameters**+* `method` (Default: `"fastembed"`): The embedding provider to use (e.g., `"sentence_transformers"`, `"openai"`, `"fastembed"`).+* `model_name` (Optional): Specific model name (e.g., `"all-MiniLM-L6-v2"`, `"text-embedding-3-small"`).+* `device` (Default: `"cpu"`): Computing device (`"cpu"`, `"cuda"`, `"mps"`).+* `normalize` (Default: `True`): Whether to L2-normalize embeddings (crucial for cosine similarity).-**Methods:**--| Method | Description |-|--------|-------------|-| `generate_embeddings(data, data_type="text")` | Generate embedding |-| `process_batch(items)` | Batch generation |-| `compare_embeddings(emb1, emb2, method="cosine")` | Calculate similarity |-| `get_text_method()` | Get active text embedding method |-| `get_methods_info()` | Get detailed method information |--**Example:**+#### **Core Methods**+* **`generate_embeddings(data, data_type="text")`**: Generates an embedding for a single item.+* **`process_batch(items)`**: Generates embeddings for a list of items (optimized).+* **`compare_embeddings(emb1, emb2)`**: Calculates cosine similarity between two vectors.+* **`get_text_method()`**: Returns the active embedding strategy.+#### **Code Example**```pythonfrom semantica.embeddings import EmbeddingGenerator-gen = EmbeddingGenerator()-vec = gen.generate_embeddings("Hello world", data_type="text")-```+# 1. Initialize+gen = EmbeddingGenerator(+ method="sentence_transformers",+ model_name="all-MiniLM-L6-v2"+)-### TextEmbedder+# 2. Generate+vector = gen.generate_embeddings("Hello world")-Specialized text embedding generation.+# 3. Compare+vec1 = gen.generate_embeddings("AI is great")+vec2 = gen.generate_embeddings("Machine learning is awesome")+similarity = gen.compare_embeddings(vec1, vec2)+print(f"Similarity: {similarity}")+```-**Methods:**+----| Method | Description |-|--------|-------------|-| `embed_text(text)` | Generate vector for single text |-| `embed_batch(texts)` | Batch processing |-| `get_method()` | Get active embedding method |-| `get_model_info()` | Get detailed model information |-| `get_embedding_dimension()` | Get embedding dimension |+### 2. TextEmbedder (The Worker)+A specialized class focused purely on text-to-vector operations. It wraps the `EmbeddingGenerator` with text-specific logic and simplified methods.-**Example:**+#### **Core Methods**+* **`embed_text(text)`**: Returns a list of floats for the input string.+* **`embed_batch(texts)`**: Returns a list of lists (vectors) for the input strings.+* **`get_embedding_dimension()`**: Returns the size of the output vector (e.g., 384, 768, 1536).+#### **Code Example**```pythonfrom semantica.embeddings import TextEmbedder+# Initialize with FastEmbed (lightweight, fast)embedder = TextEmbedder(method="fastembed")-vec = embedder.embed_text("Hello world")-```--### VectorEmbeddingManager-Manages embeddings for vector databases.+# Single text+vector = embedder.embed_text("Semantica is powerful")-**Methods:**--| Method | Description |-|--------|-------------|-| `prepare_for_vector_db(embeddings, backend, ...)` | Prepare embeddings for vector DB |-| `batch_prepare(embeddings_list, ...)` | Batch preparation |-| `validate_dimensions(embeddings, expected_dim)` | Validate embedding dimensions |--### GraphEmbeddingManager--Manages embeddings for graph databases.--**Methods:**+# Batch processing (Recommended for speed)+texts = ["Document 1", "Document 2", "Document 3"]+vectors = embedder.embed_batch(texts)-| Method | Description |-|--------|-------------|-| `prepare_for_graph_db(entities, relationships, ...)` | Prepare embeddings for graph DB |-| `embed_entities(entities, ...)` | Generate entity embeddings |-| `embed_relationships(relationships, ...)` | Generate relationship embeddings |+print(f"Dimension: {embedder.get_embedding_dimension()}")+```----## Convenience Functions+### 3. VectorEmbeddingManager (The Bridge)+A utility class that prepares raw embeddings for insertion into specific vector databases. It handles formatting differences between backends like FAISS and Pinecone.+#### **Core Methods**+* **`prepare_for_vector_db(embeddings, backend, ...)`**: Formats data for the target DB.+* **`validate_dimensions(embeddings, expected_dim)`**: Ensures vectors match the index configuration.+* **`batch_prepare(embeddings_list)`**: Prepares a batch of embeddings for storage.++#### **Code Example**```python-from semantica.embeddings import embed_text, calculate_similarity, check_available_providers+from semantica.embeddings import VectorEmbeddingManager, TextEmbedder-# Generate embeddings-emb1 = embed_text("text1", method="sentence_transformers")-emb2 = embed_text("text2", method="fastembed")+# 1. Generate Embeddings+embedder = TextEmbedder()+texts = ["Doc A", "Doc B"]+embeddings = embedder.embed_batch(texts)-# Similarity-score = calculate_similarity(emb1, emb2)+# 2. Format for FAISS+manager = VectorEmbeddingManager()+formatted_data = manager.prepare_for_vector_db(+ embeddings,+ metadata=[{"id": 1, "text": "Doc A"}, {"id": 2, "text": "Doc B"}],+ backend="faiss"+)-# Check available providers-providers = check_available_providers()-if providers["fastembed"]:- print("FastEmbed is available")+# formatted_data is now ready to be passed to VectorStore```----## Configuration+## ⚙️ Configuration & Tuning### Environment Variables+You can configure defaults globally using `.env` files.```bashexport EMBEDDING_MODEL=all-MiniLM-L6-v2@@ -165,6 +148,7 @@ export OPENAI_API_KEY=sk-...```### YAML Configuration+For project-specific settings.```yamlembeddings:@@ -177,76 +161,27 @@ embeddings:----## Integration Examples+## 🚀 Best Practices-### Text Embedding with Multiple Methods+1. **Batch Processing**: Always use `embed_batch` or `process_batch` when dealing with multiple items. It is significantly faster, especially on GPUs.+2. **Normalization**: Keep `normalize=True` (default) if you intend to use Cosine Similarity.+3. **Dimension Matching**: Ensure your `VectorStore` index is created with the same dimension as your embedding model (e.g., 384 for MiniLM, 1536 for OpenAI Ada).+4. **Caching**: Embeddings are compute-intensive. Cache results where possible to avoid re-computing vectors for the same text.-```python-from semantica.embeddings import TextEmbedder, check_available_providers-from semantica.vector_store import VectorStore--# Check available providers-providers = check_available_providers()--# Use FastEmbed if available, otherwise sentence-transformers-if providers["fastembed"]:- embedder = TextEmbedder(method="fastembed", model_name="BAAI/bge-small-en-v1.5")-else:- embedder = TextEmbedder(method="sentence_transformers")--# Generate embeddings-texts = ["Machine learning", "Artificial intelligence", "Deep learning"]-embeddings = embedder.embed_batch(texts)--# Store in vector database-store = VectorStore()-store.store_vectors(embeddings, metadata=[{"text": t} for t in texts])+----# Search-query_emb = embedder.embed_text("neural networks")-results = store.search(query_emb, k=2)-print(f"Found {len(results)} similar texts")-```+## 🧩 Advanced Usage-### Using Vector Embedding Manager+### Checking Available Providers+Dynamically check which embedding backends are installed and available.```python-from semantica.embeddings import VectorEmbeddingManager, TextEmbedder--# Generate embeddings-embedder = TextEmbedder()-texts = ["Document 1", "Document 2", "Document 3"]-embeddings = embedder.embed_batch(texts)+from semantica.embeddings import check_available_providers-# Prepare for vector database-manager = VectorEmbeddingManager()-formatted = manager.prepare_for_vector_db(- embeddings,- metadata=[{"id": i, "text": t} for i, t in enumerate(texts)],- backend="faiss"-)+providers = check_available_providers()-# Use formatted data with your vector database-print(f"Prepared {len(formatted['ids'])} vectors for {formatted['backend']}")+if providers["fastembed"]:+ print("FastEmbed is ready!")+if providers["openai"]:+ print("OpenAI is configured!")```-------## Best Practices--1. **Batch Processing**: Always use batch methods (`embed_batch`, `process_batch`) for >1 item. It's much faster on GPU.-2. **Use Caching**: Embeddings are expensive to compute. Cache them if possible.-3. **Match Dimensions**: Ensure your vector store is configured with the correct dimension for your chosen model.-4. **Normalize**: L2 normalization is usually required for Cosine Similarity to work correctly.-------## See Also--- [Vector Store Module](vector_store.md) - Storing the generated vectors-- [Ingest Module](ingest.md) - Loading data to embed-- [Pipeline Module](pipeline.md) - Orchestrating the embedding process--## Cookbook--- [Embedding Generation](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/12_Embedding_Generation.ipynb)