# How the AgentContext API Unifies Vector Search and Graph Traversal in Semantica

> Discover how Semantica's AgentContext API unifies vector search and graph traversal. Learn how it fuses results and blends scores for powerful context retrieval.

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

---

**The `AgentContext` API seamlessly integrates vector search and graph traversal by orchestrating a `ContextRetriever` pipeline that fuses cosine-based nearest-neighbor results with knowledge graph expansions, then blends their scores using a configurable `hybrid_alpha` weight.**

The **AgentContext API** in the Semantica framework serves as the primary interface for agent memory, abstracting away the complexity of hybrid retrieval systems. Rather than forcing developers to choose between semantic similarity and structured reasoning, it composes **vector stores**, **knowledge graphs**, and intelligent **retrieval orchestration** into a single, coherent API.

## Core Architecture: Three Integrated Components

`AgentContext` composes three specialized subsystems that work together during every retrieval operation:

- **VectorStore** — Maintains dense embeddings for raw text, decisions, and artifacts. Provides fast semantic similarity via cosine-based nearest-neighbor search.
- **ContextGraph (Knowledge Graph)** — Stores entities, relationships, and bi-temporal facts. Enables graph-native traversals including BFS/DFS, centrality analysis, and path-finding.
- **ContextRetriever** — Orchestrates the hybrid pipeline: queries the vector store, optionally expands results via graph traversal, and fuses scores from both sources.

This composition happens in [`semantica/context/agent_context.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/context/agent_context.py) lines 90–105, where the constructor receives and wires together these dependencies.

## Initialization and Configuration

When you instantiate `AgentContext`, the API automatically configures hybrid retrieval if a knowledge graph is provided. In [`agent_context.py`](https://github.com/semantica-agi/semantica/blob/main/agent_context.py) lines 98–110, the retriever is initialized with three critical parameters:

```python
ctx = AgentContext(
    vector_store=vs,
    knowledge_graph=kg,           # enables hybrid mode

    graph_expansion=True,         # activate traversal

    max_expansion_hops=2,         # BFS depth limit

    hybrid_alpha=0.5,             # equal weight: 50% vector, 50% graph

)

```

Key configuration parameters:

| Parameter | Default | Purpose |
|-----------|---------|---------|
| `use_graph_expansion` | `True` | Toggle graph traversal on/off |
| `max_expansion_hops` | `2` | Maximum BFS depth from vector results |
| `hybrid_alpha` | `0.5` | Blend factor: 0 = pure vector, 1 = pure graph |

## The Hybrid Retrieval Pipeline

The `ContextRetriever.retrieve` method executes a four-stage pipeline documented in [`semantica/context/context_retriever.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/context/context_retriever.py).

### Stage 1: Vector Retrieval

First, the retriever queries the vector store for top-k nearest neighbors. This stage is documented in lines 11–15:

```python

# Pseudocode representing the vector search stage

vector_results = self.vector_store.search(
    query_embedding=embed(query),
    k=top_k
)

```

### Stage 2: Graph Expansion

If `use_graph_expansion` is enabled, the retriever invokes graph utilities to explore related entities. Lines 18–24 show how `PathFinder`, `CentralityCalculator`, and other KG analytics tools expand the result set up to `max_expansion_hops`.

### Stage 3: Score Normalization

Both result sets are normalized to 0–1 range. Lines 31–33 implement this normalization to ensure fair comparison between vector similarity scores and graph-derived relevance signals.

### Stage 4: Hybrid Blending

The final relevance score computes as:

```

final_score = hybrid_alpha * graph_score + (1 - hybrid_alpha) * vector_score

```

