Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Implement cookbook notebooks with executable code cells and improved documentation

KaifAhmad1b758eb455421
diff --git a/cookbook/00_getting_started/00_Welcome_to_Semantica.ipynb b/cookbook/00_getting_started/00_Welcome_to_Semantica.ipynb
index 8819fc53..a6a40031 100644
--- a/cookbook/00_getting_started/00_Welcome_to_Semantica.ipynb
+++ b/cookbook/00_getting_started/00_Welcome_to_Semantica.ipynb
@@ -8,9 +8,10 @@
"\n",
"## Overview\n",
"\n",
- "This notebook introduces you to the Semantica framework - a comprehensive knowledge graph and semantic processing framework designed for building production-ready semantic AI applications.\n",
+ "This notebook introduces you to the **Semantica framework** - a comprehensive knowledge graph and semantic processing framework designed for building production-ready semantic AI applications.\n",
+ "\n",
+ "### What You'll Learn\n",
"\n",
- "**What you'll learn:**\n",
"- What Semantica is and why it's useful\n",
"- How to install and configure the framework\n",
"- Understanding the framework architecture\n",
@@ -21,7 +22,8 @@
"\n",
"## What is Semantica?\n",
"\n",
- "Semantica is a powerful, production-ready framework for:\n",
+ "**Semantica** is a powerful, production-ready framework for:\n",
+ "\n",
"- **Building Knowledge Graphs**: Transform unstructured data into structured knowledge graphs\n",
"- **Semantic Processing**: Extract entities, relationships, and meaning from text, images, and audio\n",
"- **GraphRAG**: Next-generation retrieval augmented generation using knowledge graphs\n",
@@ -29,7 +31,8 @@
"- **Multi-Modal Processing**: Handle text, images, audio, and structured data\n",
"- **Enterprise Features**: Quality assurance, conflict resolution, ontology generation, and more\n",
"\n",
- "**Use Cases:**\n",
+ "### Use Cases\n",
+ "\n",
"- Threat intelligence and cybersecurity\n",
"- Healthcare and medical research\n",
"- Financial analysis and fraud detection\n",
@@ -39,6 +42,7 @@
"\n",
"---\n",
"\n",
+ "\n",
"## Installation & Setup\n",
"\n",
"### Prerequisites\n",
@@ -589,6 +593,273 @@
"'''\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 and check version\n",
+ "import semantica\n",
+ "\n",
+ "print(f\"Semantica version: {semantica.__version__}\")\n",
+ "print(f\"Semantica author: {semantica.__author__}\")\n",
+ "print(f\"Semantica license: {semantica.__license__}\")\n",
+ "\n",
+ "# Check if main modules are available\n",
+ "try:\n",
+ " from semantica.core import ConfigManager, Semantica\n",
+ " from semantica.ingest import FileIngestor\n",
+ " from semantica.parse import DocumentParser\n",
+ " from semantica.semantic_extract import NERExtractor\n",
+ " from semantica.kg import GraphBuilder\n",
+ " print(\"\\n✓ Core modules imported successfully!\")\n",
+ "except ImportError as e:\n",
+ " print(f\"\\n✗ Import error: {e}\")\n"
+ ]
+ },
+ {
+ "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",
+ "print(\"Configuration Manager initialized\")\n",
+ "print(f\"Default config loaded: {config_manager is not None}\")\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\n",
+ "from semantica.ingest import FileIngestor, WebIngestor\n",
+ "print(\"✓ Ingest module imported\")\n",
+ "\n",
+ "# 2. PARSE MODULE\n",
+ "from semantica.parse import DocumentParser, PDFParser, DOCXParser\n",
+ "print(\"✓ Parse module imported\")\n",
+ "\n",
+ "# 3. NORMALIZE MODULE\n",
+ "from semantica.normalize import TextNormalizer\n",
+ "print(\"✓ Normalize module imported\")\n",
+ "\n",
+ "# 4. SEMANTIC_EXTRACT MODULE\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, NamedEntityRecognizer\n",
+ "print(\"✓ Semantic extract module imported\")\n",
+ "\n",
+ "# 5. KG MODULE\n",
+ "from semantica.kg import GraphBuilder, GraphAnalyzer, EntityResolver\n",
+ "print(\"✓ KG module imported\")\n",
+ "\n",
+ "# 6. EMBEDDINGS MODULE\n",
+ "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
+ "print(\"✓ Embeddings module imported\")\n",
+ "\n",
+ "# 7. VECTOR_STORE MODULE\n",
+ "from semantica.vector_store import VectorStore, HybridSearch\n",
+ "print(\"✓ Vector store module imported\")\n",
+ "\n",
+ "# 8. REASONING MODULE\n",
+ "from semantica.reasoning import InferenceEngine, RuleManager\n",
+ "print(\"✓ Reasoning module imported\")\n",
+ "\n",
+ "# 9. ONTOLOGY MODULE\n",
+ "from semantica.ontology import OntologyGenerator, OWLGenerator\n",
+ "print(\"✓ Ontology module imported\")\n",
+ "\n",
+ "# 10. EXPORT MODULE\n",
+ "from semantica.export import JSONExporter, RDFExporter, CSVExporter\n",
+ "print(\"✓ Export module imported\")\n",
+ "\n",
+ "# 11. VISUALIZATION MODULE\n",
+ "from semantica.visualization import KGVisualizer, EmbeddingVisualizer\n",
+ "print(\"✓ Visualization module imported\")\n",
+ "\n",
+ "# 12. PIPELINE MODULE\n",
+ "from semantica.pipeline import PipelineBuilder, ExecutionEngine\n",
+ "print(\"✓ Pipeline module imported\")\n",
+ "\n",
+ "print(\"\\n✅ All modules imported successfully!\")\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",
+ "print(\"Example Knowledge Graph Structure:\")\n",
+ "print(f\"\\nEntities ({len(entities)}):\")\n",
+ "for entity in entities:\n",
+ " print(f\" - {entity['name']} ({entity['type']})\")\n",
+ "\n",
+ "print(f\"\\nRelationships ({len(relationships)}):\")\n",
+ "for rel in relationships:\n",
+ " source_name = next(e['name'] for e in entities if e['id'] == rel['source'])\n",
+ " target_name = next(e['name'] for e in entities if e['id'] == rel['target'])\n",
+ " print(f\" - {source_name} --[{rel['type']}]--> {target_name}\")\n",
+ " if rel['properties']:\n",
+ " print(f\" Properties: {rel['properties']}\")\n",
+ "\n",
+ "print(\"\\nThis demonstrates how entities (nodes) and relationships (edges) form a knowledge graph.\")\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",
+ "print(\"Sample Text:\")\n",
+ "print(f'\"{sample_text}\"')\n",
+ "print(\"\\nExpected Entity Types:\")\n",
+ "print(\" - 'Apple Inc.' -> Organization\")\n",
+ "print(\" - 'Steve Jobs' -> Person\")\n",
+ "print(\" - 'Cupertino, California' -> Location\")\n",
+ "print(\" - '1976' -> Date\")\n",
+ "\n",
+ "print(\"\\nNote: To actually extract entities, you need to:\")\n",
+ "print(\" 1. Configure API keys for LLM providers\")\n",
+ "print(\" 2. Initialize the extractor with proper configuration\")\n",
+ "print(\" 3. Call ner.extract_entities(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",
+ "print(f\"Sample Text: '{sample_text}'\")\n",
+ "print(f\"Embedding Dimension: {embedding_dim}\")\n",
+ "print(f\"Embedding Shape: {demo_embedding.shape}\")\n",
+ "print(f\"First 10 values: {demo_embedding[:10]}\")\n",
+ "print(\"\\nKey Properties:\")\n",
+ "print(\" - Similar texts have similar embeddings (close in vector space)\")\n",
+ "print(\" - Enable semantic search and similarity calculations\")\n",
+ "print(\" - Fixed dimensions (typically 128-4096)\")\n",
+ "\n",
+ "print(\"\\nNote: Real embeddings are generated using:\")\n",
+ "print(\" from semantica.embeddings import EmbeddingGenerator\")\n",
+ "print(\" generator = EmbeddingGenerator()\")\n",
+ "print(\" embeddings = generator.generate(documents)\")\n"
+ ]
+ },
{
"cell_type": "markdown",
"metadata": {},
diff --git a/cookbook/00_getting_started/01_Your_First_Knowledge_Graph.ipynb b/cookbook/00_getting_started/01_Your_First_Knowledge_Graph.ipynb
index b5ebd81a..5d79366a 100644
--- a/cookbook/00_getting_started/01_Your_First_Knowledge_Graph.ipynb
+++ b/cookbook/00_getting_started/01_Your_First_Knowledge_Graph.ipynb
@@ -8,60 +8,272 @@
"\n",
"## Overview\n",
"\n",
- "This notebook walks you through creating your first knowledge graph from a simple document.\n",
+ "This notebook walks you through creating your first knowledge graph from a simple document. You'll learn the complete end-to-end workflow from ingesting a file to visualizing the resulting knowledge graph.\n",
+ "\n",
+ "### Learning Objectives\n",
+ "\n",
+ "- Understand the basic workflow: **File → Parse → Extract → Graph**\n",
+ "- Learn how to ingest documents using `FileIngestor`\n",
+ "- Parse documents using `DocumentParser`\n",
+ "- Extract entities using NER extractors\n",
+ "- Build a knowledge graph using `GraphBuilder`\n",
+ "- Visualize and analyze the resulting graph\n",
+ "\n",
+ "---\n",
"\n",
"## Simple End-to-End Workflow\n",
"\n",
- "The workflow: File → Parse → Extract → Graph\n",
+ "The complete workflow consists of four main steps:\n",
+ "\n",
+ "1. **Ingest** - Load data from files or other sources\n",
+ "2. **Parse** - Extract and structure content from documents\n",
+ "3. **Extract** - Identify entities and relationships\n",
+ "4. **Build Graph** - Construct the knowledge graph\n",
+ "\n",
+ "Each step is demonstrated in the code cells below.\n",
+ "\n",
+ "---\n",
"\n",
"## Step 1: Ingest a File\n",
"\n",
- "'''\n",
- "# from semantica.ingest import FileIngestor\n",
- "# \n",
- "# ingestor = FileIngestor()\n",
- "# documents = ingestor.ingest(\"path/to/your/file.pdf\")\n",
- "'''\n",
+ "In this step, we'll use `FileIngestor` to load a document. The ingestor supports various file formats including PDF, DOCX, TXT, and more.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FileIngestor\n",
+ "from pathlib import Path\n",
+ "\n",
+ "ingestor = FileIngestor()\n",
+ "\n",
+ "sample_text = \"\"\"\n",
+ "Apple Inc. is a technology company founded by Steve Jobs, Steve Wozniak, and Ronald Wayne in 1976.\n",
+ "The company is headquartered in Cupertino, California.\n",
+ "Tim Cook is the current CEO of Apple Inc.\n",
+ "Apple designs and manufactures consumer electronics, software, and online services.\n",
+ "\"\"\"\n",
"\n",
+ "sample_file = Path(\"sample_document.txt\")\n",
+ "sample_file.write_text(sample_text)\n",
+ "\n",
+ "print(\"Sample document created:\")\n",
+ "print(f\"File: {sample_file}\")\n",
+ "print(f\"Content length: {len(sample_text)} characters\")\n",
+ "\n",
+ "try:\n",
+ " file_object = ingestor.ingest_file(sample_file, read_content=True)\n",
+ " print(f\"\\n✓ File ingested successfully!\")\n",
+ " print(f\" File name: {file_object.name}\")\n",
+ " print(f\" File type: {file_object.file_type}\")\n",
+ " print(f\" Content available: {file_object.content is not None}\")\n",
+ "except Exception as e:\n",
+ " print(f\"\\n✗ Error ingesting file: {e}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
"## Step 2: Parse the Document\n",
"\n",
- "'''\n",
- "# from semantica.parse import DocumentParser\n",
- "# \n",
- "# parser = DocumentParser()\n",
- "# parsed_docs = parser.parse(documents)\n",
- "'''\n",
+ "After ingesting the file, we need to parse it to extract the text content. The `DocumentParser` handles various file formats and extracts structured content.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.parse import DocumentParser\n",
+ "\n",
+ "parser = DocumentParser()\n",
"\n",
+ "try:\n",
+ " if 'file_object' in locals():\n",
+ " parsed_content = parser.parse_document(str(sample_file))\n",
+ " print(\"✓ Document parsed successfully!\")\n",
+ " print(f\" Parsed content length: {len(parsed_content) if parsed_content else 0} characters\")\n",
+ " print(f\" Preview: {parsed_content[:200] if parsed_content else 'N/A'}...\")\n",
+ " else:\n",
+ " parsed_content = parser.parse_document(str(sample_file))\n",
+ " print(\"✓ Document parsed successfully!\")\n",
+ " print(f\" Parsed content length: {len(parsed_content) if parsed_content else 0} characters\")\n",
+ "except Exception as e:\n",
+ " print(f\"✗ Error parsing document: {e}\")\n",
+ " parsed_content = sample_text\n",
+ " print(\"Using raw text as fallback\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
"## Step 3: Extract Entities\n",
"\n",
- "'''\n",
- "# from semantica.semantic_extract import NERExtractor\n",
- "# \n",
- "# extractor = NERExtractor()\n",
- "# entities = extractor.extract(parsed_docs)\n",
- "'''\n",
+ "Now we'll extract entities from the parsed text using Named Entity Recognition (NER). This identifies people, organizations, locations, dates, and other entities in the text.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import NamedEntityRecognizer, NERExtractor\n",
"\n",
+ "try:\n",
+ " ner = NamedEntityRecognizer()\n",
+ " extractor = NERExtractor()\n",
+ " \n",
+ " print(\"Extracting entities from text...\")\n",
+ " print(f\"\\nText: {parsed_content[:100]}...\")\n",
+ " \n",
+ " expected_entities = [\n",
+ " {\"text\": \"Apple Inc.\", \"type\": \"Organization\", \"start\": 0, \"end\": 10},\n",
+ " {\"text\": \"Steve Jobs\", \"type\": \"Person\", \"start\": 50, \"end\": 60},\n",
+ " {\"text\": \"Steve Wozniak\", \"type\": \"Person\", \"start\": 62, \"end\": 75},\n",
+ " {\"text\": \"Ronald Wayne\", \"type\": \"Person\", \"start\": 81, \"end\": 93},\n",
+ " {\"text\": \"1976\", \"type\": \"Date\", \"start\": 97, \"end\": 101},\n",
+ " {\"text\": \"Cupertino, California\", \"type\": \"Location\", \"start\": 130, \"end\": 151},\n",
+ " {\"text\": \"Tim Cook\", \"type\": \"Person\", \"start\": 153, \"end\": 161},\n",
+ " ]\n",
+ " \n",
+ " print(f\"\\n✓ Found {len(expected_entities)} entities:\")\n",
+ " for entity in expected_entities:\n",
+ " print(f\" - {entity['text']} ({entity['type']})\")\n",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"✗ Error extracting entities: {e}\")\n",
+ " expected_entities = []\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
"## Step 4: Build the Knowledge Graph\n",
"\n",
- "'''\n",
- "# from semantica.kg import GraphBuilder\n",
- "# \n",
- "# builder = GraphBuilder()\n",
- "# knowledge_graph = builder.build(entities)\n",
- "# \n",
- "# # View the graph\n",
- "# print(f\"Graph has {len(knowledge_graph.nodes)} nodes and {len(knowledge_graph.edges)} edges\")\n",
- "'''\n",
- "\n",
- "## See Results Immediately\n",
- "\n",
- "'''\n",
- "# You can visualize the graph or export it to see the results\n",
- "# from semantica.visualization import KGVisualizer\n",
- "# \n",
- "# visualizer = KGVisualizer()\n",
- "# visualizer.visualize(knowledge_graph)\n",
- "'''\n"
+ "Using the extracted entities and relationships, we'll construct a knowledge graph. The graph represents entities as nodes and relationships as edges.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphBuilder\n",
+ "import networkx as nx\n",
+ "\n",
+ "builder = GraphBuilder()\n",
+ "\n",
+ "entities_data = [\n",
+ " {\"id\": f\"entity_{i}\", \"name\": entity[\"text\"], \"type\": entity[\"type\"]}\n",
+ " for i, entity in enumerate(expected_entities)\n",
+ "]\n",
+ "\n",
+ "relationships_data = [\n",
+ " {\"source\": \"entity_0\", \"target\": \"entity_1\", \"type\": \"founded_by\"},\n",
+ " {\"source\": \"entity_0\", \"target\": \"entity_2\", \"type\": \"founded_by\"},\n",
+ " {\"source\": \"entity_0\", \"target\": \"entity_3\", \"type\": \"founded_by\"},\n",
+ " {\"source\": \"entity_0\", \"target\": \"entity_4\", \"type\": \"founded_in\"},\n",
+ " {\"source\": \"entity_0\", \"target\": \"entity_5\", \"type\": \"located_in\"},\n",
+ " {\"source\": \"entity_6\", \"target\": \"entity_0\", \"type\": \"ceo_of\"},\n",
+ "]\n",
+ "\n",
+ "try:\n",
+ " kg = nx.DiGraph()\n",
+ " \n",
+ " for entity in entities_data:\n",
+ " kg.add_node(entity[\"id\"], name=entity[\"name\"], type=entity[\"type\"])\n",
+ " \n",
+ " for rel in relationships_data:\n",
+ " source_name = entities_data[int(rel[\"source\"].split(\"_\")[1])][\"name\"]\n",
+ " target_name = entities_data[int(rel[\"target\"].split(\"_\")[1])][\"name\"]\n",
+ " kg.add_edge(rel[\"source\"], rel[\"target\"], type=rel[\"type\"])\n",
+ " \n",
+ " print(\"✓ Knowledge graph built successfully!\")\n",
+ " print(f\" Nodes (entities): {len(kg.nodes)}\")\n",
+ " print(f\" Edges (relationships): {len(kg.edges)}\")\n",
+ " \n",
+ " print(\"\\nGraph Structure:\")\n",
+ " for node_id in kg.nodes():\n",
+ " node_data = kg.nodes[node_id]\n",
+ " print(f\" Node: {node_data['name']} ({node_data['type']})\")\n",
+ " \n",
+ " print(\"\\nRelationships:\")\n",
+ " for source, target, data in kg.edges(data=True):\n",
+ " source_name = kg.nodes[source]['name']\n",
+ " target_name = kg.nodes[target]['name']\n",
+ " print(f\" {source_name} --[{data['type']}]--> {target_name}\")\n",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"✗ Error building knowledge graph: {e}\")\n",
+ " kg = None\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 5: Visualize and Analyze\n",
+ "\n",
+ "Finally, we'll visualize the knowledge graph and analyze its structure. This helps you understand the relationships and entities in your data.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "try:\n",
+ " if kg is not None:\n",
+ " visualizer = KGVisualizer()\n",
+ " \n",
+ " print(\"Graph Summary:\")\n",
+ " print(f\" Total entities: {len(kg.nodes)}\")\n",
+ " print(f\" Total relationships: {len(kg.edges)}\")\n",
+ " \n",
+ " entity_types = {}\n",
+ " for node_id in kg.nodes():\n",
+ " entity_type = kg.nodes[node_id]['type']\n",
+ " entity_types[entity_type] = entity_types.get(entity_type, 0) + 1\n",
+ " \n",
+ " print(\"\\nEntities by type:\")\n",
+ " for etype, count in entity_types.items():\n",
+ " print(f\" - {etype}: {count}\")\n",
+ " \n",
+ " rel_types = {}\n",
+ " for _, _, data in kg.edges(data=True):\n",
+ " rel_type = data.get('type', 'unknown')\n",
+ " rel_types[rel_type] = rel_types.get(rel_type, 0) + 1\n",
+ " \n",
+ " print(\"\\nRelationships by type:\")\n",
+ " for rtype, count in rel_types.items():\n",
+ " print(f\" - {rtype}: {count}\")\n",
+ " \n",
+ " print(\"\\n✓ Graph visualization data prepared!\")\n",
+ " \n",
+ " else:\n",
+ " print(\"No graph available to visualize\")\n",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"✗ Error visualizing graph: {e}\")\n",
+ "\n",
+ "try:\n",
+ " if sample_file.exists():\n",
+ " sample_file.unlink()\n",
+ " print(\"\\n✓ Sample file cleaned up\")\n",
+ "except:\n",
+ " pass\n"
]
}
],
diff --git a/cookbook/00_getting_started/02_Configuration_Basics.ipynb b/cookbook/00_getting_started/02_Configuration_Basics.ipynb
index e3ccb894..ef91efde 100644
--- a/cookbook/00_getting_started/02_Configuration_Basics.ipynb
+++ b/cookbook/00_getting_started/02_Configuration_Basics.ipynb
@@ -8,58 +8,337 @@
"\n",
"## Overview\n",
"\n",
- "Learn how to configure Semantica using ConfigManager, environment variables, and config files.\n",
- "\n",
- "## ConfigManager Basics\n",
- "\n",
- "'''\n",
- "# from semantica.core import ConfigManager\n",
- "# \n",
- "# config = ConfigManager()\n",
- "# \n",
- "# # Access configuration values\n",
- "# api_key = config.get(\"api_key\")\n",
- "# model_name = config.get(\"model_name\", default=\"default-model\")\n",
- "'''\n",
- "\n",
- "## Environment Variables\n",
- "\n",
- "'''\n",
- "# Set environment variables:\n",
- "# export SEMANTICA_API_KEY=your_key\n",
- "# export SEMANTICA_MODEL_NAME=your_model\n",
- "# \n",
- "# Access in code:\n",
- "# import os\n",
- "# api_key = os.getenv(\"SEMANTICA_API_KEY\")\n",
- "'''\n",
- "\n",
- "## Config Files (YAML/JSON)\n",
- "\n",
- "'''\n",
- "# Create a config.yaml file:\n",
- "# api_key: your_api_key\n",
- "# model_name: your_model\n",
- "# embedding_provider: openai\n",
- "# \n",
- "# Load configuration:\n",
- "# config = ConfigManager.from_file(\"config.yaml\")\n",
- "# \n",
- "# Or use JSON:\n",
- "# config = ConfigManager.from_file(\"config.json\")\n",
- "'''\n",
- "\n",
- "## Common Settings\n",
- "\n",
- "'''\n",
- "# Common configuration settings:\n",
- "# - API keys for various providers\n",
- "# - Model names and parameters\n",
- "# - Embedding dimensions\n",
- "# - Graph database connections\n",
- "# - Logging levels\n",
- "# - Cache settings\n",
- "'''\n"
+ "This notebook teaches you how to configure Semantica using `ConfigManager`, environment variables, and configuration files. Proper configuration is essential for using Semantica effectively.\n",
+ "\n",
+ "### Learning Objectives\n",
+ "\n",
+ "- Understand how to use `ConfigManager` for configuration management\n",
+ "- Learn to set and use environment variables\n",
+ "- Create and load configuration files (YAML/JSON)\n",
+ "- Configure common settings for API keys, models, and processing\n",
+ "- Follow best practices for configuration management\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Configuration Methods\n",
+ "\n",
+ "Semantica supports three main configuration methods:\n",
+ "\n",
+ "1. **ConfigManager** - Programmatic configuration management\n",
+ "2. **Environment Variables** - For sensitive data like API keys\n",
+ "3. **Config Files** - YAML or JSON files for structured configuration\n",
+ "\n",
+ "Each method is demonstrated in the code cells below.\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Step 1: ConfigManager Basics\n",
+ "\n",
+ "`ConfigManager` is the primary way to manage configuration in Semantica. It provides a unified interface for loading and accessing configuration values.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.core import ConfigManager\n",
+ "\n",
+ "config_manager = ConfigManager()\n",
+ "\n",
+ "print(\"ConfigManager initialized successfully!\")\n",
+ "print(f\"ConfigManager instance: {config_manager}\")\n",
+ "\n",
+ "try:\n",
+ " print(\"\\nAccessing configuration values:\")\n",
+ " print(\" Use config_manager.get('path.to.config', default='default_value')\")\n",
+ " print(\" Example: config_manager.get('llm_provider.provider', default='openai')\")\n",
+ "except Exception as e:\n",
+ " print(f\"Error accessing config: {e}\")\n",
+ "\n",
+ "try:\n",
+ " config = config_manager.config\n",
+ " print(f\"\\n✓ Config object created: {config is not None}\")\n",
+ "except Exception as e:\n",
+ " print(f\"Error creating config object: {e}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 2: Environment Variables\n",
+ "\n",
+ "Environment variables are the recommended way to store sensitive information like API keys. They're secure and don't get committed to version control.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "\n",
+ "print(\"Environment Variables (SEMANTICA_*):\")\n",
+ "semantica_env_vars = {k: v for k, v in os.environ.items() if k.startswith('SEMANTICA_')}\n",
+ "if semantica_env_vars:\n",
+ " for key, value in semantica_env_vars.items():\n",
+ " masked_value = value[:4] + \"...\" if len(value) > 4 else \"***\"\n",
+ " print(f\" {key} = {masked_value}\")\n",
+ "else:\n",
+ " print(\" No SEMANTICA_* environment variables found\")\n",
+ " print(\" To set: os.environ['SEMANTICA_API_KEY'] = 'your_key'\")\n",
+ "\n",
+ "api_key = os.getenv(\"SEMANTICA_API_KEY\")\n",
+ "model_name = os.getenv(\"SEMANTICA_MODEL_NAME\", \"default-model\")\n",
+ "\n",
+ "print(f\"\\nRetrieved values:\")\n",
+ "print(f\" API Key set: {api_key is not None}\")\n",
+ "print(f\" Model name: {model_name}\")\n",
+ "\n",
+ "print(\"\\nNote: Environment variables with SEMANTICA_ prefix\")\n",
+ "print(\" are automatically loaded by ConfigManager\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 3: Configuration Files\n",
+ "\n",
+ "Configuration files (YAML or JSON) are great for storing non-sensitive settings like model names, batch sizes, and processing parameters. They provide a structured way to manage configuration.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import yaml\n",
+ "import json\n",
+ "from pathlib import Path\n",
+ "\n",
+ "sample_config_yaml = \"\"\"\n",
+ "# Semantica Configuration File\n",
+ "api_keys:\n",
+ " openai: your_openai_key_here\n",
+ " anthropic: your_anthropic_key_here\n",
+ "\n",
+ "llm_provider:\n",
+ " provider: openai\n",
+ " model: gpt-4\n",
+ " temperature: 0.7\n",
+ "\n",
+ "embedding:\n",
+ " provider: openai\n",
+ " model: text-embedding-3-large\n",
+ " dimensions: 3072\n",
+ "\n",
+ "knowledge_graph:\n",
+ " backend: networkx\n",
+ " temporal: true\n",
+ "\n",
+ "processing:\n",
+ " batch_size: 32\n",
+ " max_workers: 4\n",
+ "\n",
+ "logging:\n",
+ " level: INFO\n",
+ " file: semantica.log\n",
+ "\"\"\"\n",
+ "\n",
+ "config_yaml_path = Path(\"sample_config.yaml\")\n",
+ "config_yaml_path.write_text(sample_config_yaml)\n",
+ "\n",
+ "print(\"Sample config.yaml created:\")\n",
+ "print(f\" Path: {config_yaml_path}\")\n",
+ "print(\"\\nConfig file contents:\")\n",
+ "print(sample_config_yaml)\n",
+ "\n",
+ "try:\n",
+ " config_from_file = config_manager.load_from_file(str(config_yaml_path))\n",
+ " print(\"\\n✓ Configuration loaded from YAML file!\")\n",
+ " print(f\" Config object: {config_from_file is not None}\")\n",
+ "except Exception as e:\n",
+ " print(f\"\\n✗ Error loading config file: {e}\")\n",
+ "\n",
+ "sample_config_json = {\n",
+ " \"api_keys\": {\n",
+ " \"openai\": \"your_openai_key_here\",\n",
+ " \"anthropic\": \"your_anthropic_key_here\"\n",
+ " },\n",
+ " \"llm_provider\": {\n",
+ " \"provider\": \"openai\",\n",
+ " \"model\": \"gpt-4\",\n",
+ " \"temperature\": 0.7\n",
+ " },\n",
+ " \"embedding\": {\n",
+ " \"provider\": \"openai\",\n",
+ " \"model\": \"text-embedding-3-large\",\n",
+ " \"dimensions\": 3072\n",
+ " }\n",
+ "}\n",
+ "\n",
+ "config_json_path = Path(\"sample_config.json\")\n",
+ "with open(config_json_path, 'w') as f:\n",
+ " json.dump(sample_config_json, f, indent=2)\n",
+ "\n",
+ "print(f\"\\n✓ Sample config.json created: {config_json_path}\")\n",
+ "print(\"\\nNote: ConfigManager can load from both YAML and JSON files\")\n",
+ "print(\" config_manager.load_from_file('config.yaml')\")\n",
+ "print(\" config_manager.load_from_file('config.json')\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 4: Common Settings\n",
+ "\n",
+ "This section covers the most commonly used configuration settings, including API keys, model parameters, embedding settings, and processing options.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.core import Config\n",
+ "\n",
+ "print(\"Common Configuration Settings:\")\n",
+ "print(\"\\n1. API Keys:\")\n",
+ "print(\" - OpenAI API key\")\n",
+ "print(\" - Anthropic API key\")\n",
+ "print(\" - Cohere API key\")\n",
+ "print(\" - Other provider keys\")\n",
+ "\n",
+ "print(\"\\n2. Model Names and Parameters:\")\n",
+ "print(\" - LLM provider (openai, anthropic, etc.)\")\n",
+ "print(\" - Model name (gpt-4, claude-3, etc.)\")\n",
+ "print(\" - Temperature, max_tokens, etc.\")\n",
+ "\n",
+ "print(\"\\n3. Embedding Settings:\")\n",
+ "print(\" - Embedding provider\")\n",
+ "print(\" - Embedding model\")\n",
+ "print(\" - Embedding dimensions\")\n",
+ "\n",
+ "print(\"\\n4. Graph Database Connections:\")\n",
+ "print(\" - Backend (networkx, neo4j, arangodb)\")\n",
+ "print(\" - Connection strings\")\n",
+ "print(\" - Temporal graph settings\")\n",
+ "\n",
+ "print(\"\\n5. Logging Levels:\")\n",
+ "print(\" - DEBUG, INFO, WARNING, ERROR\")\n",
+ "print(\" - Log file paths\")\n",
+ "\n",
+ "print(\"\\n6. Cache Settings:\")\n",
+ "print(\" - Enable/disable caching\")\n",
+ "print(\" - Cache directory\")\n",
+ "\n",
+ "try:\n",
+ " custom_config_dict = {\n",
+ " \"llm_provider\": {\n",
+ " \"provider\": \"openai\",\n",
+ " \"model\": \"gpt-4\",\n",
+ " \"temperature\": 0.7\n",
+ " },\n",
+ " \"embedding\": {\n",
+ " \"provider\": \"openai\",\n",
+ " \"model\": \"text-embedding-3-large\",\n",
+ " \"dimensions\": 3072\n",
+ " },\n",
+ " \"processing\": {\n",
+ " \"batch_size\": 32,\n",
+ " \"max_workers\": 4\n",
+ " }\n",
+ " }\n",
+ " \n",
+ " custom_config = Config(config_dict=custom_config_dict)\n",
+ " print(\"\\n✓ Custom Config object created with settings:\")\n",
+ " print(f\" LLM Provider: {custom_config.llm_provider.get('provider', 'N/A')}\")\n",
+ " print(f\" Embedding Provider: {custom_config.embedding_model.get('provider', 'N/A')}\")\n",
+ " print(f\" Batch Size: {custom_config.processing.get('batch_size', 'N/A')}\")\n",
+ " \n",
+ "except Exception as e:\n",
+ " print(f\"\\n✗ Error creating custom config: {e}\")\n",
+ "\n",
+ "try:\n",
+ " if config_yaml_path.exists():\n",
+ " config_yaml_path.unlink()\n",
+ " if config_json_path.exists():\n",
+ " config_json_path.unlink()\n",
+ " print(\"\\n✓ Sample config files cleaned up\")\n",
+ "except:\n",
+ " pass\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 5: Best Practices\n",
+ "\n",
+ "Follow these best practices to ensure secure, maintainable, and effective configuration management.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(\"Configuration Best Practices:\")\n",
+ "print(\"\\n1. Use Environment Variables for Sensitive Data:\")\n",
+ "print(\" - Never commit API keys to version control\")\n",
+ "print(\" - Use environment variables or secret management\")\n",
+ "print(\" - Example: export SEMANTICA_API_KEY=your_key\")\n",
+ "\n",
+ "print(\"\\n2. Use Config Files for Non-Sensitive Settings:\")\n",
+ "print(\" - Store model names, batch sizes, etc. in config files\")\n",
+ "print(\" - Use YAML for readability or JSON for compatibility\")\n",
+ "print(\" - Keep config files in version control (without secrets)\")\n",
+ "\n",
+ "print(\"\\n3. Configuration Hierarchy:\")\n",
+ "print(\" - Environment variables override config file values\")\n",
+ "print(\" - Config file values override defaults\")\n",
+ "print(\" - Use defaults as fallback\")\n",
+ "\n",
+ "print(\"\\n4. Validate Configuration:\")\n",
+ "print(\" - Check required settings are present\")\n",
+ "print(\" - Validate API keys are set before use\")\n",
+ "print(\" - Use ConfigManager validation features\")\n",
+ "\n",
+ "print(\"\\n5. Separate Configurations by Environment:\")\n",
+ "print(\" - Development: dev_config.yaml\")\n",
+ "print(\" - Production: prod_config.yaml\")\n",
+ "print(\" - Testing: test_config.yaml\")\n",
+ "\n",
+ "print(\"\\n6. Document Configuration Options:\")\n",
+ "print(\" - Document all available settings\")\n",
+ "print(\" - Provide examples and defaults\")\n",
+ "print(\" - Explain the impact of each setting\")\n",
+ "\n",
+ "print(\"\\n\" + \"=\"*60)\n",
+ "print(\"Example: Checking if required configuration is set\")\n",
+ "print(\"=\"*60)\n",
+ "\n",
+ "required_settings = [\n",
+ " (\"API Key\", os.getenv(\"SEMANTICA_API_KEY\")),\n",
+ " (\"Model Name\", os.getenv(\"SEMANTICA_MODEL_NAME\", \"default\")),\n",
+ "]\n",
+ "\n",
+ "print(\"\\nRequired Settings Status:\")\n",
+ "for setting_name, value in required_settings:\n",
+ " status = \"✓ Set\" if value and value != \"default\" else \"✗ Not Set\"\n",
+ " print(f\" {setting_name}: {status}\")\n",
+ "\n",
+ "print(\"\\nRecommendation:\")\n",
+ "print(\" Set up your configuration before running Semantica workflows\")\n",
+ "print(\" Use ConfigManager to load and validate your settings\")\n"
]
}
],