Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Refactor: Clean up 01_Welcome_to_Semantica notebook

KaifAhmad18b3680cd1416
diff --git a/cookbook/introduction/01_Welcome_to_Semantica.ipynb b/cookbook/introduction/01_Welcome_to_Semantica.ipynb
index 96b8f1f7..23fb4bf6 100644
--- a/cookbook/introduction/01_Welcome_to_Semantica.ipynb
+++ b/cookbook/introduction/01_Welcome_to_Semantica.ipynb
@@ -339,597 +339,8 @@
" .build()\n",
"```\n",
"\n",
- "---\n",
- "\n",
- "## Key Concepts Explained\n",
- "\n",
- "Understanding these concepts is crucial for working with Semantica:\n",
- "\n",
- "### 1. KNOWLEDGE GRAPHS\n",
- "**Definition**: A knowledge graph is a structured representation of entities (nodes) and their relationships (edges) with properties and attributes.\n",
- "\n",
- "**Structure**:\n",
- "- **Nodes**: Represent entities (people, places, concepts, events)\n",
- "- **Edges**: Represent relationships (works_for, located_in, causes)\n",
- "- **Properties**: Attributes of entities and relationships\n",
- "- **Metadata**: Additional information (sources, timestamps, confidence)\n",
- "\n",
- "**Example**:\n",
- "- Entity: \"John Doe\" (Person)\n",
- "- Relationship: \"works_for\" -> \"Acme Corp\" (Organization)\n",
- "- Properties: `{start_date: \"2020-01-01\", role: \"Engineer\"}`\n",
- "\n",
- "**Benefits**:\n",
- "- Structured representation of unstructured data\n",
- "- Enables complex queries and reasoning\n",
- "- Supports temporal tracking\n",
- "- Facilitates knowledge discovery\n",
- "\n",
- "### 2. ENTITY EXTRACTION (NER - Named Entity Recognition)\n",
- "**Definition**: The process of identifying and classifying named entities in text into predefined categories.\n",
- "\n",
- "**Entity Types**:\n",
- "- **Person**: Names of people\n",
- "- **Organization**: Companies, institutions\n",
- "- **Location**: Places, geographic entities\n",
- "- **Date/Time**: Temporal expressions\n",
- "- **Money**: Monetary values\n",
- "- **Product**: Products and services\n",
- "- **Event**: Events and occurrences\n",
- "- **Custom**: Domain-specific entities\n",
- "\n",
- "**Example**:\n",
- "Text: \"Apple Inc. was founded by Steve Jobs in Cupertino, California.\"\n",
- "Entities:\n",
- "- \"Apple Inc.\" -> Organization\n",
- "- \"Steve Jobs\" -> Person\n",
- "- \"Cupertino, California\" -> Location\n",
- "\n",
- "**Methods**:\n",
- "- Rule-based: Pattern matching\n",
- "- Machine Learning: Trained models (spaCy, transformers)\n",
- "- LLM-based: Using large language models\n",
- "\n",
- "### 3. RELATIONSHIP EXTRACTION\n",
- "**Definition**: Identifying and extracting relationships between entities in text.\n",
- "\n",
- "**Relationship Types**:\n",
- "- **Semantic**: \"works_for\", \"located_in\", \"causes\"\n",
- "- **Temporal**: \"before\", \"after\", \"during\"\n",
- "- **Causal**: \"causes\", \"results_in\", \"prevents\"\n",
- "- **Hierarchical**: \"part_of\", \"subclass_of\", \"instance_of\"\n",
- "\n",
- "**Example**:\n",
- "Text: \"John works for Acme Corp in New York.\"\n",
- "Relationships:\n",
- "- (John, works_for, Acme Corp)\n",
- "- (Acme Corp, located_in, New York)\n",
- "\n",
- "**Methods**:\n",
- "- Pattern matching\n",
- "- Dependency parsing\n",
- "- Machine learning models\n",
- "- LLM-based extraction\n",
- "\n",
- "### 4. EMBEDDINGS\n",
- "**Definition**: Dense vector representations of text, images, or other data that capture semantic meaning in a continuous vector space.\n",
- "\n",
- "**Properties**:\n",
- "- Similar entities have similar embeddings (close in vector space)\n",
- "- Enable semantic search and similarity calculations\n",
- "- Fixed or variable dimensions (typically 128-4096)\n",
- "\n",
- "**Example**:\n",
- "Text: \"machine learning\"\n",
- "Embedding: `[0.123, -0.456, 0.789, ..., 0.234]` (vector of 1536 dimensions)\n",
- "\n",
- "**Use Cases**:\n",
- "- Semantic search\n",
- "- Clustering and classification\n",
- "- Recommendation systems\n",
- "- Anomaly detection\n",
- "\n",
- "### 5. TEMPORAL GRAPHS\n",
- "**Definition**: Knowledge graphs that track changes over time, allowing queries about the state of the graph at specific time points.\n",
- "\n",
- "**Features**:\n",
- "- Timestamps on entities and relationships\n",
- "- Version history\n",
- "- Time-point queries\n",
- "- Temporal pattern detection\n",
- "\n",
- "**Example**:\n",
- "- Entity: \"Company X\"\n",
- "- Relationship: (Company X, has_CEO, Person Y)\n",
- "- Temporal: `valid_from=\"2020-01-01\", valid_to=\"2023-12-31\"`\n",
- "\n",
- "**Use Cases**:\n",
- "- Tracking organizational changes\n",
- "- Monitoring system evolution\n",
- "- Analyzing trends over time\n",
- "- Historical analysis\n",
- "\n",
- "### 6. GraphRAG (Graph-based Retrieval Augmented Generation)\n",
- "**Definition**: An advanced RAG approach that combines vector search with knowledge graph traversal to provide more accurate and contextually relevant information to LLMs.\n",
- "\n",
- "**Components**:\n",
- "- **Vector Store**: For semantic similarity search\n",
- "- **Knowledge Graph**: For structured relationship traversal\n",
- "- **Hybrid Search**: Combines both approaches\n",
- "- **LLM Integration**: Uses retrieved context for generation\n",
- "\n",
- "**Advantages over Traditional RAG**:\n",
- "- Better handling of complex queries\n",
- "- Relationship-aware retrieval\n",
- "- Reduced hallucinations\n",
- "- More accurate answers\n",
- "\n",
- "**Example Workflow**:\n",
- "1. Query: \"Who worked with John at Acme Corp?\"\n",
- "2. Vector search finds relevant documents\n",
- "3. Knowledge graph traversal finds relationships\n",
- "4. Combined context sent to LLM\n",
- "5. LLM generates accurate answer using both sources\n",
- "\n",
- "### 7. ONTOLOGY\n",
- "**Definition**: A formal specification of concepts, relationships, and constraints in a domain, typically expressed in OWL (Web Ontology Language).\n",
- "\n",
- "**Components**:\n",
- "- **Classes**: Categories of entities\n",
- "- **Properties**: Relationships and attributes\n",
- "- **Individuals**: Specific instances\n",
- "- **Axioms**: Rules and constraints\n",
- "\n",
- "**Example**:\n",
- "- Class: Person\n",
- "- SubClass: Employee, Customer\n",
- "- Property: worksFor (domain: Person, range: Organization)\n",
- "\n",
- "**Use Cases**:\n",
- "- Standardize domain knowledge\n",
- "- Enable reasoning\n",
- "- Facilitate data integration\n",
- "- Support semantic web\n",
- "\n",
- "### 8. QUALITY ASSURANCE\n",
- "**Definition**: Processes and metrics to ensure knowledge graph quality, including completeness, consistency, and accuracy.\n",
- "\n",
- "**Metrics**:\n",
- "- **Completeness**: Percentage of entities with required properties\n",
- "- **Consistency**: Absence of contradictions\n",
- "- **Accuracy**: Correctness of extracted information\n",
- "- **Coverage**: Breadth of domain coverage\n",
- "\n",
- "**Methods**:\n",
- "- Validation rules\n",
- "- Automated quality checks\n",
- "- Conflict detection\n",
- "- Source verification\n",
- "\n",
- "---\n",
- "\n",
- "## Next Steps\n",
- "\n",
- "Now that you understand the basics, here are recommended next steps:\n",
- "\n",
- "1. **Your First Knowledge Graph** (`01_Your_First_Knowledge_Graph.ipynb`)\n",
- " - Build your first knowledge graph from a document\n",
- " - Learn the basic workflow\n",
- "\n",
- "2. **Configuration Basics** (`02_Configuration_Basics.ipynb`)\n",
- " - Set up configuration files\n",
- " - Configure API keys and providers\n",
- "\n",
- "3. **Core Workflows** (`01_core_workflows/`)\n",
- " - Learn common patterns and workflows\n",
- " - Start with \"From Unstructured to Structured\"\n",
- "\n",
- "4. **Use Cases** (`03_use_cases/`)\n",
- " - Explore domain-specific applications\n",
- " - Find examples relevant to your domain\n",
- "\n",
- "---\n",
- "\n",
- "## Best Practices\n",
- "\n",
- "### 1. START SMALL\n",
- "- Begin with simple documents\n",
- "- Validate each step before moving forward\n",
- "- Build incrementally\n",
- "\n",
- "### 2. CONFIGURE PROPERLY\n",
- "- Use environment variables for sensitive data\n",
- "- Set up proper logging\n",
- "- Configure appropriate model sizes\n",
- "\n",
- "### 3. VALIDATE DATA\n",
- "- Always validate extracted entities\n",
- "- Check relationship quality\n",
- "- Use quality assurance tools\n",
- "\n",
- "### 4. HANDLE ERRORS\n",
- "- Implement error handling\n",
- "- Use retry mechanisms\n",
- "- Log errors for debugging\n",
- "\n",
- "### 5. OPTIMIZE PERFORMANCE\n",
- "- Use batch processing for large datasets\n",
- "- Enable parallel processing where possible\n",
- "- Cache embeddings and results\n",
- "\n",
- "### 6. DOCUMENT YOUR WORKFLOWS\n",
- "- Document data sources\n",
- "- Track processing steps\n",
- "- Maintain metadata\n",
- "\n",
- "---\n",
- "\n",
- "## Troubleshooting\n",
- "\n",
- "Common issues and solutions:\n",
- "\n",
- "### Issue 1: Import Errors\n",
- "**Solution**:\n",
- "- Ensure Semantica is properly installed\n",
- "- Check Python version (3.8+)\n",
- "- Verify virtual environment is activated\n",
- "- Install missing dependencies: `pip install -r requirements.txt`\n",
- "\n",
- "### Issue 2: API Key Errors\n",
- "**Solution**:\n",
- "- Set environment variables: `export SEMANTICA_API_KEY=your_key`\n",
- "- Check config file for correct key format\n",
- "- Verify API key is valid and has sufficient credits\n",
- "\n",
- "### Issue 3: Memory Issues\n",
- "**Solution**:\n",
- "- Process documents in batches\n",
- "- Use smaller embedding models\n",
- "- Enable garbage collection\n",
- "- Consider using streaming for large datasets\n",
- "\n",
- "### Issue 4: Low Quality Extractions\n",
- "**Solution**:\n",
- "- Preprocess and normalize text\n",
- "- Use domain-specific models\n",
- "- Adjust extraction parameters\n",
- "- Validate and clean extracted entities\n",
- "\n",
- "### Issue 5: Slow Processing\n",
- "**Solution**:\n",
- "- Enable parallel processing\n",
- "- Use GPU acceleration if available\n",
- "- Cache intermediate results\n",
- "- Optimize batch sizes\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 1: Verify Installation\n",
- "\n",
- "Run the code below to verify that Semantica is properly installed and check the version.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Verify installation\n",
- "import semantica\n",
- "\n",
- "semantica.__version__\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Framework Architecture\n",
- "\n",
- "Semantica is organized into modular components:\n",
- "\n",
- "1. **INGEST** - Data ingestion from various sources\n",
- "2. **PARSE** - Document parsing and content extraction\n",
- "3. **NORMALIZE** - Text normalization and cleaning\n",
- "4. **SEMANTIC_EXTRACT** - Entity and relationship extraction\n",
- "5. **KG** - Knowledge graph construction and management\n",
- "6. **EMBEDDINGS** - Vector embedding generation\n",
- "7. **VECTOR_STORE** - Vector database operations\n",
- "8. **GRAPH_STORE** - Persistent graph database operations\n",
- "9. **REASONING** - Inference and reasoning\n",
- "10. **ONTOLOGY** - Ontology generation and management\n",
- "11. **EXPORT** - Data export in various formats\n",
- "12. **VISUALIZATION** - Graph and analytics visualization\n",
- "13. **PIPELINE** - Pipeline orchestration\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Import core modules\n",
- "from semantica.ingest import FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",
- "from semantica.parse import DocumentParser\n",
- "from semantica.semantic_extract import NERExtractor\n",
- "from semantica.kg import GraphBuilder\n",
- "from semantica.embeddings import EmbeddingGenerator\n",
- "from semantica.vector_store import VectorStore\n",
- "from semantica.graph_store import GraphStore\n",
- "from semantica.ontology import OntologyGenerator\n",
- "from semantica.export import JSONExporter\n",
- "from semantica.pipeline import PipelineBuilder\n",
"\n"
]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Key Concepts\n",
- "\n",
- "### Knowledge Graphs\n",
- "A structured representation of entities (nodes) and their relationships (edges) with properties and attributes.\n",
- "\n",
- "### Entity Extraction (NER)\n",
- "The process of identifying and classifying named entities in text (Person, Organization, Location, etc.).\n",
- "\n",
- "### Relationship Extraction\n",
- "Identifying relationships between entities (works_for, located_in, causes, etc.).\n",
- "\n",
- "### Embeddings\n",
- "Dense vector representations that capture semantic meaning for similarity search and retrieval.\n",
- "\n",
- "### GraphRAG\n",
- "Graph-based Retrieval Augmented Generation that combines vector search with knowledge graph traversal.\n",
- "\n",
- "### Temporal Graphs\n",
- "Knowledge graphs that track changes over time with timestamps and version history.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Example: Simple knowledge graph structure\n",
- "entities = [\n",
- " {\"id\": \"person_1\", \"name\": \"John Doe\", \"type\": \"Person\"},\n",
- " {\"id\": \"org_1\", \"name\": \"Acme Corp\", \"type\": \"Organization\"},\n",
- " {\"id\": \"loc_1\", \"name\": \"New York\", \"type\": \"Location\"}\n",
- "]\n",
- "\n",
- "relationships = [\n",
- " {\"source\": \"person_1\", \"target\": \"org_1\", \"type\": \"works_for\"},\n",
- " {\"source\": \"org_1\", \"target\": \"loc_1\", \"type\": \"located_in\"}\n",
- "]\n",
- "\n",
- "len(entities), len(relationships)\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Next Steps\n",
- "\n",
- "1. **Configuration Basics** - Set up configuration files and API keys\n",
- "2. **Data Ingestion** - Learn to ingest data from various sources\n",
- "3. **Entity Extraction** - Extract entities from text\n",
- "4. **Building Knowledge Graphs** - Create your first knowledge graph\n",
- "5. **Your First Knowledge Graph** - Complete end-to-end workflow\n",
- "\n",
- "## Best Practices\n",
- "\n",
- "- Start with small datasets\n",
- "- Configure properly using environment variables\n",
- "- Validate extracted data\n",
- "- Use quality assurance tools\n",
- "- Document your workflows\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": []
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 2: Configuration Setup\n",
- "\n",
- "Learn how to configure Semantica using `ConfigManager`. Configuration is essential for using API keys, model settings, and other framework parameters.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Configuration Examples\n",
- "import os\n",
- "from semantica.core import ConfigManager\n",
- "\n",
- "# Method 1: Using ConfigManager with environment variables\n",
- "# Set environment variables (uncomment to use):\n",
- "# os.environ['SEMANTICA_API_KEY'] = 'your_openai_key'\n",
- "# os.environ['SEMANTICA_EMBEDDING_PROVIDER'] = 'openai'\n",
- "# os.environ['SEMANTICA_MODEL_NAME'] = 'gpt-4'\n",
- "\n",
- "# Initialize ConfigManager\n",
- "config_manager = ConfigManager()\n",
- "\n",
- "# Access configuration\n",
- "\n",
- "# Method 2: Load from config file (if config.yaml exists)\n",
- "# config = config_manager.load_from_file(\"config.yaml\")\n",
- "# print(f\"Config loaded from file: {config is not None}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 3: Explore Core Modules\n",
- "\n",
- "Semantica consists of 12 core modules. The code below demonstrates how to import all of them. Each module handles a specific aspect of semantic processing.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Module Import Examples\n",
- "# This demonstrates how to import and use various Semantica modules\n",
- "\n",
- "# 1. INGEST MODULE - All 8 ingestion types\n",
- "from semantica.ingest import FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",
- "\n",
- "# 2. PARSE MODULE\n",
- "from semantica.parse import DocumentParser, PDFParser, DOCXParser\n",
- "\n",
- "# 3. NORMALIZE MODULE\n",
- "from semantica.normalize import TextNormalizer\n",
- "\n",
- "# 4. SEMANTIC_EXTRACT MODULE\n",
- "from semantica.semantic_extract import NERExtractor, RelationExtractor, NamedEntityRecognizer\n",
- "\n",
- "# 5. KG MODULE\n",
- "from semantica.kg import GraphBuilder, GraphAnalyzer, EntityResolver\n",
- "\n",
- "# 6. EMBEDDINGS MODULE\n",
- "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
- "\n",
- "# 7. VECTOR_STORE MODULE\n",
- "from semantica.vector_store import VectorStore, HybridSearch\n",
- "\n",
- "# 8. GRAPH_STORE MODULE\n",
- "from semantica.graph_store import GraphStore\n",
- "\n",
- "# 9. REASONING MODULE\n",
- "from semantica.reasoning import InferenceEngine, RuleManager\n",
- "\n",
- "# 10. ONTOLOGY MODULE\n",
- "from semantica.ontology import OntologyGenerator, OWLGenerator\n",
- "\n",
- "# 11. EXPORT MODULE\n",
- "from semantica.export import JSONExporter, RDFExporter, CSVExporter\n",
- "\n",
- "# 12. VISUALIZATION MODULE\n",
- "from semantica.visualization import KGVisualizer, EmbeddingVisualizer\n",
- "\n",
- "# 13. PIPELINE MODULE\n",
- "from semantica.pipeline import PipelineBuilder, ExecutionEngine\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 4: Understanding Knowledge Graphs\n",
- "\n",
- "This example demonstrates the basic structure of a knowledge graph with entities (nodes) and relationships (edges).\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Example: Creating a simple knowledge graph structure\n",
- "# This demonstrates the concept of knowledge graphs\n",
- "\n",
- "# Example entities and relationships\n",
- "entities = [\n",
- " {\"id\": \"person_1\", \"name\": \"John Doe\", \"type\": \"Person\"},\n",
- " {\"id\": \"org_1\", \"name\": \"Acme Corp\", \"type\": \"Organization\"},\n",
- " {\"id\": \"loc_1\", \"name\": \"New York\", \"type\": \"Location\"}\n",
- "]\n",
- "\n",
- "relationships = [\n",
- " {\"source\": \"person_1\", \"target\": \"org_1\", \"type\": \"works_for\", \"properties\": {\"start_date\": \"2020-01-01\", \"role\": \"Engineer\"}},\n",
- " {\"source\": \"org_1\", \"target\": \"loc_1\", \"type\": \"located_in\", \"properties\": {}}\n",
- "]\n",
- "\n",
- "# This demonstrates how entities (nodes) and relationships (edges) form a knowledge graph\n",
- "entities, relationships\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 5: Entity Extraction Example\n",
- "\n",
- "Named Entity Recognition (NER) identifies and classifies entities in text. This example shows what types of entities can be extracted.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Example: Entity Extraction (NER) demonstration\n",
- "from semantica.semantic_extract import NamedEntityRecognizer\n",
- "\n",
- "# Sample text\n",
- "sample_text = \"Apple Inc. was founded by Steve Jobs in Cupertino, California in 1976.\"\n",
- "\n",
- "# Initialize NER extractor\n",
- "ner = NamedEntityRecognizer()\n",
- "\n",
- "# Extract entities (this is a demonstration - actual extraction requires proper setup)\n",
- "# 1. Configure API keys for LLM providers\n",
- "# 2. Initialize the extractor with proper configuration\n",
- "sample_text\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 6: Understanding Embeddings\n",
- "\n",
- "Embeddings are dense vector representations that capture semantic meaning. This example demonstrates the concept of embeddings.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Example: Embeddings concept demonstration\n",
- "# Embeddings are dense vector representations of text\n",
- "\n",
- "import numpy as np\n",
- "\n",
- "# Simulate what an embedding looks like (this is just for demonstration)\n",
- "sample_text = \"machine learning\"\n",
- "# Real embeddings would be generated by EmbeddingGenerator\n",
- "# For demo purposes, we'll create a random vector\n",
- "embedding_dim = 1536 # Typical dimension for OpenAI embeddings\n",
- "demo_embedding = np.random.rand(embedding_dim).astype(np.float32)\n",
- "\n",
- "# Embeddings enable semantic search and similarity calculations\n",
- "# Similar texts have similar embeddings (close in vector space)\n",
- "# Fixed dimensions (typically 128-4096)\n",
- "demo_embedding.shape\n"
- ]
}
],
"metadata": {