This weighting logic appears in [`context_retriever.py`](https://github.com/semantica-agi/semantica/blob/main/context_retriever.py) lines 32–34. The `HybridSimilarityCalculator` class (instantiated at lines 58–60) performs this computation.

## Decision-Aware Embedding: Deepening the Integration

When `decision_tracking=True`, the integration goes deeper. Lines 74–80 of [`context_retriever.py`](https://github.com/semantica-agi/semantica/blob/main/context_retriever.py) initialize a `DecisionEmbeddingPipeline` that enriches vector embeddings with graph-derived features before storage:

- **Node2Vec embeddings** — Capture structural graph position
- **Centrality scores** — Identify influential entities
- **Community tags** — Group semantically related clusters

This preprocessing means subsequent vector searches inherently benefit from structural knowledge graph signals, even during the initial nearest-neighbor lookup.

## Complete Working Example

```python
from semantica.context import AgentContext, ContextGraph
from semantica.vector_store import VectorStore

# 1. Create backends

vs = VectorStore(backend="faiss", dimension=1536)
kg = ContextGraph(advanced_analytics=True)

# 2. Initialize hybrid context

ctx = AgentContext(
    vector_store=vs,
    knowledge_graph=kg,
    graph_expansion=True,
    max_expansion_hops=3,
    hybrid_alpha=0.6,          # favor graph signals

    decision_tracking=True,
)

# 3. Store with dual indexing

mem_id = ctx.store(
    "Alice approved the Acme renewal in Q1 2024",
    conversation_id="conv_001",
    extract_entities=True,
    extract_relationships=True,
)

# 4. Hybrid retrieval

results = ctx.retrieve(
    "Who approved the Acme contract?",
    max_results=5,
)

for r in results:
    print(f"[{r.score:.2f}] {r.content}")
    print(f"  Related entities: {[e['id'] for e in r.related_entities]}")

```

Each `RetrievedContext` object contains the merged content, blended relevance score, and related graph entities/relationships from the expansion phase.

## Key Implementation Files

| File | Purpose |
|------|---------|
| [`semantica/context/agent_context.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/context/agent_context.py) | High-level API; glues memory, vector store, and graph |
| [`semantica/context/context_retriever.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/context/context_retriever.py) | Hybrid pipeline, score normalization, graph expansion |
| [`semantica/vector_store/hybrid_similarity.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/vector_store/hybrid_similarity.py) | `HybridSimilarityCalculator` for score blending |
| [`semantica/vector_store/decision_embedding_pipeline.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/vector_store/decision_embedding_pipeline.py) | KG-feature enrichment for embeddings |
| [`semantica/kg/path_finder.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/path_finder.py), [`centrality_calculator.py`](https://github.com/semantica-agi/semantica/blob/main/centrality_calculator.py) | Graph algorithms for expansion |

## Summary

- **AgentContext** provides a unified façade for hybrid retrieval in Semantica, hiding the complexity of coordinating vector and graph subsystems.
- **ContextRetriever** implements the core pipeline: vector search → graph expansion → score normalization → weighted blending.
- **Configurable weights** via `hybrid_alpha` let developers tune the balance between semantic similarity and structural relevance.
- **Decision-aware embedding** pre-enriches vectors with graph features, enabling even "pure" vector searches to leverage structural knowledge.

## Frequently Asked Questions

### How do I disable graph traversal and use only vector search?

Set `graph_expansion=False` when constructing `AgentContext`, or equivalently `use_graph_expansion=False` in retriever configuration. The retriever will skip the expansion stage and return pure vector results with `hybrid_alpha` effectively ignored.

### What graph algorithms are available during expansion?

The retriever instantiates `PathFinder`, `CentralityCalculator`, and community detection utilities as shown in [`context_retriever.py`](https://github.com/semantica-agi/semantica/blob/main/context_retriever.py) lines 62–68. These support BFS/DFS traversal, shortest-path queries, betweenness centrality, and modularity-based clustering.

### Can I tune `hybrid_alpha` per query rather than globally?

Currently `hybrid_alpha` is configured at initialization. For query-specific tuning, you would need to instantiate multiple `AgentContext` instances with different configurations, or modify the retriever's `retrieve` method to accept runtime override parameters.

### How does decision tracking affect storage overhead?

The `DecisionEmbeddingPipeline` adds computational overhead during the `store()` operation to compute graph features and enrich embeddings. Storage increases proportionally with the dimensionality of added features (node2vec vectors, centrality scalars, community identifiers).