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
Merge origin/main into docs and resolve conflicts
KaifAhmad127e1d94290df
diff --cc README.mdindex 9b9ac360,216e424d..0d40a410--- a/README.md+++ b/README.md@@@ -510,593 -210,56 +210,80 @@@ Semantica is designed for **developers---- ### 3. πΈοΈ Knowledge Graph Construction-- Build production-ready knowledge graphs from any data source with automatic entity resolution, relationship inference, and graph optimization.-- **Example: Building Knowledge Graph**-- ```python- from semantica import Semantica- from semantica.kg import (- GraphBuilder,- EntityResolver,- GraphAnalyzer,- CentralityCalculator,- CommunityDetector- )- from semantica.export import RDFExporter, JSONExporter-- # Sample documents- documents = [- """Apple Inc. was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne in 1976.- The company is headquartered in Cupertino, California.""",-- """In 2014, Apple acquired Beats Electronics for $3 billion. Dr. Dre and- Jimmy Iovine joined Apple's executive team.""",-- """Tim Cook became CEO in 2011 after Jobs stepped down. Under Cook's leadership,- Apple expanded into services generating over $80 billion annually."""- ]-- # Option 1: High-level API (recommended for quick start)- core = Semantica(- graph_db="neo4j", # or "networkx", "rdflib", "memgraph"- merge_entities=True,- resolve_conflicts=True- )- kg = core.build_knowledge_graph(- sources=documents,- merge_entities=True,- resolve_conflicts=True,- generate_embeddings=True- )-- # Option 2: Low-level API (for fine-grained control)- graph_builder = GraphBuilder(- merge_entities=True,- entity_resolution_strategy="fuzzy",- resolve_conflicts=True,- enable_temporal=True, # Enable temporal knowledge graph features- temporal_granularity="day",- track_history=True,- version_snapshots=True- )-- entity_resolver = EntityResolver(- similarity_threshold=0.85,- merge_strategy="highest_confidence"- )-- # Build graph step by step- kg = graph_builder.build(- sources=documents,- entity_resolver=entity_resolver- )-- # Resolve entities- kg = entity_resolver.resolve(kg)-- # Graph Statistics- print("=== GRAPH STATISTICS ===")- print(f"Nodes: {kg.node_count}")- print(f"Edges: {kg.edge_count}")- print(f"Entity Types: {sorted(kg.entity_types)}")- print(f"Relationship Types: {sorted(kg.relationship_types)}")- print(f"Graph Density: {kg.density:.3f}")- print(f"Connected Components: {kg.connected_components}\n")-- # Output:- # Nodes: 25- # Edges: 38- # Entity Types: ['Date', 'Location', 'Money', 'Organization', 'Person', 'Product']- # Relationship Types: ['acquired', 'became', 'expanded_into', 'founded', 'headquartered_in', 'joined', 'works_for']- # Graph Density: 0.127- # Connected Components: 1-- # Query the graph- result = kg.query(- "Who founded Apple Inc.?",- return_format="structured"- )- print(f"Q: Who founded Apple Inc.?")- print(f"A: {result.answer}")- print(f"Confidence: {result.confidence:.2f}")- print(f"Supporting Entities: {[e.name for e in result.supporting_entities]}")- print(f"Evidence Paths: {result.evidence_paths}\n")-- # Output:- # Q: Who founded Apple Inc.?- # A: Apple Inc. was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne in 1976.- # Confidence: 0.98- # Supporting Entities: ['Steve Jobs', 'Steve Wozniak', 'Ronald Wayne', 'Apple Inc.']- # Evidence Paths: [['Apple Inc.', 'founded_by', 'Steve Jobs'], ...]-- # Export to multiple formats- rdf_exporter = RDFExporter()- rdf_exporter.export(kg, "output.ttl", format="turtle")-- json_exporter = JSONExporter()- json_exporter.export(kg, "output.jsonld", format="json-ld")-- # Export to graph databases- kg.to_neo4j("bolt://localhost:7687", "neo4j", "password")- kg.to_memgraph("localhost", 7687, username="admin", password="password")-- print("β Graph exported to multiple formats!")- ```-- **Temporal Knowledge Graph Example**-- ```python- from semantica import Semantica- from semantica.kg import (- GraphBuilder,- TemporalGraphQuery,- TemporalPatternDetector,- TemporalVersionManager,- GraphAnalyzer- )- from datetime import datetime, timedelta-- # Initialize with temporal support- core = Semantica(- graph_db="neo4j",- enable_temporal=True,- temporal_granularity="day"- )-- # Build temporal knowledge graph- graph_builder = GraphBuilder(- enable_temporal=True,- temporal_granularity="day",- track_history=True,- version_snapshots=True- )-- kg = graph_builder.build(- sources=documents,- entity_resolver=entity_resolver- )-- # Add temporal edges with validity periods- graph_builder.add_temporal_edge(- graph=kg,- source="Apple Inc.",- target="Steve Jobs",- relationship="founded_by",- valid_from="1976-04-01",- valid_until=None, # Ongoing relationship- temporal_metadata={"timezone": "UTC", "precision": "day"}- )-- graph_builder.add_temporal_edge(- graph=kg,- source="Apple Inc.",- target="Beats Electronics",- relationship="acquired",- valid_from="2014-05-28",- valid_until="2014-08-01", # Acquisition completed- temporal_metadata={"amount": "$3B", "status": "completed"}- )-- # Create temporal snapshot- version_manager = TemporalVersionManager(- snapshot_interval=timedelta(days=30),- auto_snapshot=True- )-- snapshot = version_manager.create_version(- graph=kg,- timestamp="2024-01-15",- version_label="Q1_2024",- metadata={"description": "Q1 2024 knowledge graph snapshot"}- )-- # Query temporal graph- temporal_query = TemporalGraphQuery(- enable_temporal_reasoning=True,- temporal_granularity="day"- )-- # Query at specific time point- results_at_2014 = temporal_query.query_at_time(- graph=kg,- query="Who founded Apple Inc.?",- at_time="2014-06-15",- include_history=True- )-- # Query within time range- results_range = temporal_query.query_time_range(- graph=kg,- query="What acquisitions did Apple make?",- start_time="2010-01-01",- end_time="2020-12-31",- temporal_aggregation="union"- )-- # Analyze temporal evolution- analyzer = GraphAnalyzer(enable_temporal=True)- evolution = analyzer.analyze_temporal_evolution(- graph=kg,- start_time="2000-01-01",- end_time="2024-12-31",- metrics=["node_count", "edge_count", "density", "communities"],- interval=timedelta(days=365) # Yearly snapshots- )-- print("=== TEMPORAL EVOLUTION ===")- for snapshot in evolution.snapshots:- print(f"{snapshot.timestamp}: {snapshot.metrics}")-- # Detect temporal patterns- pattern_detector = TemporalPatternDetector()- patterns = pattern_detector.detect_temporal_patterns(- graph=kg,- pattern_type="sequence",- min_frequency=2,- time_window=timedelta(days=365)- )+ ## π¦ Installation- print(f"\nβ Detected {len(patterns)} temporal patterns")+ **Prerequisites:** Python 3.8+ (3.9+ recommended) β’ pip (latest version)- # Find temporal paths- temporal_paths = temporal_query.find_temporal_paths(- graph=kg,- source="Apple Inc.",- target="Beats Electronics",- start_time="2010-01-01",- end_time="2015-12-31",- max_path_length=3- )+ ### Install from PyPI (Recommended)- print(f"\nβ Found {len(temporal_paths)} temporal paths")- ```+ ```bash+ # Install latest version from PyPI+ pip install semantica- **Advanced Graph Analytics**+ # Or install with optional dependencies+ pip install semantica[all]- ```python- from semantica.kg import (- GraphAnalyzer,- CentralityCalculator,- CommunityDetector,- ConnectivityAnalyzer- )-- analyzer = GraphAnalyzer(kg)-- # Centrality analysis- centrality_calc = CentralityCalculator(kg)- pagerank_scores = centrality_calc.pagerank()- betweenness_scores = centrality_calc.betweenness_centrality()- closeness_scores = centrality_calc.closeness_centrality()- eigenvector_scores = centrality_calc.eigenvector_centrality()-- print("\nMost Influential Entities (PageRank):")- for entity, score in sorted(pagerank_scores.items(), key=lambda x: x[1], reverse=True)[:5]:- print(f" {entity}: {score:.3f}")-- # Community detection- community_detector = CommunityDetector(kg)- communities = community_detector.detect(algorithm="louvain") # or "leiden", "greedy_modularity"- print(f"\nCommunities detected: {len(communities)}")- for i, community in enumerate(communities[:3], 1):- print(f" Community {i}: {len(community)} entities - {community[:3]}...")-- # Connectivity analysis- connectivity = ConnectivityAnalyzer(kg)- shortest_paths = connectivity.find_shortest_paths("Apple Inc.", "Dr. Dre", max_length=3)- all_paths = connectivity.find_all_paths("Apple Inc.", "Dr. Dre", max_length=4)-- print(f"\nShortest paths found: {len(shortest_paths)}")- for path in shortest_paths[:3]:- print(f" {' β '.join(str(node) for node in path)}")-- # Graph metrics- metrics = analyzer.compute_metrics()- print(f"\nGraph Metrics:")- print(f" Average degree: {metrics['avg_degree']:.2f}")- print(f" Clustering coefficient: {metrics['clustering']:.3f}")- print(f" Diameter: {metrics['diameter']}")- print(f" Average path length: {metrics['avg_path_length']:.2f}")+ # Verify installation+ python -c "import semantica; print(semantica.__version__)"```- ----- ### 4. π Ontology Generation & Management-- Generate formal ontologies automatically using a 6-stage LLM-based pipeline that transforms unstructured content into W3C-compliant OWL ontologies.+ **Current Version:** [](https://pypi.org/project/semantica/0.0.1/) β’ [View on PyPI](https://pypi.org/project/semantica/0.0.1/)- **The 6-Stage Pipeline:**-- ```- Stage 1: Semantic Network Parsing β Extract domain concepts- Stage 2: YAML-to-Definition β Transform into class definitions- Stage 3: Definition-to-Types β Map to OWL types- Stage 4: Hierarchy Generation β Build taxonomic structures- Stage 5: TTL Generation β Generate OWL/Turtle syntax- Stage 6: Symbolic Validation β HermiT/Pellet reasoning (F1 up to 0.99)- ```++## π³ Semantica Cookbook+- **Example: Automatic Ontology Generation**++> **Interactive Jupyter Notebooks** designed to take you from beginner to expert.+- ```python- from semantica.ontology import (- OntologyGenerator,- OntologyValidator,- ClassInferrer,- PropertyGenerator,- OWLGenerator,- OntologyEvaluator,- RequirementsSpec- )++[**View Full Cookbook**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook)+- # Sample domain documents- documents = [- """Apple Inc. is a technology company that designs and manufactures consumer- electronics, software, and online services. Products include iPhone, iPad, Mac.""",-- """Companies can acquire other companies. Apple acquired Beats Electronics for- $3 billion. Acquisitions involve financial transactions and integration."""- ]-- # Step 1: Define requirements and competency questions- requirements = RequirementsSpec()- requirements.add_competency_question(- "What companies exist in the domain?",- category="entity_identification"- )- requirements.add_competency_question(- "What are the relationships between companies?",- category="relationship_modeling"- )++### Featured Recipes+- # Step 2: Initialize generator with full configuration- generator = OntologyGenerator(- llm_provider="openai",- model="gpt-4",- validation_mode="hybrid", # LLM + symbolic reasoner- enable_class_inference=True,- enable_property_generation=True,- quality_threshold=0.95- )++| **Recipe** | **Description** | **Link** |++|:-----------|:----------------|:---------|++| **GraphRAG Complete** | Build a production-ready **Graph Retrieval Augmented Generation** system. Features **Graph Validation**, **Hybrid Retrieval**, and **Logical Inference**. | [Open Notebook](cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb) |++| **RAG vs. GraphRAG** | Side-by-side comparison. Demonstrates the **Reasoning Gap** and how GraphRAG solves it with **Inference Engines**. | [Open Notebook](cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb) |++| **First Knowledge Graph** | Go from raw text to a queryable knowledge graph in 20 minutes. | [Open Notebook](cookbook/introduction/08_Your_First_Knowledge_Graph.ipynb) |++| **Real-Time Anomalies** | Detect anomalies in streaming data using dynamic graphs. | [Open Notebook](cookbook/use_cases/cybersecurity/01_Anomaly_Detection_Real_Time.ipynb) |+- # Step 3: Generate ontology using 6-stage pipeline- ontology = generator.generate_from_documents(- sources=documents,- requirements=requirements,- quality_threshold=0.95,- namespace="https://example.org/ontology#",- prefix="ex"- )++### Core Tutorials+- print("=== ONTOLOGY GENERATION RESULTS ===")- print(f"Classes: {len(ontology.classes)}")- print(f"Properties: {len(ontology.properties)}")- print(f"Axioms: {len(ontology.axioms)}")- print(f"Validation Score: {ontology.validation_score:.2f}")- print(f"Namespace: {ontology.namespace}\n")-- # Step 4: Display generated classes with hierarchy- print("=== GENERATED CLASSES ===")- for cls in ontology.classes[:5]:- print(f"\nClass: {cls.name} ({cls.iri})")- print(f" Superclasses: {', '.join(cls.superclasses) if cls.superclasses else 'owl:Thing'}")- print(f" Subclasses: {len(cls.subclasses)}")- print(f" Properties: {len(cls.properties)}")- for prop in cls.properties[:3]:- print(f" - {prop.name} ({prop.type})")- if cls.annotations:- print(f" Annotations: {cls.annotations}")-- # Step 5: Display properties with domain and range- print("\n=== GENERATED PROPERTIES ===")- object_props = [p for p in ontology.properties if p.type == 'ObjectProperty']- datatype_props = [p for p in ontology.properties if p.type == 'DatatypeProperty']-- print(f"Object Properties: {len(object_props)}")- for prop in object_props[:3]:- print(f" {prop.name}: {prop.domain} β {prop.range}")- if prop.characteristics:- print(f" Characteristics: {prop.characteristics}")-- print(f"\nDatatype Properties: {len(datatype_props)}")- for prop in datatype_props[:3]:- print(f" {prop.name}: {prop.domain} β {prop.range}")-- # Step 6: Validate with symbolic reasoner- validator = OntologyValidator(reasoner="hermit") # or "pellet", "fact++"- validation_report = validator.validate(ontology)-- print("\n=== VALIDATION REPORT ===")- if validation_report.is_consistent:- print("β Ontology is logically consistent")- print(f"β All {len(validation_report.checks)} checks passed")- print(f"β Satisfiability: {validation_report.is_satisfiable}")- print(f"β Classification: {validation_report.classification_complete}")-- # Generate OWL/Turtle file- owl_generator = OWLGenerator()- owl_generator.generate(ontology, "domain_ontology.ttl", format="turtle")- print("\nβ Saved to domain_ontology.ttl")- else:- print("β Inconsistencies found:")- for issue in validation_report.issues:- print(f" - {issue.severity}: {issue.message}")- print(f" Location: {issue.location}")-- # Step 7: Evaluate ontology quality- evaluator = OntologyEvaluator()- evaluation = evaluator.evaluate(ontology)- print("\n=== ONTOLOGY QUALITY EVALUATION ===")- print(f"Completeness: {evaluation.completeness:.2f}")- print(f"Consistency: {evaluation.consistency:.2f}")- print(f"Clarity: {evaluation.clarity:.2f}")- print(f"Coherence: {evaluation.coherence:.2f}")- print(f"Overall Score: {evaluation.overall_score:.2f}")- ```++- [**Welcome to Semantica**](cookbook/introduction/01_Welcome_to_Semantica.ipynb) - Framework Overview++- [**Data Ingestion**](cookbook/introduction/02_Data_Ingestion.ipynb) - Universal Ingestion++- [**Entity Extraction**](cookbook/introduction/05_Entity_Extraction.ipynb) - NER & Relationships++- [**Building Knowledge Graphs**](cookbook/introduction/07_Building_Knowledge_Graphs.ipynb) - Graph Construction+- ---++> **Note:** Once published to PyPI, you'll be able to install with `pip install semantica`+- ### 5. π Context Engineering for AI Agents+ ### Install from Source (Development)- Formalize context as graphs to enable AI agents with memory, tools, and purpose:+ ```bash+ # Clone and install in editable mode+ git clone https://github.com/Hawksight-AI/semantica.git+ cd semantica+ pip install -e .- **The Three Layers of Context:**+ # Or with all optional dependencies+ pip install -e ".[all]"+ # Development setup+ pip install -e ".[dev]"```- βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- β Layer 1: Prompting (Natural Language Programming) β- β ββ Define agent goals and behaviors β- β ββ Template-based prompt construction β- β ββ Dynamic context injection β- βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- β- βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- β Layer 2: Memory (RAG + Knowledge Graphs) β- β ββ Vector databases for semantic similarity β- β ββ Knowledge graphs for relationship traversal β- β ββ Persistent context across conversations β- βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- β- βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- β Layer 3: Tools (Standardized Interfaces) β- β ββ MCP-compatible tool registry β- β ββ Semantic tool discovery β- β ββ Consistent tool access patterns β- βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- ```-- **Example: Building Context-Aware Agent**-- ```python- from semantica.context import (- ContextGraphBuilder,- AgentMemory,- ContextRetriever,- EntityLinker- )- from semantica.prompting import PromptBuilder- from semantica.agents import ToolRegistry- from semantica.vector_store import VectorStore, PineconeAdapter- from semantica.kg import GraphBuilder-- # Build context graph from conversations- context_builder = ContextGraphBuilder(- extract_entities=True,- extract_relationships=True,- link_external_entities=True- )- context_graph = context_builder.build_from_conversations(- conversations=["conv_1.json", "conv_2.json"],- link_entities=True,- extract_intents=True,- extract_sentiments=True- )-- # Initialize vector store for memory- vector_store = VectorStore(adapter=PineconeAdapter(- api_key="your-api-key",- index_name="agent-memory",- environment="us-east-1"- ))-- # Initialize agent memory with full configuration- memory = AgentMemory(- vector_store=vector_store,- knowledge_graph=context_graph,- retention_policy="30_days",- max_memory_size=10000- )-- # Store context with metadata- memory.store(- content="User prefers technical documentation over tutorials",- metadata={- "user_id": "user_123",- "session": "session_456",- "timestamp": "2024-01-15T10:30:00Z",- "category": "preferences"- },- entities=["User", "Documentation", "Tutorials"],- relationships=[("prefers", "User", "Documentation")]- )-- # Store additional context- memory.store(- content="User is interested in machine learning and NLP topics",- metadata={"user_id": "user_123", "category": "interests"},- entities=["User", "Machine Learning", "NLP"]- )-- # Initialize context retriever- context_retriever = ContextRetriever(- memory_store=memory,- use_graph_expansion=True,- max_expansion_hops=2- )-- # Retrieve relevant context- relevant_context = context_retriever.retrieve(- query="What are the user's learning preferences?",- max_results=5,- use_graph_expansion=True,- min_relevance_score=0.7- )-- print("=== RETRIEVED CONTEXT ===")- for ctx in relevant_context:- print(f"- {ctx.content} (score: {ctx.score:.2f})")- if ctx.related_entities:- print(f" Related: {[e.name for e in ctx.related_entities[:3]]}")-- # Entity linking for context- entity_linker = EntityLinker(- knowledge_graph=context_graph,- similarity_threshold=0.8- )- linked_entities = entity_linker.link(- text="Create a learning plan for technical documentation",- context=relevant_context- )-- # Build context-aware prompt- prompt_builder = PromptBuilder(- template_engine="jinja2",- include_context=True,- include_entities=True- )+ ## π Resources- prompt = prompt_builder.build(- template="agent_task",- context=relevant_context,- entities=linked_entities,- user_query="Create a learning plan",- system_instructions="You are a helpful learning assistant."- )+ > **New to Semantica?** Check out the [**Cookbook**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook) for hands-on examples!- print("\n=== GENERATED PROMPT ===")- print(prompt)+ - [**Cookbook**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook) - 50+ interactive notebooks+ - [Introduction](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/introduction) - Getting started tutorials+ - [Advanced](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/advanced) - Advanced techniques+ - [Use Cases](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/use_cases) - Real-world applications- # Tool registry for agent capabilities- tool_registry = ToolRegistry()- tool_registry.register_tool(- name="create_learning_plan",- description="Creates a personalized learning plan",- parameters={"topics": "list", "preferences": "dict"}- )+ ## β¨ Core Capabilities- # Get available tools based on context- available_tools = tool_registry.get_relevant_tools(- query="Create a learning plan",- context=relevant_context- )- print(f"\n=== AVAILABLE TOOLS ===")- for tool in available_tools:- print(f"- {tool.name}: {tool.description}")- ```+ | **Data Ingestion** | **Semantic Extract** | **Knowledge Graphs** | **Ontology** |+ |:--------------------:|:----------------------:|:----------------------:|:--------------:|+ | [50+ Formats](#universal-data-ingestion) | [Entity & Relations](#semantic-intelligence-engine) | [Graph Analytics](#knowledge-graph-construction) | [Auto Generation](#ontology-generation--management) |+ | **Context** | **GraphRAG** | **Pipeline** | **QA** |+ | [Agent Memory](#context-engineering-for-ai-agents) | [Hybrid RAG](#knowledge-graph-powered-rag-graphrag) | [Parallel Workers](#pipeline-orchestration--parallel-processing) | [Conflict Resolution](#production-ready-quality-assurance) |---diff --cc docs/cookbook.mdindex 37a8a2fc,c93870e0..d638e4f1--- a/docs/cookbook.md+++ b/docs/cookbook.md@@@ -1,103 -1,305 +1,329 @@@- # Cookbook Recipes+ # π³ Semantica Cookbook- Interactive Jupyter notebooks with hands-on examples and tutorials.+ Welcome to the **Semantica Cookbook**!- ## Introduction+ This collection of Jupyter notebooks is designed to take you from a beginner to an expert in building semantic AI applications. Whether you're looking for quick recipes or deep-dive tutorials, you'll find it here.- Get started with Semantica through these beginner-friendly tutorials.+ !!! tip "How to use this Cookbook"+ - **Beginners**: Start with the [Core Tutorials](#core-tutorials) to learn the basics.+ - **Developers**: Check out [Advanced Concepts](#advanced-concepts) for deep dives into specific features.+ - **Architects**: Explore [Industry Use Cases](#industry-use-cases) for end-to-end solutions.- ### Getting Started+ !!! note "Prerequisites"+ Before running these notebooks, ensure you have:+ - Python 3.8+ installed+ - A basic understanding of Python and Jupyter+ - An OpenAI API key (for most examples)- - **[Welcome to Semantica](cookbook/introduction/Welcome_to_Semantica.ipynb)** - Introduction to the framework- - **[Your First Knowledge Graph](cookbook/introduction/Your_First_Knowledge_Graph.ipynb)** - Build your first KG- - **[Configuration Basics](cookbook/introduction/Configuration_Basics.ipynb)** - Learn configuration options+ !!! success "Installation"+ Install Semantica from PyPI (recommended):++ ```bash+ pip install semantica+ # Or with all optional dependencies:+ pip install semantica[all]+ ```++ For more installation options, see the [Installation Guide](installation.md).- ### Core Concepts+ ---- - **[Data Ingestion](cookbook/introduction/Data_Ingestion.ipynb)** - Ingest data from various sources- - **[Document Parsing](cookbook/introduction/Document_Parsing.ipynb)** - Parse different document formats- - **[Data Normalization](cookbook/introduction/Data_Normalization.ipynb)** - Normalize and clean data- - **[Entity Extraction](cookbook/introduction/Entity_Extraction.ipynb)** - Extract entities from text- - **[Relation Extraction](cookbook/introduction/Relation_Extraction.ipynb)** - Extract relationships- - **[Building Knowledge Graphs](cookbook/introduction/Building_Knowledge_Graphs.ipynb)** - Construct KGs+ ## οΏ½ Featured Recipes- ### Quality and Analysis+ Hand-picked tutorials to show you the power of Semantica.- - **[Conflict Detection](cookbook/introduction/Conflict_Detection.ipynb)** - Detect data conflicts- - **[Deduplication](cookbook/introduction/Deduplication.ipynb)** - Remove duplicates- - **[Graph Quality](cookbook/introduction/Graph_Quality.ipynb)** - Assess KG quality- - **[Graph Analytics](cookbook/introduction/Graph_Analytics.ipynb)** - Analyze knowledge graphs+ <div class="grid cards" markdown>- ### Advanced Features+ - :material-robot: **GraphRAG Complete**+ ---+ Build a production-ready Graph Retrieval Augmented Generation system.++ **Topics**: RAG, LLMs, Vector Search, Graph Traversal++ **Difficulty**: Advanced++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb)- - **[Embedding Generation](cookbook/introduction/Embedding_Generation.ipynb)** - Generate embeddings- - **[Vector Store](cookbook/introduction/Vector_Store.ipynb)** - Store and query vectors- - **[Ontology](cookbook/introduction/Ontology.ipynb)** - Work with ontologies- - **[Visualization](cookbook/introduction/Visualization.ipynb)** - Visualize knowledge graphs- - **[Export](cookbook/introduction/Export.ipynb)** - Export in various formats+ - :material-scale-balance: **RAG vs. GraphRAG Comparison**+ ---+ Side-by-side comparison of Standard RAG vs. GraphRAG using real-world data.++ **Topics**: RAG, GraphRAG, Benchmarking, Visualization++ **Difficulty**: Intermediate++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb)+- :material-robot: **GraphRAG Complete**+ ---+ Build a production-ready Graph Retrieval Augmented Generation system.++ **New Features**: Graph Validation, Logical Inference, Hybrid Context.++ **Topics**: RAG, LLMs, Vector Search, Graph Traversal++ **Difficulty**: Advanced++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb)++- :material-scale-balance: **RAG vs. GraphRAG Comparison**+ ---+ Side-by-side comparison of Standard RAG vs. GraphRAG using real-world data.++ **New Features**: Inference-Enhanced GraphRAG, Reasoning Gap Analysis.++ **Topics**: RAG, GraphRAG, Benchmarking, Visualization++ **Difficulty**: Intermediate++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb)+- ## Advanced+ - :material-graph: **Your First Knowledge Graph**+ ---+ Go from raw text to a queryable knowledge graph in 20 minutes.++ **Topics**: Extraction, Graph Construction, Visualization++ **Difficulty**: Beginner++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/08_Your_First_Knowledge_Graph.ipynb)- Advanced techniques and patterns for experienced users.+ - :material-shield-alert: **Real-Time Anomaly Detection**+ ---+ Detect anomalies in streaming data using dynamic graphs.++ **Topics**: Streaming, Security, Dynamic Graphs++ **Difficulty**: Advanced++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Anomaly_Detection_Real_Time.ipynb)- ### Advanced Extraction+ </div>- - **[Advanced Extraction](cookbook/advanced/Advanced_Extraction.ipynb)** - Advanced extraction techniques- - **[Text Chunking Strategies](cookbook/advanced/Text_Chunking_Strategies.ipynb)** - Optimize text chunking+ ---- ### Graph Operations+ ## π Core Tutorials {#core-tutorials}- - **[Advanced Graph Analytics](cookbook/advanced/Advanced_Graph_Analytics.ipynb)** - Advanced graph analysis- - **[Temporal Knowledge Graphs](cookbook/advanced/Temporal_Knowledge_Graphs.ipynb)** - Work with temporal data- - **[Semantic Layer Construction](cookbook/advanced/Semantic_Layer_Construction.ipynb)** - Build semantic layers+ Essential guides to master the Semantica framework.- ### Integration and Processing+ <div class="grid cards" markdown>- - **[Multi-Source Data Integration](cookbook/advanced/Multi_Source_Data_Integration.ipynb)** - Integrate multiple sources- - **[Pipeline Orchestration](cookbook/advanced/Pipeline_Orchestration.ipynb)** - Orchestrate complex pipelines- - **[Unstructured to Ontology](cookbook/advanced/Unstructured_to_Ontology.ipynb)** - Convert unstructured to ontology+ - :material-hand-wave: **Welcome to Semantica**+ ---+ An interactive introduction to the framework's core philosophy and all modules including ingestion, parsing, extraction, knowledge graphs, embeddings, and more.++ **Topics**: Framework Overview, Architecture, All Modules++ **Difficulty**: Beginner++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/01_Welcome_to_Semantica.ipynb)- ### Quality and Resolution+ - :material-database-import: **Data Ingestion**+ ---+ Techniques for loading data from multiple sources using FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, RepoIngestor, EmailIngestor, DBIngestor, and MCPIngestor.++ **Topics**: File Ingestion, Web Scraping, Database Integration, Streams, Feeds, Repositories, Email, MCP++ **Difficulty**: Beginner++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/02_Data_Ingestion.ipynb)- - **[Conflict Resolution Strategies](cookbook/advanced/Conflict_Resolution_Strategies.ipynb)** - Advanced conflict resolution- - **[Reasoning and Inference](cookbook/advanced/Reasoning_and_Inference.ipynb)** - Perform reasoning+ - :material-file-document-outline: **Document Parsing**+ ---+ Extracting clean text from complex formats like PDF, DOCX, and HTML.++ **Topics**: OCR, PDF Parsing, Text Extraction++ **Difficulty**: Beginner++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/03_Document_Parsing.ipynb)- ### Visualization and Export+ - :material-broom: **Data Normalization**+ ---+ Pipelines for cleaning, normalizing, and preparing text.++ **Topics**: Text Cleaning, Unicode, Formatting++ **Difficulty**: Beginner++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/04_Data_Normalization.ipynb)- - **[Complete Visualization Suite](cookbook/advanced/Complete_Visualization_Suite.ipynb)** - Comprehensive visualization- - **[Multi-Format Export](cookbook/advanced/Multi_Format_Export.ipynb)** - Export to multiple formats+ - :material-account-search: **Entity Extraction**+ ---+ Using NER to identify people, organizations, and custom entities.++ **Topics**: NER, Spacy, LLM Extraction++ **Difficulty**: Beginner++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/05_Entity_Extraction.ipynb)- ## Use Cases+ - :material-relation-many-to-many: **Relation Extraction**+ ---+ Discovering and classifying relationships between entities.++ **Topics**: Relation Classification, Dependency Parsing++ **Difficulty**: Beginner++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/06_Relation_Extraction.ipynb)- Real-world applications across various domains.+ - :material-vector-square: **Embedding Generation**+ ---+ Creating and managing vector embeddings for semantic search.++ **Topics**: Embeddings, OpenAI, HuggingFace++ **Difficulty**: Intermediate++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/12_Embedding_Generation.ipynb)- ### Advanced RAG+ - :material-database-search: **Vector Store**+ ---+ Setting up vector stores for similarity search and retrieval.++ **Difficulty**: Intermediate++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/13_Vector_Store.ipynb)- - **[GraphRAG Complete](cookbook/use_cases/advanced_rag/GraphRAG_Complete.ipynb)** - Complete GraphRAG implementation+ - :material-database-settings: **Graph Store**+ ---+ Persisting knowledge graphs in Neo4j or FalkorDB.++ **Topics**: Neo4j, Cypher, Persistence++ **Difficulty**: Intermediate++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/09_Graph_Store.ipynb)++ - :material-sitemap: **Ontology**+ ---+ Defining domain schemas and ontologies to structure your data.++ **Topics**: OWL, RDF, Schema Design++ **Difficulty**: Intermediate++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/14_Ontology.ipynb)++ </div>++ ---++ ## π§ Advanced Concepts++ Deep dive into advanced features, customization, and complex workflows.++ <div class="grid cards" markdown>++ - :material-flask: **Advanced Extraction**+ ---+ Custom extractors, LLM-based extraction, and complex pattern matching.++ **Topics**: Custom Models, Regex, LLMs++ **Difficulty**: Advanced++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/01_Advanced_Extraction.ipynb)++ - :material-chart-network: **Advanced Graph Analytics**+ ---+ Centrality, community detection, and pathfinding algorithms.++ **Topics**: PageRank, Louvain, Shortest Path++ **Difficulty**: Advanced++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/02_Advanced_Graph_Analytics.ipynb)++ - :material-brain: **Advanced Context Engineering**+ ---+ Build a production-grade memory system for AI agents using persistent Vector (FAISS) and Graph (Neo4j) stores.++ **Topics**: Agent Memory, GraphRAG, Entity Injection, Lifecycle Management++ **Difficulty**: Advanced++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/11_Advanced_Context_Engineering.ipynb)++ - :material-monitor-dashboard: **Complete Visualization Suite**+ ---+ Creating interactive, publication-ready visualizations of your graphs.++ **Topics**: PyVis, NetworkX, D3.js++ **Difficulty**: Intermediate++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/03_Complete_Visualization_Suite.ipynb)++ - :material-scale-balance: **Conflict Resolution**+ ---+ Strategies for handling contradictory information from multiple sources.++ **Topics**: Truth Discovery, Voting, Confidence++ **Difficulty**: Advanced++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/17_Conflict_Detection_and_Resolution.ipynb)++ - :material-export: **Multi-Format Export**+ ---+ Exporting to RDF, OWL, JSON-LD, and NetworkX formats.++ **Topics**: Serialization, Interoperability++ **Difficulty**: Intermediate++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/05_Multi_Format_Export.ipynb)++ - :material-source-merge: **Multi-Source Integration**+ ---+ Merging data from disparate sources into a unified graph.++ **Topics**: Entity Resolution, Merging, Fusion++ **Difficulty**: Advanced++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/06_Multi_Source_Data_Integration.ipynb)+++ - :material-brain: **Reasoning and Inference**+ ---+ Using logical reasoning to infer new knowledge from existing facts.++ **Topics**: Logic Rules, Inference Engines++ **Difficulty**: Advanced++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/08_Reasoning_and_Inference.ipynb)++ - :material-layers: **Semantic Layer Construction**+ ---+ Building a semantic layer over your data warehouse or lake.++ **Topics**: Semantic Layer, Data Warehouse++ **Difficulty**: Advanced++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/09_Semantic_Layer_Construction.ipynb)++ - :material-clock-outline: **Temporal Knowledge Graphs**+ ---+ Modeling and querying data that changes over time.++ **Topics**: Time Series, Temporal Logic++ **Difficulty**: Advanced++ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/10_Temporal_Knowledge_Graphs.ipynb)++ </div>++ ---++ ## π Industry Use Cases {#industry-use-cases}++ Real-world examples and end-to-end applications across various industries.### Biomedicaldiff --cc docs/examples.mdindex fb990e5a,e27cef44..b6635174--- a/docs/examples.md+++ b/docs/examples.md@@@ -152,37 -159,16 +159,38 @@@ semantica = Semantica(# Build graphs separatelykg1 = semantica.kg.build_graph(["source1.pdf"])kg2 = semantica.kg.build_graph(["source2.pdf"])- kg3 = semantica.kg.build_graph(["source3.pdf"])# Merge into unified graph- merged_kg = semantica.kg.merge([kg1, kg2, kg3])-- print(f"Merged graph: {len(merged_kg['entities'])} entities")+ merged_kg = semantica.kg.merge([kg1, kg2])```- ### Example 8: Visualization+ ---- Create interactive visualizations:+ ## Advanced Patterns (30+ min examples)- ```python- from semantica import Semantica-### Example 7: Graph Store (Persistent Storage)++### Example 7: Graph Visualization+- semantica = Semantica()++**Difficulty**: Beginner+- # Build graph- result = semantica.build_knowledge_base(["document.pdf"])- kg = result["knowledge_graph"]++Visualize your knowledge graph to understand entity relationships.+- # Visualize- semantica.kg.visualize(kg, output_path="graph.html")++```python++import semantica++from semantica.visualization import GraphVisualizer++++# Build a small graph++kg = semantica.kg.build_graph(["semantica_intro.pdf"])+- # Also analyze- analysis = semantica.kg.analyze(kg)- print(f"Graph density: {analysis['density']}")- print(f"Connected components: {analysis['components']}")++# Visualize++viz = GraphVisualizer()++viz.plot(kg, title="Semantica Knowledge Map")+```+- ### Example 9: Persistent Storage (Neo4j)++---++++## Advanced Patterns (30+ min examples)++++### Example 8: Persistent Storage (Neo4j)**Difficulty**: Intermediate@@@ -218,7 -204,7 +226,7 @@@ store.create_relationshipstore.close()```- ### Example 10: FalkorDB for Real-Time Applications-### Example 8: FalkorDB for Real-Time Applications++### Example 9: FalkorDB for Real-Time Applications**Difficulty**: Intermediate@@@ -240,47 -226,11 +248,47 @@@ results = store.execute_query("MATCH (nstore.close()```- ### Example 11: GraphRAG (Knowledge-Powered Retrieval)++### Example 10: GraphRAG (Knowledge-Powered Retrieval)++**Difficulty**: Advanced++Build a production-ready GraphRAG system with logical inference and hybrid retrieval.++```python+from semantica.context import AgentContext+from semantica.reasoning import InferenceEngine++# Initialize context with Hybrid Retrieval+context = AgentContext(+ vector_store=vs,+ knowledge_graph=kg,+ use_graph_expansion=True,+ hybrid_alpha=0.7+)++# Add logical reasoning rules+engine = InferenceEngine(strategy="forward")+engine.add_rule("IF ?x :type 'Library' AND ?y :type 'Language' THEN ?x :builtWith ?y")++# Retrieve context for a query+results = context.retrieve("What technologies are used in this project?")+```++[**View Complete GraphRAG Tutorial**](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb)+- ### Example 12: RAG vs. GraphRAG Comparison++### Example 11: RAG vs. GraphRAG Comparison++**Difficulty**: Intermediate++Benchmark standard Vector RAG against Graph-enhanced retrieval.++[**View RAG vs. GraphRAG Comparison**](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb)+---## Production Patterns- ### Example 13: Streaming Data Processing-### Example 9: Streaming Data Processing++### Example 12: Streaming Data Processing**Difficulty**: Advanced@@@ -289,89 -239,39 +297,39 @@@ Process data streams in real-time```pythonfrom semantica.ingest import StreamIngestorfrom semantica.core import Semantica- ```-- ## Use Case Examples-- ### Research Paper Analysis-- Extract knowledge from research papers:-- ```python- from semantica import Semanticasemantica = Semantica()-- # Process research paper- result = semantica.build_knowledge_base([- "papers/ai_research.pdf",- "papers/ml_survey.pdf"- ])-- kg = result["knowledge_graph"]-- # Find key concepts- concepts = [e for e in kg["entities"] if e["type"] == "CONCEPT"]- print(f"Found {len(concepts)} key concepts")+ stream_ingestor = StreamIngestor(stream_uri="kafka://localhost:9092/topic")++ for batch in stream_ingestor.stream(batch_size=100):+ result = semantica.build_knowledge_base(+ sources=batch,+ embeddings=True,+ graph=True+ )+ # Process results```- ### Company Intelligence-- Build knowledge graph from company documents:-- ```python- from semantica import Semantica-- semantica = Semantica()-- # Company documents- sources = [- "company/annual_report.pdf",- "company/press_releases/",- "company/website_content.html"- ]-- result = semantica.build_knowledge_base(sources)- kg = result["knowledge_graph"]-- # Export for analysis- semantica.export.to_json(kg, "company_intelligence.json")- ```-### Example 10: Batch Processing Large Datasets++### Example 13: Batch Processing Large Datasets- ### News Article Processing+ **Difficulty**: Intermediate- Process and analyze news articles:+ Process large datasets efficiently with batching.```python- from semantica import Semantica+ from semantica.core import Semanticasemantica = Semantica()+ sources = [f"data/doc_{i}.pdf" for i in range(1000)]+ batch_size = 50- # News articles- articles = [- "https://example.com/article1",- "https://example.com/article2",- "https://example.com/article3"- ]-- result = semantica.build_knowledge_base(articles)- kg = result["knowledge_graph"]-- # Extract key entities- people = [e for e in kg["entities"] if e["type"] == "PERSON"]- organizations = [e for e in kg["entities"] if e["type"] == "ORGANIZATION"]-- print(f"People mentioned: {len(people)}")- print(f"Organizations: {len(organizations)}")+ for i in range(0, len(sources), batch_size):+ batch = sources[i:i+batch_size]+ result = semantica.build_knowledge_base(batch)+ # Save intermediate results```- ## Interactive Examples-- For more interactive examples and tutorials, check out our [Cookbook](cookbook.md) with Jupyter notebooks covering:-- - **Introduction**: Getting started tutorials- - **Advanced**: Advanced techniques and patterns- - **Use Cases**: Real-world applications in various domains+ ---## More Resources