How to Find Precedents for Decisions Using AgentContext: A Complete Guide

The AgentContext.find_precedents() method in the semantica-agi/semantica repository enables semantic and structural retrieval of past decisions by searching vector stores and knowledge graphs, returning ranked Decision objects that match a given scenario.

When building autonomous AI agents, retrieving relevant historical decisions is critical for consistent reasoning. The AgentContext class in the semantica-agi/semantica open-source framework provides a unified interface to find precedents for decisions using AgentContext, combining vector similarity with graph-based traversal. This implementation, located in semantica/context/agent_context.py, allows agents to leverage past outcomes when evaluating new scenarios, ensuring decisions align with established patterns.

Enabling Decision Tracking

Before retrieving precedents, you must configure the AgentContext with decision tracking enabled. When the decision_tracking flag is set to True during instantiation, the context creates a backend that stores each decision in both the knowledge graph and vector store. This prerequisite step populates the data stores that find_precedents queries later.

The decision tracking system records decisions via context.record_decision(), which persists decision metadata, reasoning, and outcomes to the configured backends. Without this enabled, the search methods will return empty results since no historical data exists in the storage layer.

The find_precedents Method Signature

The primary API for retrieving historical decisions is defined in semantica/context/agent_context.py at lines 1733-1788, with fallback logic extending to line 1888. The method signature accepts multiple filtering parameters to refine search results:

AgentContext.find_precedents(
    scenario: str,
    category: Optional[str] = None,
    limit: int = 10,
    use_hybrid_search: bool = True,
    max_hops: int = 3,
    include_context: bool = True,
    include_superseded: bool = False,
    as_of: Optional[Union[str, datetime]] = None,
) → List[Decision]

Key parameters include:

  • scenario – The natural-language description of the decision scenario you want precedents for
  • category – Optional filter to limit results to specific decision categories (e.g., loan_approval)
  • use_hybrid_search – Boolean flag enabling combined vector and graph search when backends support it
  • max_hops – Integer specifying how many edge traversals to perform when graph reasoning is active
  • as_of – Temporal filter accepting datetime strings to retrieve only decisions valid at a specific historical point

The method returns a list of Decision objects defined in semantica/context/decision_models.py, containing the decision ID, scenario text, outcome, confidence scores, and relevance metadata.

Backend Search Strategies

The implementation automatically selects one of three search strategies based on your configured components in semantica/context/agent_context.py. Each strategy offers different trade-offs between semantic relevance and structural reasoning.

ContextGraph (Graph-Store Mode)

  • Activation condition: self._decision_backend == "context_graph" and the graph implements find_precedents_by_scenario
  • Implementation location: semantica/context/context_graph.py lines 4470-4520
  • Behavior: Executes semantic and structural queries directly on the knowledge graph, filtering by category, temporal constraints (as_of), and superseded status

DecisionQuery (Hybrid Search Mode)

  • Activation condition: self._decision_backend == "graph_store" and use_hybrid_search=True
  • Implementation location: semantica/context/decision_query.py lines 174-210
  • Behavior: Calls DecisionQuery.find_precedents_hybrid, combining vector-store embeddings with graph-based multi-hop reasoning to identify semantically similar decisions that share structural relationships

Vector-Store Only Mode

  • Activation condition: No graph backend configured or use_hybrid_search=False
  • Implementation location: semantica/vector_store/decision_vector_methods.py lines 98-130
  • Behavior: Performs pure vector similarity search via self.vector_store.search_decisions using the scenario embedding to find nearest neighbors in the decision embedding space

Step-by-Step Implementation

Follow this complete workflow to set up precedent retrieval in your application:


# -------------------------------------------------

# 1. Set up a vector store (Qdrant example)

# -------------------------------------------------

from semantica.vector_store.qdrant_store import QdrantStore

vector_store = QdrantStore(
    url="http://localhost:6333",
    collection_name="semantic_decisions",
)

# -------------------------------------------------

# 2. Set up a knowledge graph (ContextGraph)

# -------------------------------------------------

from semantica.context.context_graph import ContextGraph

knowledge_graph = ContextGraph(
    storage_path="graph_data",
    enable_node2vec=True,
)

# -------------------------------------------------

# 3. Initialize AgentContext with decision tracking

# -------------------------------------------------

from semantica.context.agent_context import AgentContext

