Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Add intelligence cookbook notebooks: Criminal Network Analysis, Law Enforcement & Forensics, and Intelligence Analysis with Orchestrator-Worker pattern

KaifAhmad12325991e6de0
diff --git a/FINAL_PLAN.md b/FINAL_PLAN.md
new file mode 100644
index 00000000..ec7bafa1
--- /dev/null
+++ b/FINAL_PLAN.md
@@ -0,0 +1,237 @@
+# Add Intelligence Cookbook Notebooks with MCP, Agents, and Orchestrator-Worker Pattern
+
+## Overview
+Add comprehensive intelligence-focused notebooks to `cookbook/use_cases/intelligence/` with complete end-to-end pipelines. The **Intelligence Analysis** notebook will use the **Orchestrator-Worker Pattern** with detailed graph analytics, hybrid RAG, and ontology building. Update documentation in `docs/cookbook.md` and `docs/use-cases.md`.
+
+## New Notebooks to Create
+
+### 1. Criminal Network Analysis (`Criminal_Network_Analysis.ipynb`)
+Complete pipeline from data sources to GraphRAG with agent-based workflows:
+- **Data Sources**: Ingest from police reports, court records, surveillance data, communication logs
+- **MCP Integration**: Utilize MCP for accessing public records databases, court records APIs, and real-time data streams
+- **Semantica Agents**:
+ - Data Gathering Agent (autonomous data collection with AgentMemory)
+ - Network Analysis Agent (graph analytics and community detection)
+ - Pattern Detection Agent (identifying suspicious patterns)
+ - Report Generation Agent (compiling intelligence reports)
+- **Agent Coordination**: Use Pipeline module for parallel agent workflows
+- **Agent Memory**: AgentMemory for persistent context across interactions
+- **Complete Pipeline**: Data sources → MCP → Parsing → Extraction → KG → Graph Analytics → GraphRAG → Agent Analysis → Visualization → Reporting
+
+### 2. Law Enforcement and Forensics (`Law_Enforcement_Forensics.ipynb`)
+Complete forensic analysis pipeline with agent-based workflows:
+- **Data Sources**: Case files, evidence logs, witness statements, forensic reports, crime scene data
+- **Semantica Agents**:
+ - Evidence Collection Agent (autonomous evidence gathering)
+ - Timeline Analysis Agent (temporal case timelines)
+ - Cross-Case Correlation Agent (connections across cases)
+ - Forensic Report Agent (comprehensive report generation)
+- **Agent Coordination**: Multi-agent pipeline for parallel evidence processing
+- **Agent Memory**: Persistent memory for case context and evidence chains
+- **Complete Pipeline**: Case files → Parsing → Evidence Extraction → Temporal KG → Graph Analytics → GraphRAG → Agent Analysis → Visualization → Reporting
+
+### 3. Intelligence Analysis (`Intelligence_Analysis.ipynb`) - **ORCHESTRATOR-WORKER PATTERN**
+Comprehensive intelligence analysis using **Orchestrator-Worker Pattern** with detailed implementation:
+
+#### Orchestrator-Worker Architecture:
+- **Orchestrator**: ExecutionEngine coordinates all workers using PipelineBuilder and ParallelismManager
+- **Worker 1 - Data Ingestion Worker**: Handles multi-source data ingestion (FileIngestor, WebIngestor, StreamIngestor, FeedIngestor, DBIngestor)
+- **Worker 2 - Ontology Building Worker**: Complete 6-stage ontology generation pipeline
+ - Stage 1: Semantic Network Parsing (extract domain concepts)
+ - Stage 2: YAML-to-Definition (transform concepts to 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)
+- **Worker 3 - Graph Construction Worker**: Builds knowledge graphs (GraphBuilder, TemporalGraphQuery)
+- **Worker 4 - Graph Analytics Worker**: Comprehensive graph analytics including:
+ - Centrality Measures: PageRank, Betweenness, Closeness, Eigenvector
+ - Community Detection: Louvain algorithm
+ - Connectivity Analysis: Path finding, shortest paths, connectivity metrics
+ - Graph Metrics: Density, clustering coefficient, diameter, radius
+- **Worker 5 - Hybrid RAG Worker**: Complete hybrid RAG implementation:
+ - Vector Store setup with embeddings
+ - Knowledge Graph queries
+ - Hybrid Search (combining vector similarity + graph traversal)
+ - Context Retrieval (ContextRetriever)
+ - Query Orchestration across KG and vector store
+- **Worker 6 - Intelligence Analysis Worker**: Threat assessment, geospatial analysis, pattern detection
+- **Worker 7 - Report Generation Worker**: Compiles comprehensive intelligence reports
+
+#### Complete Features:
+- **Data Sources**: OSINT feeds, threat intelligence, social media, news, public records, geospatial data
+- **MCP Integration**: Real-time data fetching, web scraping, API integration, browser automation for OSINT
+- **Agent Memory**: Persistent memory for threat context and intelligence history
+- **Complete Pipeline**: OSINT sources → MCP → Orchestrator → Parallel Workers → Ontology → KG → Graph Analytics → Hybrid RAG → Intelligence Analysis → Visualization → Reporting
+
+## Files to Create/Modify
+
+### New Notebooks (in `cookbook/use_cases/intelligence/`)
+- `Criminal_Network_Analysis.ipynb`
+- `Law_Enforcement_Forensics.ipynb`
+- `Intelligence_Analysis.ipynb` (with Orchestrator-Worker Pattern)
+
+### Documentation Updates
+- `docs/cookbook.md` - Add new notebooks to Intelligence section
+- `docs/use-cases.md` - Add use case cards for Criminal Network Analysis and Law Enforcement & Forensics
+
+## Implementation Details
+
+### Intelligence Analysis - Orchestrator-Worker Pipeline Structure:
+
+1. **Orchestrator Setup** - Initialize ExecutionEngine, PipelineBuilder, ParallelismManager
+2. **Data Sources** - Multiple ingestion (FileIngestor, DBIngestor, WebIngestor, StreamIngestor, FeedIngestor)
+3. **MCP Integration** - External data access, web scraping, browser automation
+4. **Worker 1 - Data Ingestion Worker** - Parallel data gathering from multiple sources
+5. **Data Parsing** - Parse structured/unstructured data (JSONParser, XMLParser, CSVParser, DocumentParser, StructuredDataParser)
+6. **Data Normalization** - Clean and standardize (TextNormalizer, DataNormalizer)
+7. **Entity & Relation Extraction** - Extract entities, relationships, events (NERExtractor, RelationExtractor, TripleExtractor, EventDetector)
+8. **Worker 2 - Ontology Building Worker** - Complete 6-stage ontology generation:
+ - Use OntologyGenerator, ClassInferrer, PropertyGenerator
+ - Generate OWL/Turtle with OWLGenerator
+ - Validate with OntologyValidator (HermiT/Pellet)
+9. **Worker 3 - Graph Construction Worker** - Build knowledge graphs:
+ - GraphBuilder for entity/relationship graphs
+ - TemporalGraphQuery for time-aware graphs
+10. **Worker 4 - Graph Analytics Worker** - All graph analytics:
+ - GraphAnalyzer: PageRank, Betweenness, Closeness, Eigenvector centrality
+ - CommunityDetector: Louvain community detection
+ - ConnectivityAnalyzer: Path finding, shortest paths, connectivity
+ - CentralityCalculator: All centrality measures
+ - Graph metrics: density, clustering, diameter, radius
+11. **Worker 5 - Hybrid RAG Worker** - Complete hybrid RAG:
+ - EmbeddingGenerator: Generate embeddings for entities and text
+ - VectorStore: Store and index embeddings
+ - HybridSearch: Combine vector similarity + graph queries
+ - ContextRetriever: Retrieve relevant context from KG and vectors
+ - Query orchestration: Coordinate queries across KG and vector store
+12. **Worker 6 - Intelligence Analysis Worker** - Threat assessment, geospatial analysis, pattern detection
+13. **Agent Memory Integration** - Store and retrieve agent context using AgentMemory
+14. **Orchestrator Coordination** - Coordinate all workers with parallel execution
+15. **Visualization** - Network graphs, analytics dashboards, maps (KGVisualizer, AnalyticsVisualizer, TemporalVisualizer)
+16. **Worker 7 - Report Generation Worker** - Compile comprehensive intelligence reports
+17. **Report Generation** - Professional HTML reports (ReportGenerator, HTMLExporter)
+
+### Other Notebooks - Standard Pipeline Structure:
+
+1. **Data Sources** - Multiple ingestion
+2. **MCP Integration** - (Criminal Network Analysis only)
+3. **Semantica Agent Setup** - Initialize AgentMemory, create specialized agents
+4. **Agent-Based Data Gathering** - Autonomous agents gather data
+5. **Data Parsing** - Parse structured/unstructured data
+6. **Data Normalization** - Clean and standardize
+7. **Entity & Relation Extraction** - Extract entities, relationships, events
+8. **Knowledge Graph Construction** - Build graphs
+9. **Agent-Based Analysis** - Specialized agents perform parallel analysis
+10. **Graph Analytics** - Community detection, centrality, connectivity
+11. **GraphRAG Implementation** - Embeddings, vector store, hybrid search
+12. **Agent Memory Integration** - Store and retrieve agent context
+13. **Detailed Analysis** - Reasoning, inference, pattern detection
+14. **Agent Coordination** - Pipeline module for multi-agent workflow orchestration
+15. **Visualization** - Network graphs, analytics dashboards, maps
+16. **Agent-Based Report Generation** - Agents compile comprehensive reports
+17. **Report Generation** - Professional HTML reports
+
+### Semantica Agent Implementation:
+
+- **AgentMemory**: Persistent context storage, memory retrieval, conversation history
+- **Pipeline Coordination**: PipelineBuilder, ExecutionEngine, ParallelismManager for multi-agent workflows
+- **Specialized Agents**: Each agent has specific role (data gathering, analysis, reporting)
+- **Agent Examples**: Code demonstrations of agent workflows with memory integration
+
+### MCP Integration:
+
+- **Intelligence Analysis**: MCP browser tools for OSINT, resources for external feeds
+- **Criminal Network Analysis**: MCP for public records, court databases, API integration
+- **Agent-MCP Coordination**: Agents use MCP for autonomous data gathering
+
+### Notebook Structure:
+
+#### Intelligence Analysis (Orchestrator-Worker Pattern):
+- Overview with Orchestrator-Worker pattern explanation
+- Semantica modules used (30+ modules including Orchestrator, Workers, Ontology, Graph Analytics, Hybrid RAG)
+- **Orchestrator Architecture**: Detailed explanation of orchestrator and worker roles
+- **Worker Implementation**: Detailed code for each worker (7 workers)
+- **Ontology Building**: Complete 6-stage ontology generation pipeline demonstration
+- **Graph Analytics**: All analytics methods (PageRank, Betweenness, Closeness, Eigenvector, Louvain, connectivity, paths)
+- **Hybrid RAG**: Complete implementation with KG queries + vector search, query orchestration
+- MCP integration demonstration
+- Step-by-step implementation with orchestrator coordinating workers
+- Parallel worker execution examples
+- Agent memory integration
+- Best practices for orchestrator-worker pattern
+- Best practices for agents and MCP
+- Conclusion with key takeaways
+
+#### Other Notebooks:
+- Overview with complete pipeline description
+- Semantica modules used (20+ modules including AgentMemory, Pipeline)
+- Agent Architecture explanation
+- MCP integration demonstration (Criminal Network Analysis)
+- Step-by-step implementation with agent workflows
+- Agent memory integration examples
+- Multi-agent pipeline orchestration
+- Best practices for agents and MCP
+- Conclusion with key takeaways
+
+## Key Implementation Details for Orchestrator-Worker Pattern:
+
+### Orchestrator Code Example:
+```python
+from semantica.pipeline import PipelineBuilder, ExecutionEngine, ParallelismManager
+from semantica.ontology import OntologyGenerator
+from semantica.kg import GraphBuilder, GraphAnalyzer
+from semantica.vector_store import VectorStore, HybridSearch
+from semantica.context import AgentMemory
+
+# Initialize orchestrator
+orchestrator = ExecutionEngine()
+parallelism_manager = ParallelismManager(max_workers=7)
+
+# Define workers
+def data_ingestion_worker(sources):
+ # Worker 1: Multi-source data ingestion
+ pass
+
+def ontology_building_worker(entities, relationships):
+ # Worker 2: Complete 6-stage ontology generation
+ ontology_gen = OntologyGenerator()
+ ontology = ontology_gen.generate_ontology({"entities": entities, "relationships": relationships})
+ return ontology
+
+def graph_construction_worker(entities, relationships):
+ # Worker 3: Build knowledge graph
+ graph_builder = GraphBuilder()
+ kg = graph_builder.build(entities, relationships)
+ return kg
+
+def graph_analytics_worker(kg):
+ # Worker 4: All graph analytics
+ analyzer = GraphAnalyzer()
+ pagerank = analyzer.compute_centrality(kg, method="pagerank")
+ betweenness = analyzer.compute_centrality(kg, method="betweenness")
+ communities = analyzer.detect_communities(kg, method="louvain")
+ # ... all analytics
+ return {"pagerank": pagerank, "betweenness": betweenness, "communities": communities}
+
+def hybrid_rag_worker(kg, vector_store):
+ # Worker 5: Hybrid RAG with KG and vector store
+ hybrid_search = HybridSearch(vector_store=vector_store, knowledge_graph=kg)
+ # Query orchestration
+ pass
+
+# Build pipeline with workers
+pipeline = PipelineBuilder() \
+ .add_step("data_ingestion", "custom", func=data_ingestion_worker) \
+ .add_step("ontology_building", "custom", func=ontology_building_worker) \
+ .add_step("graph_construction", "custom", func=graph_construction_worker) \
+ .add_step("graph_analytics", "custom", func=graph_analytics_worker) \
+ .add_step("hybrid_rag", "custom", func=hybrid_rag_worker) \
+ .build()
+
+# Execute with parallel workers
+result = orchestrator.execute_pipeline(pipeline, parallel=True, max_workers=7)
+```
+
+Each notebook demonstrates the full journey from raw data sources through autonomous agent workflows (or orchestrator-worker pattern) and GraphRAG to actionable intelligence.
+
diff --git a/UPDATED_PLAN.md b/UPDATED_PLAN.md
new file mode 100644
index 00000000..48a2ddf4
--- /dev/null
+++ b/UPDATED_PLAN.md
@@ -0,0 +1,206 @@
+# Add Intelligence Cookbook Notebooks with MCP and Semantica Agents
+
+## Overview
+Add comprehensive intelligence-focused notebooks to `cookbook/use_cases/intelligence/` with complete end-to-end pipelines covering data ingestion (including MCP integration), knowledge graph construction, GraphRAG implementation, **Semantica agent-based workflows**, and detailed analysis. Update documentation in `docs/cookbook.md` and `docs/use-cases.md`.
+
+## New Notebooks to Create
+
+### 1. Criminal Network Analysis (`Criminal_Network_Analysis.ipynb`)
+Complete pipeline from data sources to GraphRAG with **agent-based workflows**:
+- **Data Sources**: Ingest from police reports, court records, surveillance data, communication logs
+- **MCP Integration**: Utilize MCP for accessing public records databases, court records APIs, and real-time data streams
+- **Semantica Agents**:
+ - **Data Gathering Agent**: Autonomous agent using AgentMemory to gather and track data from multiple sources
+ - **Network Analysis Agent**: Specialized agent for graph analytics and community detection
+ - **Pattern Detection Agent**: Agent for identifying suspicious patterns and relationships
+ - **Report Generation Agent**: Agent for compiling intelligence reports
+- **Agent Coordination**: Use Pipeline module (PipelineBuilder, ExecutionEngine, ParallelismManager) to coordinate parallel agent workflows
+- **Agent Memory**: Use AgentMemory for persistent context across agent interactions
+- **Parsing**: Parse structured/unstructured documents, JSON, CSV, PDFs
+- **Extraction**: Extract suspects, organizations, locations, events, relationships
+- **Knowledge Graph**: Build criminal network graph with temporal relationships
+- **Graph Analytics**: Community detection, centrality measures, key player identification
+- **GraphRAG**: Vector store, hybrid search, context retrieval for intelligence queries
+- **Detailed Analysis**: Pattern detection, network structure analysis, threat assessment
+- **Visualization**: Network graphs, community visualization, centrality rankings
+- **Reporting**: Generate intelligence reports on criminal structures
+
+### 2. Law Enforcement and Forensics (`Law_Enforcement_Forensics.ipynb`)
+Complete forensic analysis pipeline with **agent-based workflows**:
+- **Data Sources**: Case files, evidence logs, witness statements, forensic reports, crime scene data
+- **Semantica Agents**:
+ - **Evidence Collection Agent**: Autonomous agent for gathering and organizing evidence
+ - **Timeline Analysis Agent**: Agent for building temporal case timelines
+ - **Cross-Case Correlation Agent**: Agent for finding connections across multiple cases
+ - **Forensic Report Agent**: Agent for generating comprehensive forensic reports
+- **Agent Coordination**: Multi-agent pipeline for parallel evidence processing
+- **Agent Memory**: Persistent memory for case context and evidence chains
+- **Parsing**: Parse PDFs, structured reports, evidence databases, temporal logs
+- **Extraction**: Extract entities (persons, locations, evidence, events), relationships, timelines
+- **Knowledge Graph**: Build temporal knowledge graph for case timelines and evidence correlation
+- **Graph Analytics**: Timeline analysis, evidence correlation, pattern detection across cases
+- **GraphRAG**: Semantic search across case files, evidence retrieval, context-aware queries
+- **Detailed Analysis**: Cross-case correlation, evidence chain analysis, suspect identification
+- **Visualization**: Timeline visualization, evidence networks, case correlation graphs
+- **Reporting**: Generate forensic analysis reports with evidence chains
+
+### 3. Intelligence Analysis (`Intelligence_Analysis.ipynb`)
+Comprehensive intelligence analysis with **agent-based workflows**:
+- **Data Sources**: OSINT feeds, threat intelligence, social media, news, public records, geospatial data
+- **MCP Integration**: Utilize MCP for real-time data fetching, web scraping, API integration, external database access, and browser automation for OSINT gathering
+- **Semantica Agents**:
+ - **OSINT Gathering Agent**: Autonomous agent using MCP browser tools for web scraping and OSINT collection
+ - **Threat Assessment Agent**: Specialized agent for threat analysis and risk scoring
+ - **Geospatial Intelligence Agent**: Agent for location-based tracking and geographic analysis
+ - **Multi-Source Fusion Agent**: Agent for correlating intelligence from multiple sources
+ - **Intelligence Report Agent**: Agent for generating comprehensive threat intelligence reports
+- **Agent Coordination**: Complex multi-agent pipeline with parallel execution for intelligence gathering
+- **Agent Memory**: Persistent memory for threat context, entity tracking, and intelligence history
+- **Parsing**: Multi-format parsing (RSS feeds, JSON, XML, web scraping, geospatial formats)
+- **Extraction**: Extract threat actors, locations, events, relationships, temporal patterns
+- **Knowledge Graph**: Build multi-source intelligence graph with geospatial and temporal dimensions
+- **Graph Analytics**: Threat assessment, risk scoring, entity relationship mapping, pattern detection
+- **GraphRAG**: Multi-source intelligence fusion, hybrid search, contextual threat queries
+- **Detailed Analysis**:
+ - Multi-source intelligence fusion and correlation
+ - Threat assessment and risk analysis
+ - Geospatial intelligence with location tracking
+ - Temporal threat evolution analysis
+- **Visualization**: Geographic network maps, threat timelines, relationship networks
+- **Reporting**: Generate comprehensive threat intelligence reports
+
+## Files to Create/Modify
+
+### New Notebooks (in `cookbook/use_cases/intelligence/`)
+- `Criminal_Network_Analysis.ipynb`
+- `Law_Enforcement_Forensics.ipynb`
+- `Intelligence_Analysis.ipynb`
+
+### Documentation Updates
+- `docs/cookbook.md` - Add new notebooks to Intelligence section
+- `docs/use-cases.md` - Add new use case cards for criminal networks and law enforcement
+
+## Implementation Details
+
+### Complete Pipeline Structure (All Notebooks):
+1. **Data Sources** - Multiple ingestion sources (FileIngestor, DBIngestor, WebIngestor, StreamIngestor, FeedIngestor)
+2. **MCP Integration** - Utilize MCP servers for external data access, real-time feeds, API integration, web scraping, and browser automation (in Intelligence Analysis and Criminal Network Analysis notebooks)
+3. **Semantica Agent Setup** - Initialize AgentMemory, create specialized agents, set up agent coordination
+4. **Agent-Based Data Gathering** - Autonomous agents gather data using MCP and Semantica ingestors
+5. **Data Parsing** - Parse structured/unstructured data (JSONParser, XMLParser, CSVParser, DocumentParser, StructuredDataParser)
+6. **Data Normalization** - Clean and standardize (TextNormalizer, DataNormalizer)
+7. **Entity & Relation Extraction** - Extract entities, relationships, events (NERExtractor, RelationExtractor, TripleExtractor, EventDetector)
+8. **Knowledge Graph Construction** - Build graphs (GraphBuilder, TemporalGraphQuery)
+9. **Agent-Based Analysis** - Specialized agents perform parallel analysis tasks
+10. **Graph Analytics** - Community detection, centrality, connectivity (GraphAnalyzer, ConnectivityAnalyzer, CentralityCalculator)
+11. **GraphRAG Implementation** - Embeddings, vector store, hybrid search, context retrieval (EmbeddingGenerator, VectorStore, HybridSearch, ContextRetriever)
+12. **Agent Memory Integration** - Store and retrieve agent context using AgentMemory
+13. **Detailed Analysis** - Reasoning, inference, pattern detection (InferenceEngine, RuleManager, ExplanationGenerator)
+14. **Agent Coordination** - Use Pipeline module for multi-agent workflow orchestration
+15. **Visualization** - Network graphs, analytics dashboards, geographic maps (KGVisualizer, AnalyticsVisualizer, TemporalVisualizer)
+16. **Agent-Based Report Generation** - Agents compile and generate professional reports
+17. **Report Generation** - Professional HTML reports (ReportGenerator, HTMLExporter)
+
+### Semantica Agent Implementation Details:
+
+#### AgentMemory Usage:
+- **Persistent Context**: Store agent interactions, decisions, and findings
+- **Memory Retrieval**: Retrieve relevant context for agent decision-making
+- **Conversation History**: Track agent conversations and analysis sessions
+- **Context Accumulation**: Build up intelligence context over time
+
+#### Pipeline Agent Coordination:
+- **PipelineBuilder**: Define multi-agent workflows
+- **ExecutionEngine**: Execute agent pipelines with error handling
+- **ParallelismManager**: Run agents in parallel for efficiency
+- **Specialized Agents**: Each agent has a specific role (data gathering, analysis, reporting)
+
+#### Agent Workflow Examples:
+```python
+# Example: Multi-agent intelligence gathering
+from semantica.context import AgentMemory
+from semantica.pipeline import PipelineBuilder, ExecutionEngine, ParallelismManager
+
+# Initialize agent memory
+agent_memory = AgentMemory(vector_store=vs, knowledge_graph=kg)
+
+# Define specialized agents
+def osint_gathering_agent(query, memory):
+ """Autonomous OSINT gathering agent"""
+ # Use MCP for web scraping
+ # Store findings in agent memory
+ findings = gather_osint(query)
+ memory.store(f"OSINT findings: {findings}", metadata={"agent": "osint", "query": query})
+ return findings
+
+def threat_assessment_agent(intel_data, memory):
+ """Threat assessment agent"""
+ # Retrieve relevant context from memory
+ context = memory.retrieve("threat patterns", max_results=10)
+ # Perform threat analysis
+ assessment = analyze_threats(intel_data, context)
+ memory.store(f"Threat assessment: {assessment}", metadata={"agent": "threat"})
+ return assessment
+
+# Build multi-agent pipeline
+pipeline = PipelineBuilder() \
+ .add_step("osint_gathering", "custom", func=osint_gathering_agent, args=(query, agent_memory)) \
+ .add_step("threat_assessment", "custom", func=threat_assessment_agent, args=(intel_data, agent_memory)) \
+ .build()
+
+# Execute with parallel agents
+engine = ExecutionEngine()
+result = engine.execute_pipeline(pipeline, parallel=True)
+```
+
+### MCP Integration Details:
+- **Intelligence Analysis Notebook**:
+ - Use MCP browser tools for web scraping and OSINT gathering
+ - Use MCP resources for accessing external intelligence feeds
+ - Demonstrate real-time data fetching via MCP
+ - Agents use MCP for autonomous data gathering
+- **Criminal Network Analysis Notebook**:
+ - Use MCP for accessing public records and court databases
+ - Demonstrate API integration via MCP
+ - Show real-time data stream processing
+ - Agents coordinate MCP-based data gathering
+
+### Notebook Structure:
+- Overview with complete pipeline description
+- Semantica modules used (20+ modules including AgentMemory, Pipeline)
+- **Agent Architecture**: Explanation of agent roles and coordination
+- MCP integration demonstration (for Intelligence Analysis and Criminal Network Analysis)
+- Step-by-step implementation:
+ - **Agent Setup**: Initialize AgentMemory and create specialized agents
+ - Data ingestion from multiple sources (including MCP resources)
+ - **Agent-Based Data Gathering**: Autonomous agents gather data
+ - MCP-based external data fetching and API integration
+ - Parsing and normalization
+ - Entity and relation extraction
+ - Knowledge graph construction
+ - **Agent-Based Analysis**: Parallel agent workflows for analysis
+ - Graph analytics and pattern detection
+ - **Agent Memory Integration**: Store and retrieve agent context
+ - GraphRAG setup and query examples
+ - **Agent Coordination**: Multi-agent pipeline orchestration
+ - Detailed analysis with insights
+ - Visualization examples
+ - **Agent-Based Report Generation**: Agents compile reports
+ - Report generation
+- Best practices and deployment recommendations
+- **Agent Best Practices**: Agent memory management, coordination patterns
+- MCP integration best practices
+- Conclusion with key takeaways
+
+Each notebook will be comprehensive, demonstrating the full journey from raw data sources (including MCP-enabled external sources) through **autonomous agent workflows** and GraphRAG to actionable intelligence and detailed analysis.
+
+## Key Agent Features to Highlight:
+
+1. **Autonomous Data Gathering**: Agents independently gather data from multiple sources
+2. **Persistent Memory**: AgentMemory maintains context across sessions
+3. **Parallel Coordination**: Multiple agents work simultaneously on different tasks
+4. **Specialized Roles**: Each agent has a specific expertise area
+5. **Context-Aware Analysis**: Agents use memory to make informed decisions
+6. **Coordinated Workflows**: Pipeline module orchestrates complex multi-agent systems
+7. **Intelligent Reporting**: Agents compile findings into comprehensive reports
+
diff --git a/cookbook/use_cases/intelligence/Criminal_Network_Analysis.ipynb b/cookbook/use_cases/intelligence/Criminal_Network_Analysis.ipynb
new file mode 100644
index 00000000..8dafd3eb
--- /dev/null
+++ b/cookbook/use_cases/intelligence/Criminal_Network_Analysis.ipynb
@@ -0,0 +1,894 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Criminal Network Analysis with Semantica\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates a complete criminal network analysis pipeline using **Semantica as the core framework** with agent-based workflows, MCP integration, and comprehensive graph analytics. The pipeline ingests data from multiple sources (police reports, court records, surveillance data), builds knowledge graphs, performs network analysis, and generates intelligence reports.\n",
+ "\n",
+ "### Why Semantica?\n",
+ "\n",
+ "Semantica provides a complete framework for criminal network analysis:\n",
+ "\n",
+ "- **Multi-Source Data Ingestion**: Ingest from files, databases, web sources, and MCP-enabled external APIs\n",
+ "- **MCP Integration**: Access public records databases, court records APIs, and real-time data streams\n",
+ "- **Agent-Based Workflows**: Autonomous agents with persistent memory for coordinated intelligence gathering\n",
+ "- **Graph Analytics**: Comprehensive network analysis with centrality measures and community detection\n",
+ "- **GraphRAG**: Hybrid retrieval combining knowledge graph queries with vector similarity search\n",
+ "- **Pattern Detection**: Identify suspicious patterns and relationships in criminal networks\n",
+ "- **Intelligence Reporting**: Generate professional HTML reports with actionable insights\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- Ingest criminal network data from multiple sources including MCP-enabled databases\n",
+ "- Autonomous agent-based data gathering with persistent memory\n",
+ "- Extract entities (suspects, organizations, locations, events) and relationships\n",
+ "- Build temporal knowledge graphs for criminal network analysis\n",
+ "- Comprehensive graph analytics (PageRank, Betweenness, Closeness, Eigenvector, Louvain)\n",
+ "- Hybrid RAG for intelligence queries combining KG and vector search\n",
+ "- Pattern detection for identifying key players and suspicious activities\n",
+ "- Professional intelligence report generation\n",
+ "\n",
+ "### Semantica Modules Used (25+)\n",
+ "\n",
+ "- **Ingest**: FileIngestor, DBIngestor, WebIngestor, StreamIngestor (multi-source data ingestion)\n",
+ "- **MCP Integration**: MCP browser tools and resources for external data access\n",
+ "- **Parse**: StructuredDataParser, CSVParser, JSONParser, DocumentParser\n",
+ "- **Normalize**: TextNormalizer, DataNormalizer\n",
+ "- **Semantic Extract**: NERExtractor, RelationExtractor, TripleExtractor, EventDetector\n",
+ "- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer, TemporalGraphQuery\n",
+ "- **Graph Analytics**: PageRank, Betweenness, Closeness, Eigenvector centrality, Louvain community detection\n",
+ "- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",
+ "- **Vector Store**: VectorStore, HybridSearch, MetadataFilter\n",
+ "- **Context**: AgentMemory, ContextRetriever, ContextGraphBuilder\n",
+ "- **Pipeline**: PipelineBuilder, ExecutionEngine, ParallelismManager\n",
+ "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
+ "- **Export**: ReportGenerator, HTMLExporter, JSONExporter\n",
+ "- **Visualization**: KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",
+ "- **Deduplication**: DuplicateDetector, EntityMerger\n",
+ "\n",
+ "### Pipeline Overview\n",
+ "\n",
+ "**Data Sources (Police Reports, Court Records, Surveillance) → MCP Integration → Agent-Based Data Gathering → Parse → Extract Entities/Relationships → Build Criminal Network KG → Graph Analytics → GraphRAG → Agent Analysis → Pattern Detection → Generate Intelligence Report → Visualize**\n",
+ "\n",
+ "---\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 1: Setup and Import Semantica Modules\n",
+ "\n",
+ "Import all necessary Semantica modules for criminal network analysis.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Import all Semantica modules for criminal network analysis\n",
+ "from semantica.ingest import FileIngestor, DBIngestor, WebIngestor, StreamIngestor\n",
+ "from semantica.parse import StructuredDataParser, CSVParser, JSONParser, DocumentParser\n",
+ "from semantica.normalize import TextNormalizer, DataNormalizer\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, EventDetector\n",
+ "from semantica.kg import GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer, TemporalGraphQuery\n",
+ "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
+ "from semantica.vector_store import VectorStore, HybridSearch, MetadataFilter\n",
+ "from semantica.context import AgentMemory, ContextRetriever, ContextGraphBuilder\n",
+ "from semantica.pipeline import PipelineBuilder, ExecutionEngine, ParallelismManager\n",
+ "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
+ "from semantica.export import ReportGenerator, HTMLExporter, JSONExporter\n",
+ "from semantica.visualization import KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",
+ "from semantica.deduplication import DuplicateDetector, EntityMerger\n",
+ "\n",
+ "import tempfile\n",
+ "import os\n",
+ "import json\n",
+ "from datetime import datetime, timedelta\n",
+ "import numpy as np\n",
+ "\n",
+ "print(\"✓ All Semantica modules imported successfully\")\n",
+ "print(\"✓ Ready for criminal network analysis with agent-based workflows\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 2: Initialize Agent Memory and Setup Agents\n",
+ "\n",
+ "Set up AgentMemory for persistent context and initialize specialized agents for criminal network analysis.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize vector store for agent memory\n",
+ "vector_store = VectorStore(backend=\"faiss\", dimension=768)\n",
+ "embedding_generator = EmbeddingGenerator()\n",
+ "\n",
+ "# Initialize agent memory for persistent context\n",
+ "agent_memory = AgentMemory(\n",
+ " vector_store=vector_store,\n",
+ " retention_policy=\"unlimited\",\n",
+ " max_memory_size=10000\n",
+ ")\n",
+ "\n",
+ "# Initialize Semantica modules for agents\n",
+ "file_ingestor = FileIngestor()\n",
+ "db_ingestor = DBIngestor()\n",
+ "web_ingestor = WebIngestor()\n",
+ "graph_analyzer = GraphAnalyzer()\n",
+ "inference_engine = InferenceEngine()\n",
+ "\n",
+ "print(\"✓ Agent memory initialized\")\n",
+ "print(\"✓ Semantica modules ready for agent workflows\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 3: Ingest Criminal Network Data with MCP Integration\n",
+ "\n",
+ "Ingest data from multiple sources including police reports, court records, and surveillance data. Use MCP for accessing external databases and APIs.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Create temporary directory for sample data\n",
+ "temp_dir = tempfile.mkdtemp()\n",
+ "\n",
+ "# Sample criminal network data - police reports\n",
+ "police_reports_data = {\n",
+ " \"reports\": [\n",
+ " {\n",
+ " \"report_id\": \"PR001\",\n",
+ " \"date\": \"2024-01-15\",\n",
+ " \"suspects\": [\"John Doe\", \"Jane Smith\"],\n",
+ " \"location\": \"Downtown District\",\n",
+ " \"incident_type\": \"Drug Trafficking\",\n",
+ " \"description\": \"Multiple suspects observed in suspicious activity. Connection to known criminal organization.\"\n",
+ " },\n",
+ " {\n",
+ " \"report_id\": \"PR002\",\n",
+ " \"date\": \"2024-02-10\",\n",
+ " \"suspects\": [\"Jane Smith\", \"Bob Johnson\"],\n",
+ " \"location\": \"Warehouse District\",\n",
+ " \"incident_type\": \"Money Laundering\",\n",
+ " \"description\": \"Financial transactions linked to criminal network. Multiple bank accounts involved.\"\n",
+ " },\n",
+ " {\n",
+ " \"report_id\": \"PR003\",\n",
+ " \"date\": \"2024-03-05\",\n",
+ " \"suspects\": [\"John Doe\", \"Alice Brown\", \"Charlie Wilson\"],\n",
+ " \"location\": \"Port Area\",\n",
+ " \"incident_type\": \"Smuggling\",\n",
+ " \"description\": \"Cargo shipment investigation reveals connections to international criminal network.\"\n",
+ " }\n",
+ " ]\n",
+ "}\n",
+ "\n",
+ "# Sample court records data\n",
+ "court_records_data = {\n",
+ " \"cases\": [\n",
+ " {\n",
+ " \"case_id\": \"CR001\",\n",
+ " \"defendant\": \"John Doe\",\n",
+ " \"charges\": [\"Drug Trafficking\", \"Conspiracy\"],\n",
+ " \"date\": \"2024-01-20\",\n",
+ " \"outcome\": \"Pending\",\n",
+ " \"co_defendants\": [\"Jane Smith\"]\n",
+ " },\n",
+ " {\n",
+ " \"case_id\": \"CR002\",\n",
+ " \"defendant\": \"Jane Smith\",\n",
+ " \"charges\": [\"Money Laundering\", \"Racketeering\"],\n",
+ " \"date\": \"2024-02-15\",\n",
+ " \"outcome\": \"Pending\",\n",
+ " \"co_defendants\": [\"Bob Johnson\"]\n",
+ " }\n",
+ " ]\n",
+ "}\n",
+ "\n",
+ "# Sample surveillance data\n",
+ "surveillance_data = {\n",
+ " \"observations\": [\n",
+ " {\n",
+ " \"observation_id\": \"SV001\",\n",
+ " \"date\": \"2024-01-18\",\n",
+ " \"subjects\": [\"John Doe\", \"Jane Smith\"],\n",
+ " \"location\": \"Restaurant XYZ\",\n",
+ " \"duration_minutes\": 45,\n",
+ " \"notes\": \"Extended meeting between known associates\"\n",
+ " },\n",
+ " {\n",
+ " \"observation_id\": \"SV002\",\n",
+ " \"date\": \"2024-02-12\",\n",
+ " \"subjects\": [\"Jane Smith\", \"Bob Johnson\"],\n",
+ " \"location\": \"Business Office ABC\",\n",
+ " \"duration_minutes\": 120,\n",
+ " \"notes\": \"Business meeting with financial documents exchange\"\n",
+ " }\n",
+ " ]\n",
+ "}\n",
+ "\n",
+ "# Save sample data files\n",
+ "police_reports_file = os.path.join(temp_dir, \"police_reports.json\")\n",
+ "court_records_file = os.path.join(temp_dir, \"court_records.json\")\n",
+ "surveillance_file = os.path.join(temp_dir, \"surveillance.json\")\n",
+ "\n",
+ "with open(police_reports_file, 'w') as f:\n",
+ " json.dump(police_reports_data, f, indent=2)\n",
+ "with open(court_records_file, 'w') as f:\n",
+ " json.dump(court_records_data, f, indent=2)\n",
+ "with open(surveillance_file, 'w') as f:\n",
+ " json.dump(surveillance_data, f, indent=2)\n",
+ "\n",
+ "# Ingest files using Semantica\n",
+ "police_data = file_ingestor.ingest_file(police_reports_file, read_content=True)\n",
+ "court_data = file_ingestor.ingest_file(court_records_file, read_content=True)\n",
+ "surveillance_data_obj = file_ingestor.ingest_file(surveillance_file, read_content=True)\n",
+ "\n",
+ "# Store in agent memory\n",
+ "agent_memory.store(\n",
+ " \"Ingested police reports, court records, and surveillance data\",\n",
+ " metadata={\n",
+ " \"type\": \"data_ingestion\",\n",
+ " \"sources\": [\"police_reports\", \"court_records\", \"surveillance\"],\n",
+ " \"timestamp\": datetime.now().isoformat()\n",
+ " }\n",
+ ")\n",
+ "\n",
+ "print(f\"✓ Ingested criminal network data\")\n",
+ "print(f\" - Police reports: {len(police_reports_data['reports'])}\")\n",
+ "print(f\" - Court records: {len(court_records_data['cases'])}\")\n",
+ "print(f\" - Surveillance observations: {len(surveillance_data['observations'])}\")\n",
+ "print(f\"✓ Data stored in agent memory\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize parsers and normalizers\n",
+ "json_parser = JSONParser()\n",
+ "structured_parser = StructuredDataParser()\n",
+ "text_normalizer = TextNormalizer()\n",
+ "data_normalizer = DataNormalizer()\n",
+ "\n",
+ "# Parse all data sources\n",
+ "parsed_police = json_parser.parse(police_reports_file)\n",
+ "parsed_court = json_parser.parse(court_records_file)\n",
+ "parsed_surveillance = json_parser.parse(surveillance_file)\n",
+ "\n",
+ "# Combine all parsed data\n",
+ "all_data = {\n",
+ " \"police_reports\": parsed_police.data if hasattr(parsed_police, 'data') else parsed_police,\n",
+ " \"court_records\": parsed_court.data if hasattr(parsed_court, 'data') else parsed_court,\n",
+ " \"surveillance\": parsed_surveillance.data if hasattr(parsed_surveillance, 'data') else parsed_surveillance\n",
+ "}\n",
+ "\n",
+ "print(f\"✓ Parsed all data sources\")\n",
+ "print(f\" - Police reports parsed: {len(all_data['police_reports'].get('reports', [])) if isinstance(all_data['police_reports'], dict) else 0}\")\n",
+ "print(f\" - Court records parsed: {len(all_data['court_records'].get('cases', [])) if isinstance(all_data['court_records'], dict) else 0}\")\n",
+ "print(f\" - Surveillance parsed: {len(all_data['surveillance'].get('observations', [])) if isinstance(all_data['surveillance'], dict) else 0}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 5: Extract Entities and Relationships\n",
+ "\n",
+ "Extract criminal network entities (suspects, organizations, locations, events) and relationships using Semantica's extraction modules.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize extractors\n",
+ "ner_extractor = NERExtractor()\n",
+ "relation_extractor = RelationExtractor()\n",
+ "triple_extractor = TripleExtractor()\n",
+ "event_detector = EventDetector()\n",
+ "\n",
+ "# Extract entities and relationships\n",
+ "criminal_entities = []\n",
+ "criminal_relationships = []\n",
+ "entity_id_map = {} # Map names to IDs\n",
+ "\n",
+ "# Process police reports\n",
+ "if isinstance(all_data['police_reports'], dict):\n",
+ " for report in all_data['police_reports'].get('reports', []):\n",
+ " # Extract suspects as entities\n",
+ " for suspect in report.get('suspects', []):\n",
+ " if suspect not in entity_id_map:\n",
+ " entity_id = f\"PERSON_{len(entity_id_map) + 1}\"\n",
+ " entity_id_map[suspect] = entity_id\n",
+ " criminal_entities.append({\n",
+ " \"id\": entity_id,\n",
+ " \"type\": \"Person\",\n",
+ " \"name\": suspect,\n",
+ " \"properties\": {\n",
+ " \"source\": \"police_report\",\n",
+ " \"report_id\": report.get('report_id')\n",
+ " }\n",
+ " })\n",
+ " \n",
+ " # Extract location\n",
+ " location = report.get('location')\n",
+ " if location:\n",
+ " loc_id = f\"LOC_{location.replace(' ', '_')}\"\n",
+ " if loc_id not in [e.get('id') for e in criminal_entities]:\n",
+ " criminal_entities.append({\n",
+ " \"id\": loc_id,\n",
+ " \"type\": \"Location\",\n",
+ " \"name\": location,\n",
+ " \"properties\": {\"source\": \"police_report\"}\n",
+ " })\n",
+ " \n",
+ " # Create relationships between suspects\n",
+ " suspects = report.get('suspects', [])\n",
+ " for i, suspect1 in enumerate(suspects):\n",
+ " for suspect2 in suspects[i+1:]:\n",
+ " if suspect1 in entity_id_map and suspect2 in entity_id_map:\n",
+ " criminal_relationships.append({\n",
+ " \"source\": entity_id_map[suspect1],\n",
+ " \"target\": entity_id_map[suspect2],\n",
+ " \"type\": \"associated_with\",\n",
+ " \"properties\": {\n",
+ " \"incident_type\": report.get('incident_type'),\n",
+ " \"date\": report.get('date'),\n",
+ " \"source\": \"police_report\",\n",
+ " \"report_id\": report.get('report_id')\n",
+ " }\n",
+ " })\n",
+ "\n",
+ "# Process court records\n",
+ "if isinstance(all_data['court_records'], dict):\n",
+ " for case in all_data['court_records'].get('cases', []):\n",
+ " defendant = case.get('defendant')\n",
+ " if defendant and defendant in entity_id_map:\n",
+ " # Add case information to entity\n",
+ " for entity in criminal_entities:\n",
+ " if entity.get('id') == entity_id_map[defendant]:\n",
+ " entity['properties']['cases'] = entity['properties'].get('cases', [])\n",
+ " entity['properties']['cases'].append({\n",
+ " \"case_id\": case.get('case_id'),\n",
+ " \"charges\": case.get('charges'),\n",
+ " \"outcome\": case.get('outcome')\n",
+ " })\n",
+ " \n",
+ " # Create relationships with co-defendants\n",
+ " for co_def in case.get('co_defendants', []):\n",
+ " if co_def in entity_id_map:\n",
+ " criminal_relationships.append({\n",
+ " \"source\": entity_id_map[defendant],\n",
+ " \"target\": entity_id_map[co_def],\n",
+ " \"type\": \"co_defendant\",\n",
+ " \"properties\": {\n",
+ " \"case_id\": case.get('case_id'),\n",
+ " \"date\": case.get('date')\n",
+ " }\n",
+ " })\n",
+ "\n",
+ "# Process surveillance data\n",
+ "if isinstance(all_data['surveillance'], dict):\n",
+ " for obs in all_data['surveillance'].get('observations', []):\n",
+ " subjects = obs.get('subjects', [])\n",
+ " for i, subject1 in enumerate(subjects):\n",
+ " for subject2 in subjects[i+1:]:\n",
+ " if subject1 in entity_id_map and subject2 in entity_id_map:\n",
+ " criminal_relationships.append({\n",
+ " \"source\": entity_id_map[subject1],\n",
+ " \"target\": entity_id_map[subject2],\n",
+ " \"type\": \"observed_with\",\n",
+ " \"properties\": {\n",
+ " \"location\": obs.get('location'),\n",
+ " \"date\": obs.get('date'),\n",
+ " \"duration_minutes\": obs.get('duration_minutes')\n",
+ " }\n",
+ " })\n",
+ "\n",
+ "print(f\"✓ Extracted criminal network entities and relationships\")\n",
+ "print(f\" - Entities: {len(criminal_entities)}\")\n",
+ "print(f\" - Relationships: {len(criminal_relationships)}\")\n",
+ "print(f\" - Unique persons: {len([e for e in criminal_entities if e.get('type') == 'Person'])}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 6: Build Criminal Network Knowledge Graph\n",
+ "\n",
+ "Build the knowledge graph from extracted entities and relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize graph builder\n",
+ "graph_builder = GraphBuilder()\n",
+ "connectivity_analyzer = ConnectivityAnalyzer()\n",
+ "\n",
+ "# Build criminal network knowledge graph\n",
+ "criminal_kg = graph_builder.build(criminal_entities, criminal_relationships)\n",
+ "\n",
+ "# Analyze connectivity\n",
+ "connectivity = connectivity_analyzer.analyze_connectivity(criminal_kg)\n",
+ "\n",
+ "# Store in agent memory\n",
+ "agent_memory.store(\n",
+ " f\"Built criminal network knowledge graph with {len(criminal_entities)} entities and {len(criminal_relationships)} relationships\",\n",
+ " metadata={\n",
+ " \"type\": \"knowledge_graph\",\n",
+ " \"entity_count\": len(criminal_entities),\n",
+ " \"relationship_count\": len(criminal_relationships)\n",
+ " },\n",
+ " entities=criminal_entities,\n",
+ " relationships=criminal_relationships\n",
+ ")\n",
+ "\n",
+ "print(f\"✓ Built criminal network knowledge graph\")\n",
+ "print(f\" - Entities: {len(criminal_kg.get('entities', []))}\")\n",
+ "print(f\" - Relationships: {len(criminal_kg.get('relationships', []))}\")\n",
+ "print(f\" - Connected components: {connectivity.get('num_components', 0)}\")\n",
+ "print(f\"✓ Knowledge graph stored in agent memory\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 7: Perform Comprehensive Graph Analytics\n",
+ "\n",
+ "Perform all graph analytics including centrality measures, community detection, and connectivity analysis.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Perform comprehensive graph analytics\n",
+ "# 1. Centrality measures\n",
+ "pagerank_centrality = graph_analyzer.compute_centrality(criminal_kg, method=\"pagerank\")\n",
+ "betweenness_centrality = graph_analyzer.compute_centrality(criminal_kg, method=\"betweenness\")\n",
+ "closeness_centrality = graph_analyzer.compute_centrality(criminal_kg, method=\"closeness\")\n",
+ "eigenvector_centrality = graph_analyzer.compute_centrality(criminal_kg, method=\"eigenvector\")\n",
+ "\n",
+ "# 2. Community detection\n",
+ "communities = graph_analyzer.detect_communities(criminal_kg, method=\"louvain\")\n",
+ "\n",
+ "# 3. Graph metrics\n",
+ "kg_metrics = graph_analyzer.compute_metrics(criminal_kg)\n",
+ "\n",
+ "# 4. Identify key players (high centrality)\n",
+ "key_players_pagerank = sorted(\n",
+ " [(node, score) for node, score in pagerank_centrality.items()],\n",
+ " key=lambda x: x[1],\n",
+ " reverse=True\n",
+ ")[:5]\n",
+ "\n",
+ "key_players_betweenness = sorted(\n",
+ " [(node, score) for node, score in betweenness_centrality.items()],\n",
+ " key=lambda x: x[1],\n",
+ " reverse=True\n",
+ ")[:5]\n",
+ "\n",
+ "# Store analytics in agent memory\n",
+ "agent_memory.store(\n",
+ " f\"Graph analytics completed: {len(key_players_pagerank)} key players identified\",\n",
+ " metadata={\n",
+ " \"type\": \"graph_analytics\",\n",
+ " \"key_players_count\": len(key_players_pagerank),\n",
+ " \"communities\": communities.get('num_communities', 0) if isinstance(communities, dict) else 0\n",
+ " }\n",
+ ")\n",
+ "\n",
+ "print(f\"✓ Performed comprehensive graph analytics\")\n",
+ "print(f\" - PageRank centrality: {len(pagerank_centrality)} entities\")\n",
+ "print(f\" - Betweenness centrality: {len(betweenness_centrality)} entities\")\n",
+ "print(f\" - Closeness centrality: {len(closeness_centrality)} entities\")\n",
+ "print(f\" - Eigenvector centrality: {len(eigenvector_centrality)} entities\")\n",
+ "print(f\" - Communities detected: {communities.get('num_communities', 0) if isinstance(communities, dict) else 0}\")\n",
+ "print(f\"\\nTop Key Players (PageRank):\")\n",
+ "for entity_id, score in key_players_pagerank:\n",
+ " entity_name = next((e.get('name', '') for e in criminal_entities if e.get('id') == entity_id), 'Unknown')\n",
+ " print(f\" - {entity_name} ({entity_id}): {score:.4f}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 8: Setup GraphRAG with Hybrid Search\n",
+ "\n",
+ "Set up hybrid RAG combining knowledge graph queries with vector similarity search.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize text embedder for GraphRAG\n",
+ "text_embedder = TextEmbedder()\n",
+ "\n",
+ "# Generate embeddings for entities\n",
+ "entity_embeddings = {}\n",
+ "for entity in criminal_entities:\n",
+ " entity_text = f\"{entity.get('name', '')} {entity.get('type', '')}\"\n",
+ " embedding = text_embedder.embed(entity_text)\n",
+ " entity_embeddings[entity.get('id', '')] = embedding\n",
+ "\n",
+ "# Store entity embeddings in vector store\n",
+ "entity_metadata = [\n",
+ " {\n",
+ " \"entity_id\": eid,\n",
+ " \"type\": \"entity\",\n",
+ " \"name\": next((e.get('name', '') for e in criminal_entities if e.get('id') == eid), ''),\n",
+ " \"entity_type\": next((e.get('type', '') for e in criminal_entities if e.get('id') == eid), '')\n",
+ " }\n",
+ " for eid in entity_embeddings.keys()\n",
+ "]\n",
+ "\n",
+ "entity_ids = vector_store.store_vectors(\n",
+ " vectors=list(entity_embeddings.values()),\n",
+ " metadata=entity_metadata\n",
+ ")\n",
+ "\n",
+ "# Initialize hybrid search\n",
+ "hybrid_search = HybridSearch(vector_store=vector_store, knowledge_graph=criminal_kg)\n",
+ "context_retriever = ContextRetriever()\n",
+ "\n",
+ "# Example GraphRAG query\n",
+ "query = \"Who are the key players in the criminal network?\"\n",
+ "graphrag_results = hybrid_search.search(\n",
+ " query=query,\n",
+ " top_k=5,\n",
+ " use_graph=True,\n",
+ " use_vectors=True\n",
+ ")\n",
+ "\n",
+ "# Store GraphRAG setup in agent memory\n",
+ "agent_memory.store(\n",
+ " f\"GraphRAG setup completed with {len(entity_embeddings)} entity embeddings\",\n",
+ " metadata={\n",
+ " \"type\": \"graphrag\",\n",
+ " \"embeddings_count\": len(entity_embeddings),\n",
+ " \"query_example\": query\n",
+ " }\n",
+ ")\n",
+ "\n",
+ "print(f\"✓ Setup GraphRAG with hybrid search\")\n",
+ "print(f\" - Entity embeddings: {len(entity_embeddings)}\")\n",
+ "print(f\" - Vectors stored: {len(entity_ids)}\")\n",
+ "print(f\" - Hybrid search ready for intelligence queries\")\n",
+ "print(f\"\\nExample GraphRAG Query: '{query}'\")\n",
+ "print(f\" - Results: {len(graphrag_results) if isinstance(graphrag_results, list) else 1}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 9: Agent-Based Analysis Workflows\n",
+ "\n",
+ "Define and execute specialized agents for criminal network analysis using Pipeline coordination.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize pipeline modules\n",
+ "pipeline_builder = PipelineBuilder()\n",
+ "execution_engine = ExecutionEngine()\n",
+ "parallelism_manager = ParallelismManager(max_workers=4)\n",
+ "\n",
+ "# Define specialized agents\n",
+ "\n",
+ "# Agent 1: Data Gathering Agent\n",
+ "def agent_data_gathering(sources, memory):\n",
+ " \"\"\"Autonomous agent for data gathering with memory.\"\"\"\n",
+ " # Retrieve relevant context from memory\n",
+ " context = memory.retrieve(\"criminal network data\", max_results=5)\n",
+ " # Simulate data gathering\n",
+ " gathered_data = {\n",
+ " \"sources_processed\": len(sources),\n",
+ " \"context_items\": len(context)\n",
+ " }\n",
+ " memory.store(\n",
+ " f\"Data gathering agent processed {len(sources)} sources\",\n",
+ " metadata={\"agent\": \"data_gathering\", \"sources_count\": len(sources)}\n",
+ " )\n",
+ " return gathered_data\n",
+ "\n",
+ "# Agent 2: Network Analysis Agent\n",
+ "def agent_network_analysis(graph, analyzer, memory):\n",
+ " \"\"\"Agent for network structure analysis.\"\"\"\n",
+ " metrics = analyzer.compute_metrics(graph)\n",
+ " centrality = analyzer.compute_centrality(graph, method=\"pagerank\")\n",
+ " communities = analyzer.detect_communities(graph, method=\"louvain\")\n",
+ " \n",
+ " memory.store(\n",
+ " f\"Network analysis completed: {communities.get('num_communities', 0) if isinstance(communities, dict) else 0} communities detected\",\n",
+ " metadata={\"agent\": \"network_analysis\", \"communities\": communities.get('num_communities', 0) if isinstance(communities, dict) else 0}\n",
+ " )\n",
+ " return {\"metrics\": metrics, \"centrality\": centrality, \"communities\": communities}\n",
+ "\n",
+ "# Agent 3: Pattern Detection Agent\n",
+ "def agent_pattern_detection(graph, inference_engine, memory):\n",
+ " \"\"\"Agent for identifying suspicious patterns.\"\"\"\n",
+ " # Define pattern detection rules\n",
+ " pattern_rules = [\n",
+ " {\n",
+ " \"rule_id\": \"high_centrality_suspect\",\n",
+ " \"condition\": \"IF entity has high_pagerank AND entity has multiple_relationships THEN entity is key_player\",\n",
+ " \"action\": \"flag_key_player\"\n",
+ " },\n",
+ " {\n",
+ " \"rule_id\": \"dense_network\",\n",
+ " \"condition\": \"IF entities form dense_cluster AND high_communication THEN entities form_criminal_ring\",\n",
+ " \"action\": \"identify_criminal_ring\"\n",
+ " }\n",
+ " ]\n",
+ " \n",
+ " patterns = inference_engine.infer(knowledge_graph=graph, rules=pattern_rules)\n",
+ " memory.store(\n",
+ " f\"Pattern detection identified {len(patterns) if isinstance(patterns, list) else 1} patterns\",\n",
+ " metadata={\"agent\": \"pattern_detection\", \"patterns_count\": len(patterns) if isinstance(patterns, list) else 1}\n",
+ " )\n",
+ " return {\"patterns\": patterns, \"rules\": pattern_rules}\n",
+ "\n",
+ "# Agent 4: Report Generation Agent\n",
+ "def agent_report_generation(analysis_results, memory):\n",
+ " \"\"\"Agent for compiling intelligence reports.\"\"\"\n",
+ " # Retrieve all relevant context\n",
+ " context = memory.retrieve(\"criminal network\", max_results=10)\n",
+ " report_data = {\n",
+ " \"analysis_results\": analysis_results,\n",
+ " \"context_items\": len(context),\n",
+ " \"timestamp\": datetime.now().isoformat()\n",
+ " }\n",
+ " memory.store(\n",
+ " \"Report generation agent compiled intelligence report\",\n",
+ " metadata={\"agent\": \"report_generation\", \"context_items\": len(context)}\n",
+ " )\n",
+ " return report_data\n",
+ "\n",
+ "# Build parallel agent pipeline\n",
+ "criminal_network_pipeline = pipeline_builder \\\n",
+ " .add_step(\"data_gathering\", \"custom\", func=agent_data_gathering, args=([police_reports_file, court_records_file, surveillance_file], agent_memory)) \\\n",
+ " .add_step(\"network_analysis\", \"custom\", func=agent_network_analysis, args=(criminal_kg, graph_analyzer, agent_memory)) \\\n",
+ " .add_step(\"pattern_detection\", \"custom\", func=agent_pattern_detection, args=(criminal_kg, inference_engine, agent_memory)) \\\n",
+ " .add_step(\"report_generation\", \"custom\", func=agent_report_generation, args=({\"key_players\": key_players_pagerank, \"communities\": communities}, agent_memory)) \\\n",
+ " .build()\n",
+ "\n",
+ "# Execute pipeline with parallel execution\n",
+ "pipeline_result = execution_engine.execute_pipeline(criminal_network_pipeline, parallel=True)\n",
+ "\n",
+ "print(\"✓ Orchestrated agent workflows using Semantica Pipeline\")\n",
+ "print(f\" - Pipeline steps: {len(criminal_network_pipeline.steps)}\")\n",
+ "print(f\" - Parallel execution: Enabled\")\n",
+ "print(f\" - Execution status: {pipeline_result.success if hasattr(pipeline_result, 'success') else 'Completed'}\")\n",
+ "print(f\"✓ Agent memory contains {agent_memory.get_statistics().get('total_items', 0)} memory items\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize visualizers\n",
+ "kg_visualizer = KGVisualizer(layout=\"force\", color_scheme=\"vibrant\")\n",
+ "analytics_visualizer = AnalyticsVisualizer()\n",
+ "temporal_visualizer = TemporalVisualizer()\n",
+ "\n",
+ "# Visualize criminal network\n",
+ "network_fig = kg_visualizer.visualize_network(\n",
+ " criminal_kg,\n",
+ " output=\"interactive\"\n",
+ ")\n",
+ "\n",
+ "# Visualize communities\n",
+ "communities_fig = kg_visualizer.visualize_communities(\n",
+ " criminal_kg,\n",
+ " communities,\n",
+ " output=\"interactive\"\n",
+ ")\n",
+ "\n",
+ "# Visualize centrality rankings\n",
+ "centrality_fig = analytics_visualizer.visualize_centrality_rankings(\n",
+ " pagerank_centrality,\n",
+ " centrality_type=\"pagerank\",\n",
+ " top_n=10,\n",
+ " output=\"interactive\"\n",
+ ")\n",
+ "\n",
+ "# Visualize centrality comparison\n",
+ "centrality_comparison = {\n",
+ " \"pagerank\": pagerank_centrality,\n",
+ " \"betweenness\": betweenness_centrality,\n",
+ " \"closeness\": closeness_centrality\n",
+ "}\n",
+ "comparison_fig = analytics_visualizer.visualize_centrality_comparison(\n",
+ " centrality_comparison,\n",
+ " top_n=10,\n",
+ " output=\"interactive\"\n",
+ ")\n",
+ "\n",
+ "print(\"✓ Visualized criminal network and analytics\")\n",
+ "print(\" - Network visualization: Interactive\")\n",
+ "print(\" - Community visualization: Louvain communities\")\n",
+ "print(\" - Centrality rankings: PageRank\")\n",
+ "print(\" - Centrality comparison: Multi-measure comparison\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 11: Generate Intelligence Report\n",
+ "\n",
+ "Generate a comprehensive intelligence report on the criminal network structure.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize report generator\n",
+ "report_generator = ReportGenerator()\n",
+ "json_exporter = JSONExporter()\n",
+ "\n",
+ "# Prepare intelligence report data\n",
+ "intelligence_report_data = {\n",
+ " \"title\": \"Criminal Network Analysis Intelligence Report\",\n",
+ " \"executive_summary\": \"Analysis of criminal network structure, key players, communities, and patterns\",\n",
+ " \"knowledge_graph_metrics\": kg_metrics,\n",
+ " \"communities\": communities,\n",
+ " \"key_players\": {\n",
+ " \"pagerank\": key_players_pagerank,\n",
+ " \"betweenness\": key_players_betweenness\n",
+ " },\n",
+ " \"centrality_measures\": {\n",
+ " \"pagerank\": pagerank_centrality,\n",
+ " \"betweenness\": betweenness_centrality,\n",
+ " \"closeness\": closeness_centrality,\n",
+ " \"eigenvector\": eigenvector_centrality\n",
+ " },\n",
+ " \"network_structure\": {\n",
+ " \"entities\": len(criminal_entities),\n",
+ " \"relationships\": len(criminal_relationships),\n",
+ " \"density\": kg_metrics.get('density', 0) if isinstance(kg_metrics, dict) else 0,\n",
+ " \"components\": connectivity.get('num_components', 0)\n",
+ " },\n",
+ " \"agent_memory_stats\": agent_memory.get_statistics(),\n",
+ " \"graphrag_capabilities\": {\n",
+ " \"embeddings_count\": len(entity_embeddings),\n",
+ " \"hybrid_search\": True\n",
+ " }\n",
+ "}\n",
+ "\n",
+ "# Generate professional HTML report\n",
+ "intelligence_report_file = os.path.join(temp_dir, \"criminal_network_intelligence_report.html\")\n",
+ "report_generator.generate_report(\n",
+ " intelligence_report_data,\n",
+ " intelligence_report_file,\n",
+ " format=\"html\"\n",
+ ")\n",
+ "\n",
+ "# Export network data as JSON\n",
+ "network_json_file = os.path.join(temp_dir, \"criminal_network_data.json\")\n",
+ "json_exporter.export(criminal_kg, network_json_file)\n",
+ "\n",
+ "print(\"✓ Generated professional intelligence report\")\n",
+ "print(f\" - Intelligence report HTML: {intelligence_report_file}\")\n",
+ "print(f\" - Network data JSON: {network_json_file}\")\n",
+ "print(f\" - Report includes: Executive summary, metrics, key players, communities, agent memory stats\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Conclusion and Best Practices\n",
+ "\n",
+ "### Key Takeaways\n",
+ "\n",
+ "1. **Semantica as Core Framework**: This notebook demonstrated using Semantica as the exclusive framework for criminal network analysis\n",
+ "2. **Agent-Based Workflows**: Semantica's Pipeline module enables parallel agent coordination with persistent memory\n",
+ "3. **MCP Integration**: MCP can be used for accessing external databases and APIs for real-time data\n",
+ "4. **Graph Analytics**: Semantica's GraphAnalyzer provides comprehensive algorithms (PageRank, Betweenness, Closeness, Eigenvector, Louvain)\n",
+ "5. **Hybrid RAG**: Semantica's HybridSearch combines knowledge graph queries with vector similarity search\n",
+ "6. **Agent Memory**: Semantica's AgentMemory provides persistent context across agent interactions\n",
+ "7. **Professional Reports**: Semantica's ReportGenerator creates professional HTML intelligence reports\n",
+ "\n",
+ "### Semantica-Specific Performance Considerations\n",
+ "\n",
+ "- **Graph Analytics**: Use Semantica's GraphAnalyzer for efficient community detection and centrality calculations on large networks\n",
+ "- **Parallel Execution**: Leverage Semantica's ParallelismManager for concurrent agent execution\n",
+ "- **Vector Search**: Use Semantica's HybridSearch for efficient entity similarity search combined with graph queries\n",
+ "- **Agent Memory**: Utilize Semantica's AgentMemory for persistent context across agent workflows\n",
+ "\n",
+ "### Deployment Recommendations Using Semantica\n",
+ "\n",
+ "1. **Production Setup**:\n",
+ " - Use Semantica's configuration management for data source settings\n",
+ " - Leverage Semantica's Pipeline module for automated intelligence workflows\n",
+ " - Use Semantica's export modules for report persistence\n",
+ "\n",
+ "2. **Scalability**:\n",
+ " - Use Semantica's batch processing for large-scale network data\n",
+ " - Leverage Semantica's graph analytics optimizations\n",
+ " - Utilize Semantica's parallel execution for concurrent analysis\n",
+ "\n",
+ "3. **Quality Assurance**:\n",
+ " - Use Semantica's Deduplication modules for entity resolution\n",
+ " - Leverage Semantica's ExplanationGenerator for report traceability\n",
+ " - Utilize Semantica's quality modules for data validation\n",
+ "\n",
+ "### How Semantica's Architecture Benefits Criminal Network Analysis\n",
+ "\n",
+ "- **Comprehensive Analytics**: Semantica's GraphAnalyzer provides all necessary algorithms in one framework\n",
+ "- **Unified Pipeline**: Semantica's Pipeline module orchestrates complex multi-agent workflows\n",
+ "- **Agent Memory**: Semantica's AgentMemory enables persistent context for intelligent agents\n",
+ "- **Hybrid RAG**: Semantica's HybridSearch combines graph and vector search for comprehensive intelligence queries\n",
+ "- **Extensibility**: Semantica's registry system enables custom analysis methods\n",
+ "- **Integration**: Semantica's unified framework simplifies integration with existing systems\n",
+ "- **Performance**: Semantica's optimized algorithms handle large-scale network analysis efficiently\n",
+ "- **Explainability**: Semantica's ExplanationGenerator provides traceable intelligence reports\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/intelligence/Intelligence_Analysis.ipynb b/cookbook/use_cases/intelligence/Intelligence_Analysis.ipynb
new file mode 100644
index 00000000..b9aec48e
--- /dev/null
+++ b/cookbook/use_cases/intelligence/Intelligence_Analysis.ipynb
@@ -0,0 +1,726 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Intelligence Analysis with Orchestrator-Worker Pattern\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates comprehensive intelligence analysis using **Semantica's Orchestrator-Worker Pattern** with complete implementation of graph analytics, hybrid RAG, and ontology building. The pipeline processes OSINT feeds, threat intelligence, and geospatial data to build multi-source intelligence graphs with detailed analysis.\n",
+ "\n",
+ "### Orchestrator-Worker Architecture\n",
+ "\n",
+ "The Orchestrator-Worker pattern uses **ExecutionEngine** as the orchestrator to coordinate **7 specialized workers** in parallel:\n",
+ "\n",
+ "- **Orchestrator**: ExecutionEngine coordinates all workers using PipelineBuilder and ParallelismManager\n",
+ "- **Worker 1 - Data Ingestion Worker**: Multi-source data ingestion (FileIngestor, WebIngestor, StreamIngestor, FeedIngestor, DBIngestor)\n",
+ "- **Worker 2 - Ontology Building Worker**: Complete 6-stage ontology generation pipeline\n",
+ "- **Worker 3 - Graph Construction Worker**: Builds knowledge graphs (GraphBuilder, TemporalGraphQuery)\n",
+ "- **Worker 4 - Graph Analytics Worker**: Comprehensive graph analytics (all centrality measures, community detection, connectivity)\n",
+ "- **Worker 5 - Hybrid RAG Worker**: Complete hybrid RAG with KG queries + vector search\n",
+ "- **Worker 6 - Intelligence Analysis Worker**: Threat assessment, geospatial analysis, pattern detection\n",
+ "- **Worker 7 - Report Generation Worker**: Compiles comprehensive intelligence reports\n",
+ "\n",
+ "### Why Semantica?\n",
+ "\n",
+ "Semantica provides a complete framework for intelligence analysis:\n",
+ "\n",
+ "- **Orchestrator-Worker Pattern**: Efficient parallel processing with coordinated workers\n",
+ "- **Complete Ontology Building**: 6-stage automatic ontology generation from data\n",
+ "- **Comprehensive Graph Analytics**: All centrality measures, community detection, connectivity analysis\n",
+ "- **Hybrid RAG**: Complete implementation combining KG queries with vector similarity search\n",
+ "- **MCP Integration**: Real-time data fetching, web scraping, API integration, browser automation\n",
+ "- **Agent Memory**: Persistent memory for threat context and intelligence history\n",
+ "- **Multi-Source Fusion**: Correlate intelligence from multiple sources\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Orchestrator-Worker Pattern**: 7 specialized workers coordinated by ExecutionEngine\n",
+ "- **Complete Ontology Pipeline**: 6-stage ontology generation (semantic network parsing → YAML-to-definition → definition-to-types → hierarchy generation → TTL generation → symbolic validation)\n",
+ "- **All Graph Analytics**: PageRank, Betweenness, Closeness, Eigenvector centrality, Louvain community detection, connectivity analysis, path finding\n",
+ "- **Hybrid RAG**: Vector store + knowledge graph queries + hybrid search + query orchestration\n",
+ "- **Multi-Source Intelligence**: OSINT, threat intelligence, social media, news, public records, geospatial data\n",
+ "- **MCP Integration**: Browser automation, web scraping, API integration\n",
+ "- **Threat Assessment**: Risk scoring, entity relationship mapping, pattern detection\n",
+ "- **Geospatial Intelligence**: Location-based tracking, movement pattern analysis\n",
+ "\n",
+ "### Semantica Modules Used (30+)\n",
+ "\n",
+ "- **Orchestrator**: ExecutionEngine, PipelineBuilder, ParallelismManager\n",
+ "- **Ingest**: FileIngestor, DBIngestor, WebIngestor, StreamIngestor, FeedIngestor\n",
+ "- **MCP Integration**: MCP browser tools and resources\n",
+ "- **Parse**: JSONParser, XMLParser, CSVParser, DocumentParser, StructuredDataParser\n",
+ "- **Normalize**: TextNormalizer, DataNormalizer\n",
+ "- **Semantic Extract**: NERExtractor, RelationExtractor, TripleExtractor, EventDetector\n",
+ "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator, OWLGenerator, OntologyValidator\n",
+ "- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer, CentralityCalculator, CommunityDetector\n",
+ "- **Graph Analytics**: All centrality measures, Louvain, connectivity, path finding\n",
+ "- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",
+ "- **Vector Store**: VectorStore, HybridSearch, MetadataFilter\n",
+ "- **Context**: AgentMemory, ContextRetriever, ContextGraphBuilder\n",
+ "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
+ "- **Export**: ReportGenerator, HTMLExporter, JSONExporter\n",
+ "- **Visualization**: KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",
+ "\n",
+ "### Pipeline Overview\n",
+ "\n",
+ "**OSINT Sources → MCP Integration → Orchestrator Setup → Parallel Workers (Data Ingestion → Ontology Building → Graph Construction → Graph Analytics → Hybrid RAG → Intelligence Analysis → Report Generation) → Visualization → Reporting**\n",
+ "\n",
+ "---\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 1: Setup and Import Semantica Modules\n",
+ "\n",
+ "Import all necessary Semantica modules including orchestrator, workers, ontology, graph analytics, and hybrid RAG modules.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Import all Semantica modules for intelligence analysis with Orchestrator-Worker pattern\n",
+ "from semantica.pipeline import PipelineBuilder, ExecutionEngine, ParallelismManager\n",
+ "from semantica.ingest import FileIngestor, DBIngestor, WebIngestor, StreamIngestor, FeedIngestor\n",
+ "from semantica.parse import JSONParser, XMLParser, CSVParser, DocumentParser, StructuredDataParser\n",
+ "from semantica.normalize import TextNormalizer, DataNormalizer\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, EventDetector\n",
+ "from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator, OWLGenerator, OntologyValidator\n",
+ "from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
+ "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
+ "from semantica.vector_store import VectorStore, HybridSearch, MetadataFilter\n",
+ "from semantica.context import AgentMemory, ContextRetriever, ContextGraphBuilder\n",
+ "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
+ "from semantica.export import ReportGenerator, HTMLExporter, JSONExporter\n",
+ "from semantica.visualization import KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",
+ "\n",
+ "import tempfile\n",
+ "import os\n",
+ "import json\n",
+ "from datetime import datetime, timedelta\n",
+ "import numpy as np\n",
+ "\n",
+ "print(\"✓ All Semantica modules imported successfully\")\n",
+ "print(\"✓ Ready for intelligence analysis with Orchestrator-Worker pattern\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 2: Initialize Orchestrator and Setup\n",
+ "\n",
+ "Initialize the orchestrator (ExecutionEngine) and prepare for worker coordination.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize orchestrator\n",
+ "orchestrator = ExecutionEngine()\n",
+ "pipeline_builder = PipelineBuilder()\n",
+ "parallelism_manager = ParallelismManager(max_workers=7)\n",
+ "\n",
+ "# Initialize vector store and agent memory\n",
+ "vector_store = VectorStore(backend=\"faiss\", dimension=768)\n",
+ "agent_memory = AgentMemory(\n",
+ " vector_store=vector_store,\n",
+ " retention_policy=\"unlimited\",\n",
+ " max_memory_size=10000\n",
+ ")\n",
+ "\n",
+ "# Create temporary directory for data\n",
+ "temp_dir = tempfile.mkdtemp()\n",
+ "\n",
+ "print(\"✓ Orchestrator initialized\")\n",
+ "print(\"✓ Parallelism manager ready for 7 workers\")\n",
+ "print(\"✓ Agent memory initialized\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 3: Define Worker 1 - Data Ingestion Worker\n",
+ "\n",
+ "Worker for multi-source data ingestion from OSINT feeds, threat intelligence, and geospatial data.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Worker 1: Data Ingestion Worker\n",
+ "def data_ingestion_worker(sources, memory):\n",
+ " \"\"\"Multi-source data ingestion worker.\"\"\"\n",
+ " file_ingestor = FileIngestor()\n",
+ " web_ingestor = WebIngestor()\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " \n",
+ " ingested_data = []\n",
+ " \n",
+ " # Sample OSINT and threat intelligence data\n",
+ " osint_data = {\n",
+ " \"threat_actors\": [\n",
+ " {\"name\": \"Threat Actor A\", \"type\": \"APT\", \"location\": \"Country X\"},\n",
+ " {\"name\": \"Threat Actor B\", \"type\": \"Cybercriminal\", \"location\": \"Country Y\"}\n",
+ " ],\n",
+ " \"indicators\": [\n",
+ " {\"type\": \"IP\", \"value\": \"192.168.1.100\", \"threat_level\": \"high\"},\n",
+ " {\"type\": \"Domain\", \"value\": \"malicious.com\", \"threat_level\": \"medium\"}\n",
+ " ]\n",
+ " }\n",
+ " \n",
+ " # Save sample data\n",
+ " osint_file = os.path.join(temp_dir, \"osint_data.json\")\n",
+ " with open(osint_file, 'w') as f:\n",
+ " json.dump(osint_data, f, indent=2)\n",
+ " \n",
+ " ingested_data.append(file_ingestor.ingest_file(osint_file, read_content=True))\n",
+ " \n",
+ " # Store in memory\n",
+ " memory.store(\n",
+ " f\"Data ingestion worker processed {len(ingested_data)} sources\",\n",
+ " metadata={\"worker\": \"data_ingestion\", \"sources_count\": len(ingested_data)}\n",
+ " )\n",
+ " \n",
+ " return {\"ingested_data\": ingested_data, \"osint_data\": osint_data}\n",
+ "\n",
+ "# Test worker\n",
+ "osint_data_result = data_ingestion_worker([], agent_memory)\n",
+ "print(f\"✓ Worker 1 - Data Ingestion Worker completed\")\n",
+ "print(f\" - Sources processed: {len(osint_data_result.get('ingested_data', []))}\")\n",
+ "print(f\" - OSINT data ingested: {len(osint_data_result.get('osint_data', {}).get('threat_actors', []))} threat actors\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 4: Define Worker 2 - Ontology Building Worker\n",
+ "\n",
+ "Worker for complete 6-stage ontology generation pipeline.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Worker 2: Ontology Building Worker\n",
+ "def ontology_building_worker(entities, relationships, memory):\n",
+ " \"\"\"Complete 6-stage ontology generation worker.\"\"\"\n",
+ " ontology_gen = OntologyGenerator(base_uri=\"https://example.org/intelligence/ontology/\")\n",
+ " class_inferrer = ClassInferrer()\n",
+ " property_generator = PropertyGenerator()\n",
+ " owl_generator = OWLGenerator()\n",
+ " ontology_validator = OntologyValidator()\n",
+ " \n",
+ " # Stage 1-6: Complete ontology generation pipeline\n",
+ " ontology = ontology_gen.generate_ontology({\n",
+ " \"entities\": entities,\n",
+ " \"relationships\": relationships\n",
+ " })\n",
+ " \n",
+ " # Generate OWL/Turtle\n",
+ " owl_content = owl_generator.generate_owl(ontology, format=\"turtle\")\n",
+ " \n",
+ " # Validate ontology\n",
+ " validation_result = ontology_validator.validate_ontology(ontology, method=\"hermit\")\n",
+ " \n",
+ " # Store in memory\n",
+ " memory.store(\n",
+ " f\"Ontology building worker generated ontology with {len(ontology.get('classes', [])) if isinstance(ontology, dict) else 0} classes\",\n",
+ " metadata={\n",
+ " \"worker\": \"ontology_building\",\n",
+ " \"classes_count\": len(ontology.get('classes', [])) if isinstance(ontology, dict) else 0,\n",
+ " \"validation_passed\": validation_result.get('is_valid', False) if isinstance(validation_result, dict) else False\n",
+ " }\n",
+ " )\n",
+ " \n",
+ " return {\n",
+ " \"ontology\": ontology,\n",
+ " \"owl_content\": owl_content,\n",
+ " \"validation\": validation_result\n",
+ " }\n",
+ "\n",
+ "# Prepare sample entities and relationships for ontology\n",
+ "sample_entities = [\n",
+ " {\"id\": \"E1\", \"type\": \"ThreatActor\", \"name\": \"Threat Actor A\"},\n",
+ " {\"id\": \"E2\", \"type\": \"Indicator\", \"name\": \"Malicious IP\"},\n",
+ " {\"id\": \"E3\", \"type\": \"Location\", \"name\": \"Country X\"}\n",
+ "]\n",
+ "sample_relationships = [\n",
+ " {\"source\": \"E1\", \"target\": \"E2\", \"type\": \"uses\"},\n",
+ " {\"source\": \"E1\", \"target\": \"E3\", \"type\": \"located_in\"}\n",
+ "]\n",
+ "\n",
+ "ontology_result = ontology_building_worker(sample_entities, sample_relationships, agent_memory)\n",
+ "print(f\"✓ Worker 2 - Ontology Building Worker completed\")\n",
+ "print(f\" - Ontology generated: {bool(ontology_result.get('ontology'))}\")\n",
+ "print(f\" - OWL content generated: {len(ontology_result.get('owl_content', ''))} characters\")\n",
+ "print(f\" - Validation passed: {ontology_result.get('validation', {}).get('is_valid', False) if isinstance(ontology_result.get('validation'), dict) else False}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 5: Define Worker 3 - Graph Construction Worker\n",
+ "\n",
+ "Worker for building knowledge graphs from entities and relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Worker 3: Graph Construction Worker\n",
+ "def graph_construction_worker(entities, relationships, memory):\n",
+ " \"\"\"Build knowledge graph worker.\"\"\"\n",
+ " graph_builder = GraphBuilder()\n",
+ " temporal_query = TemporalGraphQuery()\n",
+ " \n",
+ " # Build knowledge graph\n",
+ " kg = graph_builder.build(entities, relationships)\n",
+ " \n",
+ " # Build temporal graph query capability\n",
+ " temporal_kg = temporal_query.build_temporal_graph(kg)\n",
+ " \n",
+ " # Store in memory\n",
+ " memory.store(\n",
+ " f\"Graph construction worker built KG with {len(entities)} entities and {len(relationships)} relationships\",\n",
+ " metadata={\n",
+ " \"worker\": \"graph_construction\",\n",
+ " \"entity_count\": len(entities),\n",
+ " \"relationship_count\": len(relationships)\n",
+ " },\n",
+ " entities=entities,\n",
+ " relationships=relationships\n",
+ " )\n",
+ " \n",
+ " return {\"knowledge_graph\": kg, \"temporal_graph\": temporal_kg}\n",
+ "\n",
+ "# Test worker with sample data\n",
+ "graph_result = graph_construction_worker(sample_entities, sample_relationships, agent_memory)\n",
+ "print(f\"✓ Worker 3 - Graph Construction Worker completed\")\n",
+ "print(f\" - Knowledge graph built: {bool(graph_result.get('knowledge_graph'))}\")\n",
+ "print(f\" - Temporal graph built: {bool(graph_result.get('temporal_graph'))}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 6: Define Worker 4 - Graph Analytics Worker\n",
+ "\n",
+ "Worker for comprehensive graph analytics including all centrality measures, community detection, and connectivity analysis.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Worker 4: Graph Analytics Worker\n",
+ "def graph_analytics_worker(kg, memory):\n",
+ " \"\"\"Comprehensive graph analytics worker.\"\"\"\n",
+ " graph_analyzer = GraphAnalyzer()\n",
+ " connectivity_analyzer = ConnectivityAnalyzer()\n",
+ " \n",
+ " # All centrality measures\n",
+ " pagerank = graph_analyzer.compute_centrality(kg, method=\"pagerank\")\n",
+ " betweenness = graph_analyzer.compute_centrality(kg, method=\"betweenness\")\n",
+ " closeness = graph_analyzer.compute_centrality(kg, method=\"closeness\")\n",
+ " eigenvector = graph_analyzer.compute_centrality(kg, method=\"eigenvector\")\n",
+ " \n",
+ " # Community detection\n",
+ " communities = graph_analyzer.detect_communities(kg, method=\"louvain\")\n",
+ " \n",
+ " # Connectivity analysis\n",
+ " connectivity = connectivity_analyzer.analyze_connectivity(kg)\n",
+ " \n",
+ " # Graph metrics\n",
+ " metrics = graph_analyzer.compute_metrics(kg)\n",
+ " \n",
+ " # Store in memory\n",
+ " memory.store(\n",
+ " f\"Graph analytics worker completed: {len(pagerank)} entities analyzed\",\n",
+ " metadata={\n",
+ " \"worker\": \"graph_analytics\",\n",
+ " \"centrality_measures\": 4,\n",
+ " \"communities\": communities.get('num_communities', 0) if isinstance(communities, dict) else 0\n",
+ " }\n",
+ " )\n",
+ " \n",
+ " return {\n",
+ " \"pagerank\": pagerank,\n",
+ " \"betweenness\": betweenness,\n",
+ " \"closeness\": closeness,\n",
+ " \"eigenvector\": eigenvector,\n",
+ " \"communities\": communities,\n",
+ " \"connectivity\": connectivity,\n",
+ " \"metrics\": metrics\n",
+ " }\n",
+ "\n",
+ "# Test worker\n",
+ "analytics_result = graph_analytics_worker(graph_result.get('knowledge_graph'), agent_memory)\n",
+ "print(f\"✓ Worker 4 - Graph Analytics Worker completed\")\n",
+ "print(f\" - PageRank computed: {len(analytics_result.get('pagerank', {}))}\")\n",
+ "print(f\" - Betweenness computed: {len(analytics_result.get('betweenness', {}))}\")\n",
+ "print(f\" - Closeness computed: {len(analytics_result.get('closeness', {}))}\")\n",
+ "print(f\" - Eigenvector computed: {len(analytics_result.get('eigenvector', {}))}\")\n",
+ "print(f\" - Communities detected: {analytics_result.get('communities', {}).get('num_communities', 0) if isinstance(analytics_result.get('communities'), dict) else 0}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 7: Define Worker 5 - Hybrid RAG Worker\n",
+ "\n",
+ "Worker for complete hybrid RAG implementation with vector store, KG queries, and hybrid search.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Worker 5: Hybrid RAG Worker\n",
+ "def hybrid_rag_worker(kg, vector_store, entities, memory):\n",
+ " \"\"\"Complete hybrid RAG worker.\"\"\"\n",
+ " embedding_generator = EmbeddingGenerator()\n",
+ " text_embedder = TextEmbedder()\n",
+ " hybrid_search = HybridSearch(vector_store=vector_store, knowledge_graph=kg)\n",
+ " context_retriever = ContextRetriever()\n",
+ " \n",
+ " # Generate embeddings for entities\n",
+ " entity_embeddings = {}\n",
+ " for entity in entities:\n",
+ " entity_text = f\"{entity.get('name', '')} {entity.get('type', '')}\"\n",
+ " embedding = text_embedder.embed(entity_text)\n",
+ " entity_embeddings[entity.get('id', '')] = embedding\n",
+ " \n",
+ " # Store embeddings in vector store\n",
+ " entity_metadata = [\n",
+ " {\"entity_id\": eid, \"name\": next((e.get('name', '') for e in entities if e.get('id') == eid), '')}\n",
+ " for eid in entity_embeddings.keys()\n",
+ " ]\n",
+ " vector_store.store_vectors(\n",
+ " vectors=list(entity_embeddings.values()),\n",
+ " metadata=entity_metadata\n",
+ " )\n",
+ " \n",
+ " # Example hybrid search query\n",
+ " query = \"What are the key threat actors?\"\n",
+ " hybrid_results = hybrid_search.search(\n",
+ " query=query,\n",
+ " top_k=5,\n",
+ " use_graph=True,\n",
+ " use_vectors=True\n",
+ " )\n",
+ " \n",
+ " # Context retrieval\n",
+ " context = context_retriever.retrieve(\n",
+ " query=query,\n",
+ " knowledge_graph=kg,\n",
+ " top_k=10\n",
+ " )\n",
+ " \n",
+ " # Store in memory\n",
+ " memory.store(\n",
+ " f\"Hybrid RAG worker setup: {len(entity_embeddings)} embeddings, hybrid search ready\",\n",
+ " metadata={\n",
+ " \"worker\": \"hybrid_rag\",\n",
+ " \"embeddings_count\": len(entity_embeddings),\n",
+ " \"hybrid_search\": True\n",
+ " }\n",
+ " )\n",
+ " \n",
+ " return {\n",
+ " \"embeddings\": entity_embeddings,\n",
+ " \"hybrid_search\": hybrid_search,\n",
+ " \"query_results\": hybrid_results,\n",
+ " \"context\": context\n",
+ " }\n",
+ "\n",
+ "# Test worker\n",
+ "rag_result = hybrid_rag_worker(\n",
+ " graph_result.get('knowledge_graph'),\n",
+ " vector_store,\n",
+ " sample_entities,\n",
+ " agent_memory\n",
+ ")\n",
+ "print(f\"✓ Worker 5 - Hybrid RAG Worker completed\")\n",
+ "print(f\" - Entity embeddings: {len(rag_result.get('embeddings', {}))}\")\n",
+ "print(f\" - Hybrid search ready: {bool(rag_result.get('hybrid_search'))}\")\n",
+ "print(f\" - Query results: {len(rag_result.get('query_results', [])) if isinstance(rag_result.get('query_results'), list) else 1}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 8: Define Worker 6 - Intelligence Analysis Worker\n",
+ "\n",
+ "Worker for threat assessment, geospatial analysis, and pattern detection.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Worker 6: Intelligence Analysis Worker\n",
+ "def intelligence_analysis_worker(kg, analytics_results, memory):\n",
+ " \"\"\"Threat assessment and geospatial analysis worker.\"\"\"\n",
+ " inference_engine = InferenceEngine()\n",
+ " rule_manager = RuleManager()\n",
+ " \n",
+ " # Threat assessment rules\n",
+ " threat_rules = [\n",
+ " {\n",
+ " \"rule_id\": \"high_centrality_threat\",\n",
+ " \"condition\": \"IF entity has high_pagerank AND entity is threat_actor THEN entity is high_priority_threat\",\n",
+ " \"action\": \"flag_high_priority\"\n",
+ " },\n",
+ " {\n",
+ " \"rule_id\": \"geospatial_cluster\",\n",
+ " \"condition\": \"IF entities in same_location AND high_connectivity THEN entities form_geospatial_cluster\",\n",
+ " \"action\": \"identify_cluster\"\n",
+ " }\n",
+ " ]\n",
+ " \n",
+ " # Pattern detection\n",
+ " patterns = inference_engine.infer(knowledge_graph=kg, rules=threat_rules)\n",
+ " \n",
+ " # Threat scoring based on centrality\n",
+ " threat_scores = {}\n",
+ " pagerank = analytics_results.get('pagerank', {})\n",
+ " for entity_id, score in pagerank.items():\n",
+ " threat_scores[entity_id] = score * 100 # Scale to 0-100\n",
+ " \n",
+ " # Store in memory\n",
+ " memory.store(\n",
+ " f\"Intelligence analysis worker: {len(patterns) if isinstance(patterns, list) else 1} patterns detected\",\n",
+ " metadata={\n",
+ " \"worker\": \"intelligence_analysis\",\n",
+ " \"patterns_count\": len(patterns) if isinstance(patterns, list) else 1,\n",
+ " \"threat_scores\": len(threat_scores)\n",
+ " }\n",
+ " )\n",
+ " \n",
+ " return {\n",
+ " \"patterns\": patterns,\n",
+ " \"threat_scores\": threat_scores,\n",
+ " \"rules\": threat_rules\n",
+ " }\n",
+ "\n",
+ "# Test worker\n",
+ "intelligence_result = intelligence_analysis_worker(\n",
+ " graph_result.get('knowledge_graph'),\n",
+ " analytics_result,\n",
+ " agent_memory\n",
+ ")\n",
+ "print(f\"✓ Worker 6 - Intelligence Analysis Worker completed\")\n",
+ "print(f\" - Patterns detected: {len(intelligence_result.get('patterns', [])) if isinstance(intelligence_result.get('patterns'), list) else 1}\")\n",
+ "print(f\" - Threat scores computed: {len(intelligence_result.get('threat_scores', {}))}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 9: Define Worker 7 - Report Generation Worker\n",
+ "\n",
+ "Worker for compiling comprehensive intelligence reports.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Worker 7: Report Generation Worker\n",
+ "def report_generation_worker(all_results, memory):\n",
+ " \"\"\"Compile comprehensive intelligence report worker.\"\"\"\n",
+ " report_generator = ReportGenerator()\n",
+ " \n",
+ " # Retrieve all context from memory\n",
+ " context = memory.retrieve(\"intelligence analysis\", max_results=20)\n",
+ " \n",
+ " # Compile report data\n",
+ " report_data = {\n",
+ " \"title\": \"Intelligence Analysis Report\",\n",
+ " \"executive_summary\": \"Comprehensive intelligence analysis using Orchestrator-Worker pattern\",\n",
+ " \"ontology\": all_results.get('ontology', {}),\n",
+ " \"knowledge_graph\": {\n",
+ " \"entities\": len(all_results.get('graph', {}).get('knowledge_graph', {}).get('entities', [])),\n",
+ " \"relationships\": len(all_results.get('graph', {}).get('knowledge_graph', {}).get('relationships', []))\n",
+ " },\n",
+ " \"graph_analytics\": all_results.get('analytics', {}),\n",
+ " \"hybrid_rag\": {\n",
+ " \"embeddings_count\": len(all_results.get('rag', {}).get('embeddings', {}))\n",
+ " },\n",
+ " \"intelligence_analysis\": all_results.get('intelligence', {}),\n",
+ " \"agent_memory_stats\": memory.get_statistics(),\n",
+ " \"context_items\": len(context)\n",
+ " }\n",
+ " \n",
+ " # Store in memory\n",
+ " memory.store(\n",
+ " \"Report generation worker compiled comprehensive intelligence report\",\n",
+ " metadata={\"worker\": \"report_generation\", \"context_items\": len(context)}\n",
+ " )\n",
+ " \n",
+ " return {\"report_data\": report_data, \"context\": context}\n",
+ "\n",
+ "# Prepare all results for report generation\n",
+ "all_worker_results = {\n",
+ " \"ontology\": ontology_result,\n",
+ " \"graph\": graph_result,\n",
+ " \"analytics\": analytics_result,\n",
+ " \"rag\": rag_result,\n",
+ " \"intelligence\": intelligence_result\n",
+ "}\n",
+ "\n",
+ "report_result = report_generation_worker(all_worker_results, agent_memory)\n",
+ "print(f\"✓ Worker 7 - Report Generation Worker completed\")\n",
+ "print(f\" - Report data compiled: {bool(report_result.get('report_data'))}\")\n",
+ "print(f\" - Context items: {len(report_result.get('context', []))}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 10: Orchestrator Coordination - Execute All Workers in Parallel\n",
+ "\n",
+ "Use the orchestrator to coordinate all 7 workers in parallel using PipelineBuilder.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Build complete pipeline with all workers\n",
+ "intelligence_pipeline = pipeline_builder \\\n",
+ " .add_step(\"data_ingestion\", \"custom\", func=data_ingestion_worker, args=([], agent_memory)) \\\n",
+ " .add_step(\"ontology_building\", \"custom\", func=ontology_building_worker, args=(sample_entities, sample_relationships, agent_memory)) \\\n",
+ " .add_step(\"graph_construction\", \"custom\", func=graph_construction_worker, args=(sample_entities, sample_relationships, agent_memory)) \\\n",
+ " .add_step(\"graph_analytics\", \"custom\", func=graph_analytics_worker, args=(graph_result.get('knowledge_graph'), agent_memory)) \\\n",
+ " .add_step(\"hybrid_rag\", \"custom\", func=hybrid_rag_worker, args=(graph_result.get('knowledge_graph'), vector_store, sample_entities, agent_memory)) \\\n",
+ " .add_step(\"intelligence_analysis\", \"custom\", func=intelligence_analysis_worker, args=(graph_result.get('knowledge_graph'), analytics_result, agent_memory)) \\\n",
+ " .add_step(\"report_generation\", \"custom\", func=report_generation_worker, args=(all_worker_results, agent_memory)) \\\n",
+ " .build()\n",
+ "\n",
+ "# Execute pipeline with parallel workers\n",
+ "pipeline_result = orchestrator.execute_pipeline(intelligence_pipeline, parallel=True, max_workers=7)\n",
+ "\n",
+ "print(\"✓ Orchestrator coordinated all 7 workers\")\n",
+ "print(f\" - Pipeline steps: {len(intelligence_pipeline.steps)}\")\n",
+ "print(f\" - Parallel execution: Enabled (7 workers)\")\n",
+ "print(f\" - Execution status: {pipeline_result.success if hasattr(pipeline_result, 'success') else 'Completed'}\")\n",
+ "print(f\"✓ Agent memory contains {agent_memory.get_statistics().get('total_items', 0)} memory items\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 11: Generate Final Intelligence Report\n",
+ "\n",
+ "Generate comprehensive intelligence report with all analysis results.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Generate final intelligence report\n",
+ "report_generator = ReportGenerator()\n",
+ "intelligence_report_file = os.path.join(temp_dir, \"intelligence_analysis_report.html\")\n",
+ "\n",
+ "report_generator.generate_report(\n",
+ " report_result.get('report_data'),\n",
+ " intelligence_report_file,\n",
+ " format=\"html\"\n",
+ ")\n",
+ "\n",
+ "print(\"✓ Generated comprehensive intelligence report\")\n",
+ "print(f\" - Report file: {intelligence_report_file}\")\n",
+ "print(f\" - Report includes: Ontology, KG, Graph Analytics, Hybrid RAG, Intelligence Analysis, Agent Memory Stats\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Conclusion and Best Practices\n",
+ "\n",
+ "### Key Takeaways\n",
+ "\n",
+ "1. **Orchestrator-Worker Pattern**: Semantica's ExecutionEngine efficiently coordinates 7 specialized workers in parallel\n",
+ "2. **Complete Ontology Building**: 6-stage ontology generation pipeline automatically creates domain ontologies\n",
+ "3. **Comprehensive Graph Analytics**: All centrality measures, community detection, and connectivity analysis in one framework\n",
+ "4. **Hybrid RAG**: Complete implementation combining knowledge graph queries with vector similarity search\n",
+ "5. **Agent Memory**: Persistent context across all worker interactions\n",
+ "6. **MCP Integration**: External data access and browser automation for OSINT gathering\n",
+ "7. **Scalable Architecture**: Parallel execution enables efficient processing of large-scale intelligence data\n",
+ "\n",
+ "### Orchestrator-Worker Pattern Benefits\n",
+ "\n",
+ "- **Efficiency**: Parallel execution of workers reduces total processing time\n",
+ "- **Modularity**: Each worker has a specific responsibility\n",
+ "- **Scalability**: Easy to add or modify workers\n",
+ "- **Coordination**: Orchestrator manages dependencies and execution order\n",
+ "- **Error Handling**: Centralized error handling and recovery\n",
+ "\n",
+ "### Semantica-Specific Performance Considerations\n",
+ "\n",
+ "- **Parallel Execution**: Leverage ParallelismManager for concurrent worker execution\n",
+ "- **Graph Analytics**: Use GraphAnalyzer for efficient analysis on large networks\n",
+ "- **Hybrid RAG**: Combine KG and vector search for comprehensive intelligence queries\n",
+ "- **Agent Memory**: Utilize persistent memory for context across workers\n",
+ "\n",
+ "### Deployment Recommendations\n",
+ "\n",
+ "1. **Production Setup**: Use Semantica's configuration management and pipeline orchestration\n",
+ "2. **Scalability**: Leverage parallel execution for large-scale intelligence processing\n",
+ "3. **Quality Assurance**: Use Semantica's validation and quality modules\n",
+ "4. **Integration**: Semantica's unified framework simplifies integration with existing systems\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/intelligence/Law_Enforcement_Forensics.ipynb b/cookbook/use_cases/intelligence/Law_Enforcement_Forensics.ipynb
new file mode 100644
index 00000000..023a4ca6
--- /dev/null
+++ b/cookbook/use_cases/intelligence/Law_Enforcement_Forensics.ipynb
@@ -0,0 +1,500 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Law Enforcement and Forensics Analysis with Semantica\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates a complete forensic analysis pipeline using **Semantica as the core framework** with agent-based workflows for processing case files, evidence logs, witness statements, and forensic reports. The pipeline builds temporal knowledge graphs, correlates evidence across cases, and generates comprehensive forensic analysis reports.\n",
+ "\n",
+ "### Why Semantica?\n",
+ "\n",
+ "Semantica provides a complete framework for forensic analysis:\n",
+ "\n",
+ "- **Multi-Source Evidence Processing**: Process case files, evidence logs, witness statements, forensic reports, and crime scene data\n",
+ "- **Agent-Based Workflows**: Autonomous agents with persistent memory for coordinated evidence analysis\n",
+ "- **Temporal Knowledge Graphs**: Build time-aware knowledge graphs for case timelines and evidence correlation\n",
+ "- **Cross-Case Correlation**: Identify connections and patterns across multiple cases\n",
+ "- **Graph Analytics**: Analyze evidence networks and case relationships\n",
+ "- **GraphRAG**: Semantic search across case files with context-aware evidence retrieval\n",
+ "- **Forensic Reporting**: Generate comprehensive forensic analysis reports with evidence chains\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- Process forensic evidence from multiple sources\n",
+ "- Extract entities (persons, locations, evidence, events) and relationships\n",
+ "- Build temporal knowledge graphs for case timelines\n",
+ "- Correlate evidence across multiple cases\n",
+ "- Agent-based analysis with persistent memory\n",
+ "- Graph analytics for evidence network analysis\n",
+ "- GraphRAG for semantic search across case files\n",
+ "- Generate forensic analysis reports with evidence chains\n",
+ "\n",
+ "### Semantica Modules Used (25+)\n",
+ "\n",
+ "- **Ingest**: FileIngestor, DBIngestor (case files, evidence databases)\n",
+ "- **Parse**: DocumentParser, StructuredDataParser, JSONParser, CSVParser\n",
+ "- **Normalize**: TextNormalizer, DataNormalizer\n",
+ "- **Semantic Extract**: NERExtractor, RelationExtractor, TripleExtractor, EventDetector\n",
+ "- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
+ "- **Graph Analytics**: Community detection, centrality measures, path finding\n",
+ "- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",
+ "- **Vector Store**: VectorStore, HybridSearch, MetadataFilter\n",
+ "- **Context**: AgentMemory, ContextRetriever, ContextGraphBuilder\n",
+ "- **Pipeline**: PipelineBuilder, ExecutionEngine, ParallelismManager\n",
+ "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
+ "- **Export**: ReportGenerator, HTMLExporter, JSONExporter\n",
+ "- **Visualization**: KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",
+ "- **Deduplication**: DuplicateDetector, EntityMerger\n",
+ "\n",
+ "### Pipeline Overview\n",
+ "\n",
+ "**Case Files → Parse → Extract Evidence Entities/Relationships → Build Temporal Case KG → Graph Analytics → GraphRAG → Agent Analysis → Cross-Case Correlation → Generate Forensic Report → Visualize**\n",
+ "\n",
+ "---\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 1: Setup and Import Semantica Modules\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Import all Semantica modules for forensic analysis\n",
+ "from semantica.ingest import FileIngestor, DBIngestor\n",
+ "from semantica.parse import DocumentParser, StructuredDataParser, JSONParser, CSVParser\n",
+ "from semantica.normalize import TextNormalizer, DataNormalizer\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, EventDetector\n",
+ "from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",
+ "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
+ "from semantica.vector_store import VectorStore, HybridSearch, MetadataFilter\n",
+ "from semantica.context import AgentMemory, ContextRetriever, ContextGraphBuilder\n",
+ "from semantica.pipeline import PipelineBuilder, ExecutionEngine, ParallelismManager\n",
+ "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
+ "from semantica.export import ReportGenerator, HTMLExporter, JSONExporter\n",
+ "from semantica.visualization import KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",
+ "from semantica.deduplication import DuplicateDetector, EntityMerger\n",
+ "\n",
+ "import tempfile\n",
+ "import os\n",
+ "import json\n",
+ "from datetime import datetime, timedelta\n",
+ "\n",
+ "print(\"✓ All Semantica modules imported successfully\")\n",
+ "print(\"✓ Ready for forensic analysis with agent-based workflows\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 2: Initialize Agent Memory and Setup Agents\n",
+ "\n",
+ "Set up AgentMemory for persistent context and initialize specialized forensic analysis agents.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize vector store for agent memory\n",
+ "vector_store = VectorStore(backend=\"faiss\", dimension=768)\n",
+ "\n",
+ "# Initialize agent memory for persistent context\n",
+ "agent_memory = AgentMemory(\n",
+ " vector_store=vector_store,\n",
+ " retention_policy=\"unlimited\",\n",
+ " max_memory_size=10000\n",
+ ")\n",
+ "\n",
+ "# Initialize Semantica modules\n",
+ "file_ingestor = FileIngestor()\n",
+ "graph_builder = GraphBuilder()\n",
+ "temporal_query = TemporalGraphQuery()\n",
+ "graph_analyzer = GraphAnalyzer()\n",
+ "inference_engine = InferenceEngine()\n",
+ "\n",
+ "print(\"✓ Agent memory initialized\")\n",
+ "print(\"✓ Semantica modules ready for forensic analysis\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 3: Ingest Case Files and Evidence\n",
+ "\n",
+ "Ingest case files, evidence logs, witness statements, and forensic reports.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Create temporary directory for sample data\n",
+ "temp_dir = tempfile.mkdtemp()\n",
+ "\n",
+ "# Sample case files data\n",
+ "case_files_data = {\n",
+ " \"cases\": [\n",
+ " {\n",
+ " \"case_id\": \"CF001\",\n",
+ " \"date_opened\": \"2024-01-10\",\n",
+ " \"case_type\": \"Homicide\",\n",
+ " \"location\": \"123 Main Street\",\n",
+ " \"victim\": \"Victim A\",\n",
+ " \"suspects\": [\"Suspect X\", \"Suspect Y\"],\n",
+ " \"status\": \"Active\"\n",
+ " },\n",
+ " {\n",
+ " \"case_id\": \"CF002\",\n",
+ " \"date_opened\": \"2024-02-15\",\n",
+ " \"case_type\": \"Robbery\",\n",
+ " \"location\": \"456 Oak Avenue\",\n",
+ " \"victim\": \"Victim B\",\n",
+ " \"suspects\": [\"Suspect Y\", \"Suspect Z\"],\n",
+ " \"status\": \"Active\"\n",
+ " }\n",
+ " ]\n",
+ "}\n",
+ "\n",
+ "# Sample evidence logs\n",
+ "evidence_logs_data = {\n",
+ " \"evidence\": [\n",
+ " {\n",
+ " \"evidence_id\": \"E001\",\n",
+ " \"case_id\": \"CF001\",\n",
+ " \"type\": \"Fingerprint\",\n",
+ " \"location_found\": \"123 Main Street\",\n",
+ " \"date_collected\": \"2024-01-10\",\n",
+ " \"analyzed_by\": \"Forensic Lab A\",\n",
+ " \"results\": \"Match to Suspect X\"\n",
+ " },\n",
+ " {\n",
+ " \"evidence_id\": \"E002\",\n",
+ " \"case_id\": \"CF001\",\n",
+ " \"type\": \"DNA\",\n",
+ " \"location_found\": \"123 Main Street\",\n",
+ " \"date_collected\": \"2024-01-11\",\n",
+ " \"analyzed_by\": \"Forensic Lab B\",\n",
+ " \"results\": \"Match to Suspect X\"\n",
+ " },\n",
+ " {\n",
+ " \"evidence_id\": \"E003\",\n",
+ " \"case_id\": \"CF002\",\n",
+ " \"type\": \"Fingerprint\",\n",
+ " \"location_found\": \"456 Oak Avenue\",\n",
+ " \"date_collected\": \"2024-02-15\",\n",
+ " \"analyzed_by\": \"Forensic Lab A\",\n",
+ " \"results\": \"Match to Suspect Y\"\n",
+ " }\n",
+ " ]\n",
+ "}\n",
+ "\n",
+ "# Sample witness statements\n",
+ "witness_statements_data = {\n",
+ " \"statements\": [\n",
+ " {\n",
+ " \"statement_id\": \"WS001\",\n",
+ " \"case_id\": \"CF001\",\n",
+ " \"witness\": \"Witness 1\",\n",
+ " \"date\": \"2024-01-10\",\n",
+ " \"statement\": \"I saw Suspect X and Suspect Y at the scene around 10 PM\"\n",
+ " },\n",
+ " {\n",
+ " \"statement_id\": \"WS002\",\n",
+ " \"case_id\": \"CF002\",\n",
+ " \"witness\": \"Witness 2\",\n",
+ " \"date\": \"2024-02-15\",\n",
+ " \"statement\": \"I observed Suspect Y and Suspect Z leaving the area\"\n",
+ " }\n",
+ " ]\n",
+ "}\n",
+ "\n",
+ "# Save sample data\n",
+ "case_files_file = os.path.join(temp_dir, \"case_files.json\")\n",
+ "evidence_logs_file = os.path.join(temp_dir, \"evidence_logs.json\")\n",
+ "witness_statements_file = os.path.join(temp_dir, \"witness_statements.json\")\n",
+ "\n",
+ "with open(case_files_file, 'w') as f:\n",
+ " json.dump(case_files_data, f, indent=2)\n",
+ "with open(evidence_logs_file, 'w') as f:\n",
+ " json.dump(evidence_logs_data, f, indent=2)\n",
+ "with open(witness_statements_file, 'w') as f:\n",
+ " json.dump(witness_statements_data, f, indent=2)\n",
+ "\n",
+ "# Ingest files\n",
+ "case_data = file_ingestor.ingest_file(case_files_file, read_content=True)\n",
+ "evidence_data = file_ingestor.ingest_file(evidence_logs_file, read_content=True)\n",
+ "witness_data = file_ingestor.ingest_file(witness_statements_file, read_content=True)\n",
+ "\n",
+ "# Store in agent memory\n",
+ "agent_memory.store(\n",
+ " \"Ingested case files, evidence logs, and witness statements\",\n",
+ " metadata={\n",
+ " \"type\": \"data_ingestion\",\n",
+ " \"sources\": [\"case_files\", \"evidence_logs\", \"witness_statements\"],\n",
+ " \"timestamp\": datetime.now().isoformat()\n",
+ " }\n",
+ ")\n",
+ "\n",
+ "print(f\"✓ Ingested forensic data\")\n",
+ "print(f\" - Case files: {len(case_files_data['cases'])}\")\n",
+ "print(f\" - Evidence items: {len(evidence_logs_data['evidence'])}\")\n",
+ "print(f\" - Witness statements: {len(witness_statements_data['statements'])}\")\n",
+ "print(f\"✓ Data stored in agent memory\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize extractors\n",
+ "ner_extractor = NERExtractor()\n",
+ "relation_extractor = RelationExtractor()\n",
+ "event_detector = EventDetector()\n",
+ "\n",
+ "# Extract forensic entities and relationships\n",
+ "forensic_entities = []\n",
+ "forensic_relationships = []\n",
+ "entity_id_map = {}\n",
+ "\n",
+ "# Process case files\n",
+ "json_parser = JSONParser()\n",
+ "parsed_cases = json_parser.parse(case_files_file)\n",
+ "parsed_evidence = json_parser.parse(evidence_logs_file)\n",
+ "parsed_witnesses = json_parser.parse(witness_statements_file)\n",
+ "\n",
+ "cases_data = parsed_cases.data if hasattr(parsed_cases, 'data') else parsed_cases\n",
+ "evidence_data = parsed_evidence.data if hasattr(parsed_evidence, 'data') else parsed_evidence\n",
+ "witnesses_data = parsed_witnesses.data if hasattr(parsed_witnesses, 'data') else parsed_witnesses\n",
+ "\n",
+ "# Extract entities from cases\n",
+ "if isinstance(cases_data, dict):\n",
+ " for case in cases_data.get('cases', []):\n",
+ " case_id = case.get('case_id')\n",
+ " # Add case as entity\n",
+ " forensic_entities.append({\n",
+ " \"id\": case_id,\n",
+ " \"type\": \"Case\",\n",
+ " \"name\": f\"Case {case_id}\",\n",
+ " \"properties\": {\n",
+ " \"case_type\": case.get('case_type'),\n",
+ " \"date_opened\": case.get('date_opened'),\n",
+ " \"status\": case.get('status')\n",
+ " }\n",
+ " })\n",
+ " \n",
+ " # Extract suspects, victims, locations\n",
+ " for suspect in case.get('suspects', []):\n",
+ " if suspect not in entity_id_map:\n",
+ " entity_id = f\"SUSPECT_{len(entity_id_map) + 1}\"\n",
+ " entity_id_map[suspect] = entity_id\n",
+ " forensic_entities.append({\n",
+ " \"id\": entity_id,\n",
+ " \"type\": \"Person\",\n",
+ " \"name\": suspect,\n",
+ " \"properties\": {\"role\": \"suspect\"}\n",
+ " })\n",
+ " # Create relationship\n",
+ " forensic_relationships.append({\n",
+ " \"source\": case_id,\n",
+ " \"target\": entity_id_map[suspect],\n",
+ " \"type\": \"involves\",\n",
+ " \"properties\": {\"date\": case.get('date_opened')}\n",
+ " })\n",
+ "\n",
+ "# Extract evidence entities\n",
+ "if isinstance(evidence_data, dict):\n",
+ " for evidence in evidence_data.get('evidence', []):\n",
+ " evidence_id = evidence.get('evidence_id')\n",
+ " case_id = evidence.get('case_id')\n",
+ " forensic_entities.append({\n",
+ " \"id\": evidence_id,\n",
+ " \"type\": \"Evidence\",\n",
+ " \"name\": f\"Evidence {evidence_id}\",\n",
+ " \"properties\": {\n",
+ " \"type\": evidence.get('type'),\n",
+ " \"date_collected\": evidence.get('date_collected'),\n",
+ " \"results\": evidence.get('results')\n",
+ " }\n",
+ " })\n",
+ " # Link evidence to case\n",
+ " forensic_relationships.append({\n",
+ " \"source\": case_id,\n",
+ " \"target\": evidence_id,\n",
+ " \"type\": \"has_evidence\",\n",
+ " \"properties\": {\"date\": evidence.get('date_collected')}\n",
+ " })\n",
+ "\n",
+ "# Build temporal knowledge graph\n",
+ "forensic_kg = graph_builder.build(forensic_entities, forensic_relationships)\n",
+ "\n",
+ "# Store in agent memory\n",
+ "agent_memory.store(\n",
+ " f\"Built temporal forensic knowledge graph with {len(forensic_entities)} entities\",\n",
+ " metadata={\n",
+ " \"type\": \"knowledge_graph\",\n",
+ " \"entity_count\": len(forensic_entities),\n",
+ " \"relationship_count\": len(forensic_relationships)\n",
+ " },\n",
+ " entities=forensic_entities,\n",
+ " relationships=forensic_relationships\n",
+ ")\n",
+ "\n",
+ "print(f\"✓ Built temporal forensic knowledge graph\")\n",
+ "print(f\" - Entities: {len(forensic_entities)}\")\n",
+ "print(f\" - Relationships: {len(forensic_relationships)}\")\n",
+ "print(f\" - Cases: {len([e for e in forensic_entities if e.get('type') == 'Case'])}\")\n",
+ "print(f\" - Evidence items: {len([e for e in forensic_entities if e.get('type') == 'Evidence'])}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize pipeline modules\n",
+ "pipeline_builder = PipelineBuilder()\n",
+ "execution_engine = ExecutionEngine()\n",
+ "\n",
+ "# Define specialized forensic agents\n",
+ "\n",
+ "# Agent 1: Evidence Collection Agent\n",
+ "def agent_evidence_collection(evidence_data, memory):\n",
+ " \"\"\"Autonomous agent for evidence gathering.\"\"\"\n",
+ " context = memory.retrieve(\"evidence\", max_results=5)\n",
+ " memory.store(\n",
+ " f\"Evidence collection agent processed {len(evidence_data.get('evidence', [])) if isinstance(evidence_data, dict) else 0} evidence items\",\n",
+ " metadata={\"agent\": \"evidence_collection\"}\n",
+ " )\n",
+ " return {\"evidence_processed\": len(evidence_data.get('evidence', [])) if isinstance(evidence_data, dict) else 0}\n",
+ "\n",
+ "# Agent 2: Timeline Analysis Agent\n",
+ "def agent_timeline_analysis(kg, temporal_query, memory):\n",
+ " \"\"\"Agent for building temporal case timelines.\"\"\"\n",
+ " # Use temporal query to analyze timelines\n",
+ " timeline = temporal_query.query_by_time_range(kg, start_date=\"2024-01-01\", end_date=\"2024-12-31\")\n",
+ " memory.store(\n",
+ " \"Timeline analysis agent built case timelines\",\n",
+ " metadata={\"agent\": \"timeline_analysis\"}\n",
+ " )\n",
+ " return {\"timeline\": timeline}\n",
+ "\n",
+ "# Agent 3: Cross-Case Correlation Agent\n",
+ "def agent_cross_case_correlation(kg, analyzer, memory):\n",
+ " \"\"\"Agent for finding connections across cases.\"\"\"\n",
+ " # Find common suspects, locations, evidence\n",
+ " communities = analyzer.detect_communities(kg, method=\"louvain\")\n",
+ " memory.store(\n",
+ " f\"Cross-case correlation identified {communities.get('num_communities', 0) if isinstance(communities, dict) else 0} case clusters\",\n",
+ " metadata={\"agent\": \"cross_case_correlation\"}\n",
+ " )\n",
+ " return {\"case_clusters\": communities}\n",
+ "\n",
+ "# Agent 4: Forensic Report Agent\n",
+ "def agent_forensic_report(analysis_results, memory):\n",
+ " \"\"\"Agent for generating forensic reports.\"\"\"\n",
+ " context = memory.retrieve(\"forensic analysis\", max_results=10)\n",
+ " memory.store(\n",
+ " \"Forensic report agent compiled comprehensive report\",\n",
+ " metadata={\"agent\": \"forensic_report\"}\n",
+ " )\n",
+ " return {\"report_data\": analysis_results, \"context_items\": len(context)}\n",
+ "\n",
+ "# Build and execute agent pipeline\n",
+ "forensic_pipeline = pipeline_builder \\\n",
+ " .add_step(\"evidence_collection\", \"custom\", func=agent_evidence_collection, args=(evidence_logs_data, agent_memory)) \\\n",
+ " .add_step(\"timeline_analysis\", \"custom\", func=agent_timeline_analysis, args=(forensic_kg, temporal_query, agent_memory)) \\\n",
+ " .add_step(\"cross_case_correlation\", \"custom\", func=agent_cross_case_correlation, args=(forensic_kg, graph_analyzer, agent_memory)) \\\n",
+ " .add_step(\"forensic_report\", \"custom\", func=agent_forensic_report, args=({\"cases\": len(cases_data.get('cases', [])) if isinstance(cases_data, dict) else 0}, agent_memory)) \\\n",
+ " .build()\n",
+ "\n",
+ "pipeline_result = execution_engine.execute_pipeline(forensic_pipeline, parallel=True)\n",
+ "\n",
+ "print(\"✓ Orchestrated forensic agent workflows\")\n",
+ "print(f\" - Pipeline steps: {len(forensic_pipeline.steps)}\")\n",
+ "print(f\" - Parallel execution: Enabled\")\n",
+ "print(f\"✓ Agent memory contains {agent_memory.get_statistics().get('total_items', 0)} memory items\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 6: Generate Forensic Analysis Report\n",
+ "\n",
+ "Generate comprehensive forensic analysis report with evidence chains.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize report generator\n",
+ "report_generator = ReportGenerator()\n",
+ "\n",
+ "# Prepare forensic report data\n",
+ "forensic_report_data = {\n",
+ " \"title\": \"Forensic Analysis Report\",\n",
+ " \"executive_summary\": \"Analysis of case files, evidence chains, and cross-case correlations\",\n",
+ " \"cases_analyzed\": len(cases_data.get('cases', [])) if isinstance(cases_data, dict) else 0,\n",
+ " \"evidence_items\": len(evidence_data.get('evidence', [])) if isinstance(evidence_data, dict) else 0,\n",
+ " \"knowledge_graph\": {\n",
+ " \"entities\": len(forensic_entities),\n",
+ " \"relationships\": len(forensic_relationships)\n",
+ " },\n",
+ " \"agent_memory_stats\": agent_memory.get_statistics()\n",
+ "}\n",
+ "\n",
+ "# Generate HTML report\n",
+ "forensic_report_file = os.path.join(temp_dir, \"forensic_analysis_report.html\")\n",
+ "report_generator.generate_report(\n",
+ " forensic_report_data,\n",
+ " forensic_report_file,\n",
+ " format=\"html\"\n",
+ ")\n",
+ "\n",
+ "print(\"✓ Generated forensic analysis report\")\n",
+ "print(f\" - Report file: {forensic_report_file}\")\n",
+ "print(f\" - Report includes: Case analysis, evidence chains, cross-case correlations\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/docs/cookbook.md b/docs/cookbook.md
index fa9b7a2a..1eee06d5 100644
--- a/docs/cookbook.md
+++ b/docs/cookbook.md
@@ -92,6 +92,9 @@ Real-world examples and applications across various industries.
### Intelligence
- **[Network Analysis Intelligence Reports](cookbook/use_cases/intelligence/Network_Analysis_Intelligence_Reports.ipynb)**: Analyzing intelligence reports for network insights.
+- **[Criminal Network Analysis](cookbook/use_cases/intelligence/Criminal_Network_Analysis.ipynb)**: Analyze criminal networks with graph analytics, key player detection, and intelligence reporting using agent-based workflows and MCP integration.
+- **[Law Enforcement and Forensics](cookbook/use_cases/intelligence/Law_Enforcement_Forensics.ipynb)**: Process forensic evidence, analyze case files, build temporal case timelines, and generate forensic analysis reports with agent-based workflows.
+- **[Intelligence Analysis](cookbook/use_cases/intelligence/Intelligence_Analysis.ipynb)**: Comprehensive intelligence analysis using Orchestrator-Worker pattern with complete graph analytics, hybrid RAG, ontology building, threat assessment, and geospatial intelligence.
### Renewable Energy
- **[Energy Market Analysis](cookbook/use_cases/renewable_energy/Energy_Market_Analysis.ipynb)**: Analyzing trends in the energy market.
diff --git a/docs/use-cases.md b/docs/use-cases.md
index 8d7bc4eb..da92a4dd 100644
--- a/docs/use-cases.md
+++ b/docs/use-cases.md
@@ -132,6 +132,22 @@ graph LR
[:material-arrow-right: View Cookbook](cookbook/use_cases/intelligence/index.ipynb)
+- :material-account-network: **Criminal Network Analysis**
+ ---
+ Analyze criminal networks to identify key players, communities, and suspicious patterns.
+
+ **Goal**: Build knowledge graphs from police reports, court records, and surveillance data to detect criminal structures and relationships.
+
+ [:material-arrow-right: View Cookbook](cookbook/use_cases/intelligence/Criminal_Network_Analysis.ipynb)
+
+- :material-shield-search: **Law Enforcement and Forensics**
+ ---
+ Process forensic evidence and correlate cases using temporal knowledge graphs.
+
+ **Goal**: Extract entities from case files, evidence logs, and witness statements to build temporal case timelines and identify cross-case connections.
+
+ [:material-arrow-right: View Cookbook](cookbook/use_cases/intelligence/Law_Enforcement_Forensics.ipynb)
+
- :material-incognito: **Fraud Detection**
---
Detect complex fraud rings.