# How ExplanationGenerator Creates Reasoning Traces with Justification Objects in Semantica

> Discover how ExplanationGenerator in Semantica builds reasoning traces and justification objects from supporting evidence. Learn to structure complex reasoning for clarity.

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

---

**The ExplanationGenerator in Semantica transforms reasoning results into structured, human-readable traces by building ReasoningPath objects from ReasoningStep collections, assembling Justification objects from supporting evidence, and packaging everything into Explanation dataclasses.**

The `ExplanationGenerator` class in the `semantica-agi/semantica` repository converts raw logical results—such as `InferenceResult`, `Proof`, or abductive explanations—into transparent, step-by-step reasoning traces complete with justification objects. Understanding how ExplanationGenerator creates reasoning traces with justification objects is essential for debugging AI-driven inferences and providing end-users with auditable explanations of automated decisions.

## The Three-Stage Explanation Pipeline

The generator processes reasoning results through a structured pipeline that transforms low-level logical outputs into high-level explanatory artifacts.

### Stage 1: Constructing the ReasoningPath

The first stage converts raw reasoning results into a sequence of discrete steps. Depending on the input type, the generator delegates to specialized helper methods in [`semantica/reasoning/explanation_generator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/reasoning/explanation_generator.py):

- **`_explain_inference_result`** (lines 94‑119): Builds a `ReasoningPath` from `InferenceResult.premises`, optionally adding a rule step to capture the transformation logic.

- **`_explain_proof`** (lines 140‑155): Constructs a path from each step in a deductive `Proof` object, preserving the logical derivation chain.

- **`_explain_abductive`** (lines 176‑190): Generates a path from abductive hypotheses, mapping backward-chained explanations to forward-readable steps.

Each method populates a list of **`ReasoningStep`** objects that capture the premise, applicable rule, input facts, output fact, confidence score, and optional metadata. These steps, combined with start facts, end conclusions, and overall confidence, are wrapped in a **`ReasoningPath`** dataclass.

### Stage 2: Synthesizing Justification Objects

When explicit justification is required, the `justify_conclusion` method (lines 210‑260) performs evidence aggregation and explanatory text generation:

1. **Evidence Collection**: Gathers all supporting evidence from the `input_facts` of every step in the `ReasoningPath`.

2. **Confidence Calculation**: Copies the overall confidence score from the path to the justification.

3. **Text Generation**: Optionally synthesizes natural-language explanations via `_generate_justification_text`.

The results are packaged into a **`Justification`** dataclass containing the evidence set, confidence metrics, and human-readable explanation text.

### Stage 3: Assembling the Final Explanation

The `generate_explanation` method orchestrates the complete pipeline:

- **Tracking Initialization** (lines 31‑45): Sets up internal state for explanation generation.

- **Helper Selection** (lines 48‑72): Routes the input to the appropriate specialized handler (`_explain_inference_result`, `_explain_proof`, `_explain_abductive`, or `_explain_generic`).

- **Output Assembly** (lines 74‑79): Returns an **`Explanation`** object that embeds the `ReasoningPath` and optionally includes a `Justification` and natural-language summary generated by `_generate_natural_language*` methods.

## Practical Implementation: Generating Traces and Justifications

The following example demonstrates how to generate reasoning traces and justifications using the Semantica API:

```python
from semantica.reasoning import ExplanationGenerator, Reasoner

# Initialize reasoner and load knowledge

reasoner = Reasoner()
reasoner.add_rule("IF A THEN B")
reasoner.add_fact("A")

# Execute forward chaining inference

result = reasoner.forward_chain()[0]  # InferenceResult for conclusion "B"

# Generate explanation with reasoning trace

gen = ExplanationGenerator()
explanation = gen.generate_explanation(result)

# Inspect the reasoning path

print(explanation.reasoning_path)

# Output: ReasoningPath containing:

#   - step_0: Premise A

#   - rule_step: Applied rule IF A THEN B → B

# Generate explicit justification

justification = gen.justify_conclusion(
    conclusion=explanation.conclusion,
    reasoning_path=explanation.reasoning_path,
)

print(justification.explanation_text)

# Output: "Conclusion 'B' is justified by the following reasoning path: 

#          Premise: A -> Applied rule: IF A THEN B"

```

## Core Data Structures and Source Files

Understanding the architecture requires familiarity with these key components:

- **[`semantica/reasoning/explanation_generator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/reasoning/explanation_generator.py)**: Contains the `ExplanationGenerator` class and all explanation-building logic.

- **[`semantica/reasoning/reasoner.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/reasoning/reasoner.py)**: Defines `InferenceResult` and the `Reasoner` class that supplies input objects to the generator.

- **[`semantica/reasoning/deductive_reasoner.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/reasoning/deductive_reasoner.py)**: Provides the `Proof` dataclass used for deductive explanations.

- **[`semantica/reasoning/abductive_reasoner.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/reasoning/abductive_reasoner.py)**: Supplies abductive explanation structures consumed by `_explain_abductive`.

## Summary

- **ExplanationGenerator** converts raw reasoning outputs into structured `ReasoningPath` objects composed of discrete `ReasoningStep` instances.

- Three specialized methods—`_explain_inference_result`, `_explain_proof`, and `_explain_abductive`—handle different reasoning paradigms at lines 94‑119, 140‑155, and 176‑190 respectively.

- The `justify_conclusion` method (lines 210‑260) creates `Justification` objects by aggregating evidence from step inputs and generating explanatory text.

- The `generate_explanation` method (lines 31‑79) orchestrates the entire pipeline, returning fully populated `Explanation` dataclasses.

- All components reside in [`semantica/reasoning/explanation_generator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/reasoning/explanation_generator.py) and interface closely with [`reasoner.py`](https://github.com/semantica-agi/semantica/blob/main/reasoner.py), [`deductive_reasoner.py`](https://github.com/semantica-agi/semantica/blob/main/deductive_reasoner.py), and [`abductive_reasoner.py`](https://github.com/semantica-agi/semantica/blob/main/abductive_reasoner.py).

## Frequently Asked Questions

### What is the difference between a ReasoningPath and a Justification in Semantica?

A **`ReasoningPath`** represents the complete logical derivation as a sequence of steps from premises to conclusion, including confidence metadata and rule applications. A **`Justification`** focuses specifically on the supporting evidence for the final conclusion, aggregating input facts from all steps and providing a synthesized natural-language explanation. While the path shows *how* the system reached a conclusion, the justification explains *why* the conclusion is valid based on the evidence.

### How does ExplanationGenerator handle different types of reasoning inputs?

The generator uses polymorphic dispatch via `generate_explanation` (lines 48‑72) to route inputs to specialized handlers. `InferenceResult` objects are processed by `_explain_inference_result`, deductive `Proof` objects by `_explain_proof`, and abductive explanations by `_explain_abductive`. Each handler constructs the appropriate `ReasoningStep` sequences while preserving the semantic characteristics of the underlying reasoning type.

### Can the ExplanationGenerator produce natural language explanations?

Yes. The generator optionally synthesizes human-readable text through `_generate_justification_text` and `_generate_natural_language*` methods. These methods transform structured `ReasoningPath` and `Justification` objects into readable explanations suitable for end-user interfaces, while the underlying dataclasses maintain machine-processable structures for programmatic analysis.

### Where does the confidence score originate in a reasoning trace?

Confidence values flow from the original reasoning result into the `ReasoningPath` during step construction. When `justify_conclusion` assembles a `Justification` object (lines 210‑260), it explicitly copies the overall confidence from the path and can aggregate individual step confidences to provide transparency about the certainty level at each inference stage.