context = AgentContext(
    vector_store=vector_store,
    knowledge_graph=knowledge_graph,
    decision_tracking=True,  # Required for precedent storage

    advanced_analytics=True,
)

# -------------------------------------------------

# 4. Record historical decisions

# -------------------------------------------------

decision_id = context.record_decision(
    category="loan_approval",
    scenario="Mortgage application for a 750-point credit score",
    reasoning="Credit score high, debt-to-income low",
    outcome="approved",
    confidence=0.97,
)

# -------------------------------------------------

# 5. Find precedents for a new scenario

# -------------------------------------------------

precedents = context.find_precedents(
    scenario="Mortgage request with credit score 730",
    category="loan_approval",
    limit=5,
    use_hybrid_search=True,
    max_hops=2,
)

for p in precedents:
    print(f"{p.decision_id} – score={p.metadata.get('score'):.2f}")
    print(f"  scenario: {p.scenario}")
    print(f"  outcome: {p.outcome}")

Advanced Filtering Options

The find_precedents method supports sophisticated filtering beyond basic text matching.

Temporal Precedent Retrieval The as_of parameter enables time-aware searching, allowing you to retrieve only decisions that were valid at a specific historical moment. This is essential for auditing or reproducing decision logic from previous system states. When provided, the method normalizes timestamps and filters the result set to exclude decisions recorded after the specified datetime.

Category Isolation Use the category parameter to constrain searches to specific decision taxonomies (e.g., fraud_detection, pricing_strategy). This prevents cross-domain contamination when your agent handles multiple distinct decision types.

Superseded Decision Handling Set include_superseded=True to retrieve decisions that have been explicitly marked as overridden or deprecated. This is useful for analyzing decision evolution or understanding why previous approaches were abandoned.

Contextual Metadata When include_context=True, the returned Decision objects contain full contextual information including related entities and relationship graphs from the knowledge store. This provides explainability by showing not just similar decisions, but why they are structurally related.

Summary

  • AgentContext.find_precedents() requires decision_tracking=True during initialization to access historical decision data stored in semantica/context/agent_context.py
  • The method automatically selects between three search backends: pure vector search, graph-based semantic search, or hybrid retrieval combining both approaches
  • Hybrid search (use_hybrid_search=True) leverages DecisionQuery.find_precedents_hybrid in semantica/context/decision_query.py to balance embedding similarity with structural graph relationships
  • Time-aware queries via the as_of parameter enable historical point-in-time precedent retrieval for auditing and reproducibility
  • The implementation at lines 1733-1888 of agent_context.py normalizes timestamps, validates backends, and constructs proper Decision model instances from raw storage results

Frequently Asked Questions

Hybrid search combines vector embedding similarity with graph-structure traversal, using the DecisionQuery class to find decisions that are both semantically similar and structurally connected in the knowledge graph. Vector-only search relies solely on embedding space proximity via vector_store.search_decisions, which is faster but ignores relational context between decisions. Set use_hybrid_search=False to force vector-only mode when graph traversal latency is unacceptable.

How does time-aware precedent searching work?

The as_of parameter accepts either ISO format strings or datetime objects, allowing you to query the decision history as it existed at a specific point in time. According to the implementation in semantica/context/agent_context.py, the method normalizes all timestamps to UTC before filtering, ensuring decisions recorded after the specified cutoff are excluded from results. This enables reproducible decision-making and historical auditing capabilities.

Can I use find_precedents without a knowledge graph?

Yes, if you provide only a vector_store without a knowledge_graph that implements the precedent interface, the method automatically falls back to pure vector similarity search. In this mode, the system calls search_decisions from semantica/vector_store/decision_vector_methods.py (lines 98-130) to retrieve precedents based on embedding similarity alone. However, you lose the structural reasoning capabilities provided by ContextGraph or DecisionQuery backends.

How are precedents ranked when multiple backends are available?

The ranking depends on the active backend. In hybrid mode, DecisionQuery.find_precedents_hybrid combines vector similarity scores with graph traversal weights to produce composite relevance scores. For graph-only mode, ContextGraph.find_precedents_by_scenario applies semantic similarity within graph neighborhoods. In vector-only mode, ranking follows the vector store's native distance metrics (typically cosine similarity). All modes return Decision objects containing a score field in their metadata for transparent ranking inspection.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →