How Semantica's ExplanationGenerator Provides Explainable Reasoning Paths
Semantica's ExplanationGenerator constructs explainable reasoning paths by transforming raw inference results into structured, step‑by‑step traces composed of ReasoningStep objects, enabling both machine‑processable logic and human‑readable natural‑language justifications.
The semantica-agi/semantica repository implements a neuro‑symbolic AI framework where transparency is paramount. The ExplanationGenerator class serves as the central engine for converting opaque reasoning outputs—whether deductive proofs, abductive hypotheses, or simple inferences—into explainable reasoning paths that trace exactly how a conclusion was reached.
Core Data Structures for Reasoning Transparency
The explanation architecture in semantica/reasoning/explanation_generator.py decouples logical representation from presentation through four primary data classes.
ReasoningStep
The ReasoningStep class (lines 44‑55) captures a single discrete inference operation. It stores a unique step identifier, a human‑readable description, the specific rule applied, input facts, the output fact, confidence scores, and arbitrary metadata. This granularity ensures that every logical operation remains auditable.
ReasoningPath
A ReasoningPath (lines 58‑66) aggregates multiple ReasoningStep instances into an ordered sequence. It tracks the initial premises, the final conclusion, and an aggregate confidence calculation across all steps, providing the structural backbone for explainable reasoning paths.
Justification and Explanation
The Justification class (lines 69‑78) bundles a conclusion with its supporting ReasoningPath, evidence references, and natural‑language text. The top‑level Explanation class (lines 82‑92) encapsulates the final output, including optional reasoning paths and justifications, making the trace consumable by both visualizers and end‑users.
The Explanation Generation Workflow
The ExplanationGenerator orchestrates the creation of explanations through a type‑aware dispatch system that handles diverse reasoning modalities.
Entry Point and Type Dispatch
The generate_explanation method acts as the primary entry point (lines 130‑173), accepting any reasoning object—InferenceResult, Proof, AbductiveExplanation, or generic values. It inspects the input type and routes to specialized helper methods, ensuring that each reasoning paradigm receives appropriate processing for building explainable reasoning paths.
Specialized Handlers for Different Reasoning Types
Four distinct handlers convert specific reasoning artifacts into structured traces:
- Inference Results:
_explain_inference_result(lines 191‑236) constructs aReasoningPathfrom premises, optionally appends rule application steps, and assembles the finalExplanationobject. - Proof Objects:
_explain_proof(lines 238‑274) iterates through proof steps, converting each into aReasoningStepto build a complete deductive trace. - Abductive Explanations:
_explain_abductive(lines 276‑315) transforms hypothesis objects into reasoning paths that explain why a particular hypothesis best explains the observed facts. - Fallback Handling:
_explain_genericwraps unrecognized objects in a basicExplanationcontainer for API consistency.
Path Retrieval and Justification
The public method show_reasoning_path (lines 29‑41) provides direct access to the embedded ReasoningPath from any explanation. For formal validation, justify_conclusion (lines 43‑98) aggregates input facts across all steps, calculates aggregate confidence, and generates natural‑language justifications via _generate_justification_text.
Natural Language Synthesis
Depending on the detail_level configuration and generate_nl flag, the generator synthesizes human‑readable descriptions. Helper methods _generate_natural_language, _generate_natural_language_from_proof, and _generate_natural_language_from_abductive (lines 112‑155) produce varying verbosity levels, from concise summaries to detailed step‑by‑step narratives of the explainable reasoning paths.
Practical Code Examples
The following examples demonstrate how to generate and consume explanations using the ExplanationGenerator.
First, instantiate the generator and process an inference result:
from semantica.reasoning import ExplanationGenerator, InferenceResult
# Mock inference result (typically produced by a Reasoner)
inference = InferenceResult(
conclusion="All mammals are warm‑blooded",
premises=["All dogs are mammals", "All cats are mammals"],
confidence=0.96,
rule_used=Rule(name="Transitivity", rule_id="R1")
)
gen = ExplanationGenerator(config={"detail_level": "detailed"})
explanation = gen.generate_explanation(inference)
print("Explanation ID:", explanation.explanation_id)
print("NL text:", explanation.natural_language)
print("Path ID:", explanation.reasoning_path.path_id)
for step in explanation.reasoning_path.steps:
print(f"- {step.step_id}: {step.description}")
To retrieve only the reasoning path and generate a formal justification:
path = gen.show_reasoning_path(inference)
just = gen.justify_conclusion(conclusion=inference.conclusion, reasoning_path=path)
print("\nJustification text:")
print(just.explanation_text)
These snippets illustrate how the generator creates full reasoning traces, exposes them via show_reasoning_path, and transforms them into natural‑language justifications.
Summary
- Semantica's ExplanationGenerator in
semantica/reasoning/explanation_generator.pyconverts raw reasoning outputs into structured, auditable traces. - Four data classes—
ReasoningStep,ReasoningPath,Justification, andExplanation—provide the architectural foundation for transparent reasoning. - Type‑aware dispatch via
generate_explanationhandles inference results, proofs, and abductive explanations through specialized handlers. - Dual representation separates machine‑processable logic from human‑readable natural language, enabling consumption by both visualizers and end‑users.
- Public methods
show_reasoning_pathandjustify_conclusionprovide programmatic access to reasoning traces and formal justifications.
Frequently Asked Questions
What file contains the ExplanationGenerator implementation?
The ExplanationGenerator class and its associated data models reside in semantica/reasoning/explanation_generator.py within the semantica-agi/semantica repository. This module defines the core logic for transforming reasoning results into structured explanations.
How does Semantica handle different types of reasoning inputs?
The generator uses a dispatch pattern in the generate_explanation method to route inputs to specialized handlers: _explain_inference_result for deductive inferences, _explain_proof for formal proofs, _explain_abductive for hypothesis generation, and _explain_generic as a fallback for unknown types.
Can I extract just the reasoning path without natural language?
Yes. The show_reasoning_path method returns the ReasoningPath object directly, containing the ordered list of ReasoningStep instances without requiring natural language generation. This is useful for downstream visualizers or automated analysis tools that need structured data.
What information does each ReasoningStep capture?
Each ReasoningStep stores a unique identifier, textual description, the rule applied during that step, input facts, the resulting output fact, confidence scores, and metadata. This comprehensive capture ensures complete auditability of the reasoning process.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →