How to Record and Query Decisions with Semantica's DecisionRecorder
Semantica's DecisionRecorder treats every decision as a first-class knowledge-graph node enriched with semantic embeddings and provenance metadata, enabling hybrid semantic and structural queries via the DecisionContext API.
The semantica-agi/semantica library provides a comprehensive framework for recording and querying decisions with Semantica, separating storage concerns between low-level graph persistence and high-level retrieval interfaces. This architecture allows developers to capture decision provenance while enabling powerful precedent-based searches that combine vector similarity with graph traversal.
Understanding the DecisionRecorder Architecture
DecisionRecorder: Low-Level Graph Persistence
Located in semantica/context/decision_recorder.py, the DecisionRecorder class handles the fundamental persistence layer. It persists Decision objects (defined in semantica/context/decision_models.py) into the graph store, links them to involved entities, and registers provenance via ProvenanceManager. Key methods include record_decision(), link_entities(), apply_policies(), record_exception(), and capture_cross_system_context().
DecisionContext: High-Level Query Interface
The DecisionContext class in semantica/context/decision_context.py serves as the primary façade for applications and agents. It delegates storage operations to the vector store while exposing rich query primitives that combine semantic similarity (via embeddings) with structural similarity (via graph hops). Essential methods include record_decision(), find_similar_decisions(), query_decisions(), and explain_decision().
Recording Decisions in Semantica
To record a decision, instantiate DecisionContext with your vector store (FAISS, Pinecone, etc.) and optional graph store, then call record_decision():
from semantica.context import DecisionContext
ctx = DecisionContext(vector_store=my_vector_store, graph_store=my_graph_store)
decision_id = ctx.record_decision(
scenario="Mortgage loan request – $250k",
reasoning="Borrower has a 780 credit score, 5-year employment history",
outcome="approved",
confidence=0.96,
entities=["customer_123", "property_456"],
category="loan_approval",
loan_amount=250_000,
term_years=30
)
print(f"Decision recorded with ID: {decision_id}")
Behind the scenes, DecisionContext.record_decision() validates required fields and either forwards to a vector-store-specific store_decision() implementation or falls back to DecisionEmbeddingPipeline in semantica/vector_store/decision_embedding_pipeline.py. The pipeline generates a semantic embedding for the reasoning (when auto_embed=True) and persists the decision vector, returning a vector_id that becomes the canonical decision identifier.
The low-level DecisionRecorder.record_decision() then stores the decision node in the graph, links supplied entities via link_entities(), and records provenance using ProvenanceManager from semantica/provenance.py to create W3C PROV-O compliant activities, agents, and entity relationships.
Querying Decisions with Hybrid Search
Semantica enables precedent-based decision making through hybrid search that fuses vector similarity with graph structural relationships. The DecisionContext.find_similar_decisions() method delegates to ContextRetriever.retrieve_decision_precedents() in semantica/context/context_retriever.py:
precedents = ctx.find_similar_decisions(
scenario="Mortgage loan request – $250k",
limit=5,
use_hybrid_search=True,
include_context=True
)
for p in precedents:
print(f"{p['decision_id']} – score {p['score']:.2f} – outcome {p['outcome']}")
This hybrid approach applies configurable semantic_weight and structural_weight parameters to balance cosine distance in vector space against graph hop relationships. The method returns decision dictionaries containing similarity scores, outcomes, and linked metadata from the knowledge graph.
Explaining Decision Rationale
For transparency and compliance, DecisionContext.explain_decision() generates human-readable narratives that detail why a specific decision was made:
explanation = ctx.explain_decision(decision_id, include_paths=True)
print(f"Scenario: {explanation['scenario']}")
print(f"Reasoning: {explanation['reasoning']}")
print(f"Confidence: {explanation['confidence']:.2f}")
print("\nSimilar precedents that influenced this decision:")
for sim in explanation["similar_decisions"]:
print(f" • {sim['decision_id']} – {sim['outcome']} (score {sim['score']:.2f})")
The method either leverages the vector store's native explanation capabilities or constructs a fallback explanation incorporating original decision fields, confidence scores, similarity weights, and precedent decisions that influenced the outcome.
Summary
- DecisionRecorder (
semantica/context/decision_recorder.py) provides low-level persistence, entity linking vialink_entities(), and provenance tracking using W3C PROV-O standards. - DecisionContext (
semantica/context/decision_context.py) offers the high-level API for recording and querying decisions with Semantica, abstracting storage complexity behind methods likerecord_decision()andfind_similar_decisions(). - Hybrid retrieval combines semantic vector similarity with structural graph traversal via
ContextRetrieverto identify relevant precedents using configurable weights. - Decision models in
semantica/context/decision_models.pydefine the Pydantic-styleDecision,Policy, andApprovalChainstructures used throughout the system. - Embeddings are automatically generated by
DecisionEmbeddingPipelinewhenauto_embedis enabled, enabling cosine similarity searches across decision reasoning text.
Frequently Asked Questions
What is the difference between DecisionRecorder and DecisionContext?
DecisionRecorder is the low-level service responsible for persisting decisions to the graph store, linking entities via link_entities(), and managing provenance records through ProvenanceManager. DecisionContext is the high-level façade that applications interact with, providing simplified methods for recording decisions and querying them using hybrid semantic-structural search while abstracting the underlying storage mechanisms and embedding pipelines.
How does Semantica generate embeddings for decisions?
When auto_embed is enabled in the configuration, the DecisionEmbeddingPipeline in semantica/vector_store/decision_embedding_pipeline.py generates semantic embeddings from the decision's reasoning field. These embeddings are stored as decision vectors alongside metadata in the vector store, enabling cosine similarity searches during precedent retrieval via find_similar_decisions().
Can I query decisions using only graph relationships without vector similarity?
Yes. While the default find_similar_decisions() uses hybrid search combining both modalities, you can adjust the semantic_weight and structural_weight parameters to favor structural similarity, or interact directly with the graph store through DecisionRecorder methods like link_precedents() to perform purely topological queries based on entity links and graph connectivity.
How does Semantica track the provenance of recorded decisions?
The system uses ProvenanceManager from semantica/provenance.py to create W3C PROV-O compliant audit trails. When DecisionRecorder.record_decision() persists a decision, it simultaneously registers provenance metadata that captures the agent making the decision, the timestamp, and the involved entities via ProvenanceManager, creating a complete, standards-compliant audit trail for compliance and debugging.
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 →