# How to Generate Explanations for Inferred Results in Semantica

> Learn how to generate explanations for inferred results in Semantica using the ExplanationGenerator class. Get structured explanations with reasoning paths and confidence metadata.

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

---

**Semantica generates human-readable explanations for inferred results through the `ExplanationGenerator` class, which converts `InferenceResult` objects into structured `Explanation` instances containing reasoning paths, natural-language text, and confidence metadata.**

The Semantica framework (semantica-agi/semantica) provides a declarative pipeline for transforming raw reasoning outputs into transparent audit trails. By leveraging the `ExplanationGenerator` subsystem, developers can generate detailed justifications for any inference with configurable verbosity levels ranging from simple summaries to verbose technical breakdowns.

## Understanding the ExplanationGenerator Architecture

The explanation pipeline is implemented in [`semantica/reasoning/explanation_generator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/reasoning/explanation_generator.py). The `ExplanationGenerator` class serves as the primary entry point, exposing the `generate_explanation` method that dispatches to type-specific helpers based on the result class (lines 30-38).

### Core Components

When processing an `InferenceResult`, the generator constructs three essential components:

- **A reasoning path** – A series of `ReasoningStep` objects describing each premise and any applied rules (lines 92-102)
- **Natural-language text** – Generated on-the-fly according to the configured detail level
- **Metadata** – Confidence scores and identifiers supporting downstream visualizers or audit logs

The internal `_explain_inference_result` method (lines 87-107) builds a `ReasoningPath` from the inference's premises, optionally adds a rule step, and delegates text generation to `_generate_natural_language`.

### Configuring Detail Levels

The `_generate_natural_language` method (lines 148-166) formats explanation strings based on the `detail_level` configuration parameter. Valid options include:

- **`simple`** – Concise justification
- **`detailed`** – Comprehensive reasoning breakdown  
- **`verbose`** – Technical details including internal identifiers

The final output is an `Explanation` dataclass (lines 122-136) containing all structural and textual components.

## Generating Explanations from Inference Results

To generate an explanation directly from a reasoning operation, instantiate `ExplanationGenerator` with your desired configuration and call `generate_explanation` with an `InferenceResult` object.

```python
from semantica.reasoning.explanation_generator import ExplanationGenerator
from semantica.reasoning.deductive_reasoner import InferenceResult

# Create an inference result from your reasoning operation

inference = InferenceResult(
    conclusion="Approve loan",
    premises=["Credit score > 700", "Income > $50k"],
    rule_used=None,
    confidence=0.92,
)

# Initialize generator with detail level

gen = ExplanationGenerator(config={"detail_level": "detailed"})
explanation = gen.generate_explanation(inference)

# Access the natural language description

print(explanation.natural_language)

# → "Given the premises: Credit score > 700, Income > $50k, we conclude: Approve loan."

# Access structured reasoning steps

print([step.description for step in explanation.reasoning_path.steps])

# → ["Premise: Credit score > 700", "Premise: Income > $50k"]

```

## Enriching Explanations with Vector Store Context

For decision-level explanations that incorporate similar historical decisions, the `VectorStore` class in [`semantica/vector_store/vector_store.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/vector_store/vector_store.py) provides the `explain_decision` method (lines 12-30). This wraps the standard reasoning-path logic while augmenting output with similarity-based context from the underlying vector backend.

```python
from semantica.vector_store import VectorStore

store = VectorStore(backend="faiss")  # Supports any configured backend

# ... populate the store with decision vectors ...

decision_id = "decision_42"
explanation = store.explain_decision(decision_id, include_paths=True)

print(explanation["scenario"])

# Check if similarity data is available (e.g., FAISS without direct-map)

print(explanation.get("similarity_unavailable", False))

# Access similar decisions for contextual comparison

print(explanation.get("similar_decisions", []))

```

If the backend cannot retrieve raw vectors (such as a FAISS index lacking a direct map), the system logs a warning and sets the `similarity_unavailable` flag to `True`, allowing graceful degradation. The public `explain` shortcut exposed in [`semantica/vector_store/decision_vector_methods.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/vector_store/decision_vector_methods.py) forwards to this implementation.

## Implementation Details in the Source Code

The explanation generation flow follows a strict pipeline defined across three key files:

| File | Primary Role |
|------|--------------|
| [`semantica/reasoning/explanation_generator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/reasoning/explanation_generator.py) | Implements `ExplanationGenerator`, `Explanation`, `ReasoningPath`, and NL generation logic |
| [`semantica/vector_store/vector_store.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/vector_store/vector_store.py) | Provides `explain_decision` for similarity-enriched explanations |
| [`semantica/vector_store/decision_vector_methods.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/vector_store/decision_vector_methods.py) | Exposes the public `explain` API shortcut |

The generation process executes in four distinct stages:

1. **`generate_explanation`** – Dispatches to type-specific helpers based on result class
2. **`_explain_inference_result`** – Constructs the `ReasoningPath` and coordinates text generation
3. **`_generate_natural_language`** – Formats output according to `detail_level`
4. **Returns `Explanation`** – A dataclass containing all reasoning components

## Summary

- **Semantica** generates explanations through the `ExplanationGenerator` class, which processes `InferenceResult` objects into structured `Explanation` dataclasses.
- The system supports three detail levels (`simple`, `detailed`, `verbose`) configured via the `detail_level` parameter in `ExplanationGenerator`.
- Explanations contain **reasoning paths** (lists of `ReasoningStep` objects), **natural-language text**, and **metadata** including confidence scores.
- For decision-level queries, `VectorStore.explain_decision` enriches explanations with similar decisions from vector backends, handling unavailable similarity data gracefully via the `similarity_unavailable` flag.
- The implementation spans [`semantica/reasoning/explanation_generator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/reasoning/explanation_generator.py) and [`semantica/vector_store/vector_store.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/vector_store/vector_store.py), with a public API shortcut in [`decision_vector_methods.py`](https://github.com/semantica-agi/semantica/blob/main/decision_vector_methods.py).

## Frequently Asked Questions

### How do I change the verbosity of generated explanations?

Configure the `detail_level` parameter when initializing `ExplanationGenerator`. Valid values are `"simple"`, `"detailed"`, and `"verbose"`, which control how `_generate_natural_language` formats the output text. Pass this within the config dictionary: `ExplanationGenerator(config={"detail_level": "verbose"})`.

### What happens if the vector store cannot retrieve similar decisions?

If the backend lacks direct vector access (e.g., FAISS indices without a direct map), `VectorStore.explain_decision` logs a warning and sets `similarity_unavailable` to `True` in the returned explanation dictionary. Your application can check this flag to determine whether similarity-based context is present or degraded.

### Can I generate explanations for custom inference result types?

Yes. The `generate_explanation` method dispatches to type-specific helpers based on the result class (lines 30-38 in [`explanation_generator.py`](https://github.com/semantica-agi/semantica/blob/main/explanation_generator.py)). You can extend the generator by implementing custom handler methods for your specific result types, following the pattern established by `_explain_inference_result`.

### Where is the reasoning path data structure defined?

The `ReasoningPath` and `ReasoningStep` classes are defined alongside the `ExplanationGenerator` in [`semantica/reasoning/explanation_generator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/reasoning/explanation_generator.py). These dataclasses store the structured breakdown of premises and rules, accessible via `explanation.reasoning_path.steps` after generation.