# How to Use Semantica's CLI for Interacting with the Knowledge Graph: Commands and Implementation

> Learn to interact with Semantica's knowledge graph using its powerful CLI. Execute graph operations, run Cypher SPARQL queries, and export data directly from your terminal with the kg command.

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

---

**Semantica's command-line interface provides direct terminal access to knowledge graph operations through the `kg` command group, enabling graph construction, Cypher/SPARQL querying, statistical analysis, and multi-format exports without requiring Python code.**

The `semantica-agi/semantica` repository ships with a comprehensive CLI defined in [`semantica/cli.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/cli.py) that exposes the full knowledge graph pipeline to terminal users. This interface abstracts the underlying `Semantica` orchestrator and graph store implementations, allowing you to build, query, and manage knowledge graphs using simple terminal commands rather than programmatic APIs.

## Core CLI Architecture and Entry Points

The CLI entry point resides in the `main` function (lines 49-61 of [`semantica/cli.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/cli.py)), which parses global flags including `--config`, `--log-level`, `--json`, and `--quiet` before instantiating a **CLIContext** dataclass (lines 57-66). This context object carries runtime configuration and backend selections throughout the command lifecycle.

The framework employs **lazy loading** via `_get_framework` (lines 33-38) to defer heavy imports until explicitly needed. This optimization ensures that metadata commands execute instantly without initializing the full Semantica engine, while build and query operations trigger complete framework initialization only when required.

## Essential Knowledge Graph Commands

All knowledge graph operations route through the `kg` command group, which maps terminal inputs to the orchestrator's methods and graph store abstractions.

### Building the Knowledge Graph with `kg build`

The `kg build` subcommand triggers the complete ingestion pipeline through the `kg_build` function (around line 1310). This command delegates to `_run_build_command`, which eventually invokes `Semantica.build_knowledge_base` from [`semantica/core/orchestrator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/core/orchestrator.py).

You can ingest multiple data sources simultaneously:

```bash
semantica kg build --source ./contracts/ --source ./policies/

```

This executes the full extraction and graph-construction workflow, displaying progress bars unless you specify the `--quiet` flag.

### Querying the Graph with `kg query`

The `kg query` subcommand supports both **Cypher** and **SPARQL** query languages against the active graph store. Implemented in the `kg_query` function, it utilizes `_get_graph_store` (line 1174) to initialize the backend connection before forwarding queries to the store's `run_query` method.

Execute Cypher queries against Neo4j or FalkorDB backends:

```bash
semantica kg query "MATCH (p:Person)-[:WORKS_FOR]->(c:Company) RETURN p.name, c.name" \
    --lang cypher --limit 20

```

For RDF-compatible stores, use SPARQL with JSON output:

```bash
semantica kg query "SELECT ?s ?p ?o WHERE { ?s ?p ?o }" \
    --lang sparql --limit 10 --json

```

### Inspecting Graph State with `kg stats` and `kg list`

The `kg stats` command provides immediate visibility into graph dimensions by calling the graph store's `get_nodes` and `get_relationships` APIs, returning entity counts, relationship tallies, and active backend identification.

The `kg list` command enumerates configured graph store backends (Neo4j, FalkorDB, Memory) and tests connectivity using the same `_get_graph_store` helper, confirming network reachability and authentication status before operations commence.

### Exporting Data with `kg export`

The `kg export` subcommand serializes the knowledge graph to **RDF**, **OWL**, **Parquet**, or **Cypher** formats. This function constructs a knowledge dictionary via `graph.to_kg_dict()` before delegating to exporter classes defined in [`semantica/export.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/export.py).

Export to Turtle format:

```bash
semantica kg export --format turtle --output my_graph.ttl

```

This invokes `RDFExporter.export` under the hood, converting the internal graph representation to standard RDF triples.

## Internal Implementation Details

All KG operations rely on the `_get_graph_store` helper (lines 1174-1181) to resolve backend configurations from the YAML config file or CLI overrides. This abstraction returns a concrete **GraphStore** implementation that normalizes differences between Neo4j, FalkorDB, and in-memory storage, exposing uniform methods like `run_query` and `get_nodes` defined in [`semantica/graph_store.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/graph_store.py).

Error handling flows through `_run_with_error_handling` (lines 26-42), which catches exceptions and renders user-friendly **Rich** panels or machine-readable JSON when using the `--json` flag. Utility functions including `_ok`, `_warn`, and `_pprint` ensure consistent output formatting that respects `--quiet` and `--no-color` preferences.

## Practical CLI Workflows

Common operational patterns for the Semantica CLI include:

1. **Dry-run validation**: Test build configurations without writing data:
   
   ```bash
   semantica --dry-run kg build --source data/
   ```

2. **Multi-source ingestion**: Combine directories and files in a single build:
   
   ```bash
   semantica kg build --source ./data/ --source https://example.com/dataset.json
   ```

3. **Machine-readable querying**: Export query results for downstream processing:
   
   ```bash
   semantica kg query "MATCH (n) RETURN n LIMIT 5" --json > results.json
   ```

4. **Connectivity verification**: Confirm backend availability before operations:
   
   ```bash
   semantica kg list
   ```

## Summary

- The **CLI** in [`semantica/cli.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/cli.py) provides terminal access to all knowledge graph functions through the `kg` command group.
- **Lazy loading** via `_get_framework` ensures fast execution for metadata commands while deferring heavy imports.
- The **`kg build`** command orchestrates the full pipeline through `Semantica.build_knowledge_base` in [`semantica/core/orchestrator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/core/orchestrator.py).
- **`kg query`** supports both **Cypher** and **SPARQL** languages through the abstracted `_get_graph_store` interface.
- **Export functionality** in [`semantica/export.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/export.py) handles RDF, OWL, Parquet, and Cypher formats via `graph.to_kg_dict()`.
- Consistent error handling and output formatting are managed through `_run_with_error_handling` and helper utilities.

## Frequently Asked Questions

### How do I configure the graph database backend for the Semantica CLI?

The CLI reads backend configurations from the `graph_db` section of your configuration file (typically `~/.semantica/config.yaml`) or accepts overrides through command-line flags. The `_get_graph_store` helper (line 1174) resolves these settings to instantiate the appropriate concrete implementation, whether Neo4j, FalkorDB, or the in-memory store.

### Can I run SPARQL queries against any graph store backend?

SPARQL support depends on the configured backend's capabilities. While the CLI accepts `--lang sparql` in the `kg query` command, the query executes through the store's `run_query` method. Ensure your backend supports SPARQL before attempting these queries, as graph databases like Neo4j primarily optimize for Cypher.

### What file formats does the `kg export` command support?

The export command supports **RDF** (Turtle, XML), **OWL**, **Parquet**, and **Cypher** formats through delegations to [`semantica/export.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/export.py). The command first builds a knowledge dictionary via `graph.to_kg_dict()` before passing it to format-specific exporter classes like `RDFExporter`.

### How does the CLI handle errors and logging?

All commands wrap execution in `_run_with_error_handling` (lines 26-42), which captures exceptions and formats them as Rich panels for terminal users or JSON objects when using the `--json` flag. Global flags like `--log-level`, `--quiet`, and `--no-color` control verbosity and formatting throughout the application lifecycle.