# How to Use the Semantica CLI for Graph Exploration and Management: A Complete Guide

> Master the Semantica CLI for efficient knowledge graph exploration and management. Learn to build, query, analyze, and visualize your graphs with this comprehensive guide.

- Repository: [Semantica /semantica](https://github.com/semantica-agi/semantica)
- Tags: how-to-guide
- Published: 2026-08-14

---

**The Semantica CLI provides a Click-based command-line interface for building, querying, analyzing, and exploring knowledge graphs through sub-commands like `kg build`, `kg query`, `kg analyze`, and `semantica explorer`.**

The `semantica-agi/semantica` repository delivers a powerful Python knowledge-graph engine with a comprehensive CLI for graph exploration and management. Whether you're ingesting documents, running Cypher queries, or launching interactive visualizations, the CLI serves as your primary entry point. This guide covers every command, configuration option, and workflow based on the actual source code implementation.

## Semantica CLI Architecture and Entry Point

The CLI is defined in [`semantica/cli.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/cli.py) as a Click group that constructs a **CLIContext** object for each invocation. This context holds runtime configuration, logging settings, and flags like `--quiet` or `--json`, then passes them to sub-commands via `@click.pass_obj`.

Key architectural components include:

- **Configuration loading** – The `_load_config_data` function reads YAML/JSON config files and merges CLI flag overrides (`--log-level`, `--store`, `--vector-store`)
- **Graph store abstraction** – `_get_graph_store(cli_ctx)` instantiates concrete backends (memory, Neo4j, Amazon Neptune) through the common **GraphStore** API
- **Output formatting** – Helpers like `_jecho`, `_pprint`, and `_run_with_error_handling` ensure consistent JSON or rich-text output with user-friendly error cards

All commands ultimately delegate to the core **Orchestrator** class in [`semantica/core/orchestrator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/core/orchestrator.py), which coordinates ingestion, extraction, reasoning, and storage operations.

## Building and Managing Knowledge Graphs

### Create or Update a Graph with `kg build`

The `semantica kg build` command ingests documents, extracts entities, and populates your configured graph backend.

```bash
semantica kg build -s ./contracts/ -c my_build_config.yaml

```

This command:
1. Scans the source directory for supported file types
2. Invokes the **Orchestrator** to process each document
3. Runs named entity extraction and relationship detection
4. Stores results in the backend specified in your config

### Run Ad-Hoc Queries with `kg query`

Execute Cypher or SPARQL queries directly against your knowledge graph:

```bash
semantica kg query "MATCH (p:Person)-[r:WORKS_FOR]->(c:Company) RETURN p.name, c.name LIMIT 10"

```

The CLI calls `execute_query` from [`semantica/graph_store/graph_store.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/graph_store/graph_store.py) and returns results as Python lists/dictionaries, formatted for terminal display or JSON output with `--json`.

## Graph Analytics and Insights

### View Graph Statistics with `kg stats`

Quickly inspect high-level metrics about your graph structure:

```bash
semantica kg stats --format json

```

Internally, this instantiates the **GraphAnalyzer** class from [`semantica/kg/graph_analyzer.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/graph_analyzer.py) and calls `compute_metrics()`, which aggregates node counts, edge counts, density, and other global properties.

### Run Comprehensive Analytics with `kg analyze`

Perform multi-modal graph analysis with a single command:

```bash
semantica kg analyze --mode all

```

Available modes include:
- **centrality** – Identifies influential nodes using `CentralityCalculator`
- **community** – Detects clusters via `CommunityDetector`
- **connectivity** – Analyzes graph robustness with `ConnectivityAnalyzer`
- **all** – Runs complete pipeline and returns combined results

The `GraphAnalyzer.analyze_graph()` method orchestrates these components and returns a dictionary with keys `centrality`, `communities`, `connectivity`, and `metrics`.

## Path Finding and Graph Traversal

### Find Paths Between Entities with `kg find-path`

Discover relationships between specific nodes using multiple path types:

```bash
semantica kg find-path --from "Acme Corp" --to "John Doe" --type semantic

```

The **PathFinder** implementation in [`semantica/kg/path_finder.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/path_finder.py) supports:
- **shortest** – Minimum-hop paths
- **semantic** – Relationship-type weighted paths
- **causal** – Cause-effect chain detection

## Graph Maintenance and Enhancement

### Validate Graph Integrity with `kg validate`

Run automated integrity checks to identify orphaned nodes, dangling edges, and schema violations:

```bash
semantica kg validate

```

This invokes the **GraphValidator** class from [`semantica/kg/graph_validator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/graph_validator.py).

### Predict Missing Links with `kg predict`

Apply machine learning to suggest new relationships:

```bash
semantica kg predict

```

The **LinkPredictor** class in [`semantica/kg/link_predictor.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/link_predictor.py) trains on existing topology to score potential edges.

## Interactive Exploration and Development

### Launch the Visual Explorer

Start a web-based interactive graph visualization (requires optional dependency):

```bash
pip install semantica[explorer]
semantica explorer --graph my_graph.json

```

This launches a Vite-powered UI for exploring nodes, edges, and running ad-hoc queries through a point-and-click interface.

### Use the REPL for Rapid Prototyping

The `semantica shell` command starts an interactive session where you can omit the `semantica` prefix:

```bash
semantica shell
> kg stats
> kg query "MATCH (n) RETURN count(n) AS total"
> exit

```

The REPL parses each line, constructs a Click context, and executes sub-commands directly—ideal for iterative query development.

## Configuration and Environment Setup

Initialize a new project configuration with:

```bash
semantica init

```

This creates a template config file that [`semantica/core/config_manager.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/core/config_manager.py) validates against the **Config** dataclass schema. Key settings include:

- Graph backend selection (memory, Neo4j, Neptune)
- Vector store configuration for embeddings
- Logging levels and output formats

Override any setting at runtime:

```bash
semantica --config production.yaml --log-level DEBUG kg stats

```

## Typical CLI Workflow

Follow this sequence for production graph exploration and management:

1. **Initialize** – `semantica init` (one-time setup)
2. **Ingest** – `semantica kg build -s data/`
3. **Explore** – `semantica kg stats` and `semantica kg query "..."`
4. **Analyze** – `semantica kg analyze --mode all`
5. **Validate** – `semantica kg validate`
6. **Enhance** – `semantica kg predict`
7. **Visualize** – `semantica explorer`

All steps respect your configuration and support `--json` output for CI/CD integration.

## Summary

- **Entry point**: [`semantica/cli.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/cli.py) defines the root command and **CLIContext** passing
- **Graph construction**: `kg build` delegates to the **Orchestrator** for document ingestion and entity extraction
- **Query execution**: `kg query` calls `GraphStore.execute_query()` from [`semantica/graph_store/graph_store.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/graph_store/graph_store.py)
- **Analytics pipeline**: `kg analyze` orchestrates **GraphAnalyzer**, **CentralityCalculator**, **CommunityDetector**, and **ConnectivityAnalyzer**
- **Path algorithms**: `kg find-path` uses **PathFinder** for shortest, semantic, and causal routing
- **Maintenance tools**: `kg validate` and `kg predict` leverage **GraphValidator** and **LinkPredictor**
- **Interactive modes**: `semantica explorer` launches a web UI; `semantica shell` provides a REPL environment
- **Machine-readable output**: All commands support `--json` for automation and pipeline integration

## Frequently Asked Questions

### What graph backends does the Semantica CLI support?

The CLI supports in-memory stores for development, Neo4j for production deployments, and Amazon Neptune for cloud-native workloads. Configure your backend in the YAML/JSON config file or override with `--store` flags. The `_get_graph_store()` function in [`semantica/cli.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/cli.py) handles backend instantiation based on your configuration.

### How do I format CLI output for automated pipelines?

Add the `--json` flag to any command. The `_jecho` helper in [`semantica/cli.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/cli.py) ensures consistent JSON serialization of results, making it straightforward to parse output in shell scripts, CI systems, or data pipelines without rich-text formatting.

### Can I visualize my knowledge graph without writing code?

Yes. Install the optional explorer dependency with `pip install semantica[explorer]`, then run `semantica explorer`. This launches a Vite-powered web interface where you can browse nodes, inspect edges, and execute queries through a graphical interface—no Python coding required.