Files
semantica/cookbook/introduction/19_Context_Module.ipynb
T
KaifAhmad1 7a6f1d0417 docs: add citation section and fix stale org references
Add a Cite Us section to the README with BibTeX citation info, and
align it with docs/citation.md (author/organization: Semantica, 2026).
Update LICENSE and docs/project-license.md copyright holder to
Semantica, and replace the stale Hawksight-AI GitHub org slug with
semantica-agi across READMEs, plugin manifests, cookbook notebooks,
and GitHub templates.
2026-08-24 16:07:22 +05:30

12 KiB

Open In Colab

Context Module — Practical Guide

Semantica’s context module is the layer that makes an agent “stateful”. It combines:

  • Memory (short-term + long-term) via AgentMemory
  • Graph context via ContextGraph
  • Hybrid retrieval (vector + memory + graph) via ContextRetriever
  • High-level UX via AgentContext (recommended entry point)
  • Entity linking via EntityLinker
  • Extensibility + config via registry and config

This notebook focuses on small, runnable examples and keeps imports scoped to each cell.

In [ ]:
!pip install -q semantica

1) Vector store (for long-term memory)

The VectorStore can generate embeddings via its internal embedder. If no embedder is available in your environment, it falls back to random vectors so the API stays usable for demos.

In [ ]:
from semantica.vector_store import VectorStore

vs = VectorStore(backend="inmemory", dimension=384)

if getattr(vs, "embedder", None) and hasattr(vs.embedder, "set_text_model"):
    vs.embedder.set_text_model(method="fastembed", model_name="BAAI/bge-small-en-v1.5")

vs.backend, vs.dimension

AgentContext is the user-friendly interface that ties memory, vector store, and graph together. If you pass a ContextGraph, the system can do GraphRAG-style retrieval.

In [ ]:
from semantica.context import AgentContext, ContextGraph

kg = ContextGraph()
context = AgentContext(vector_store=vs, knowledge_graph=kg)

context.config

3) Store and retrieve memory

A single string is treated as a memory item. You can attach conversation_id and user_id through metadata-friendly parameters.

In [ ]:
memory_id = context.store(
    "User prefers short answers about Python.",
    conversation_id="conv_1",
    user_id="user_1",
    metadata={"type": "preference"},
)

context.get_memory(memory_id)
In [ ]:
context.store(
    "User is working on Semantica context module examples.",
    conversation_id="conv_1",
    user_id="user_1",
    metadata={"type": "note"},
)

context.retrieve("Python answers", max_results=3)
In [ ]:
context.conversation("conv_1", max_items=10)

4) Export, save, load

AgentContext includes simple persistence helpers. This example uses a temporary directory.

In [ ]:
export_json = context.export(conversation_id="conv_1", format="json")
export_json[:300]
In [ ]:
import tempfile

with tempfile.TemporaryDirectory() as d:
    context.save(d)
    context.load(d)

context.conversation_summary("conv_1")

5) Store documents and build a context graph

If you store a list, AgentContext.store(...) treats it as documents. To keep this notebook lightweight and deterministic, we pass pre-extracted entities and relationships per document.

In [ ]:
documents = [
    {
        "id": "doc_1",
        "content": "Python is used for machine learning.",
        "metadata": {"source": "docs"},
        "entities": [
            {"id": "e_python", "text": "Python", "type": "PROGRAMMING_LANGUAGE"},
            {"id": "e_ml", "text": "Machine Learning", "type": "CONCEPT"},
        ],
        "relationships": [
            {
                "source_id": "e_python",
                "target_id": "e_ml",
                "type": "used_for",
                "confidence": 0.9,
            }
        ],
    },
    {
        "id": "doc_2",
        "content": "PyTorch is a machine learning framework.",
        "metadata": {"source": "docs"},
        "entities": [
            {"id": "e_pytorch", "text": "PyTorch", "type": "FRAMEWORK"},
            {"id": "e_ml", "text": "Machine Learning", "type": "CONCEPT"},
        ],
        "relationships": [
            {
                "source_id": "e_pytorch",
                "target_id": "e_ml",
                "type": "implements",
                "confidence": 0.95,
            }
        ],
    },
]

stats = context.store(
    documents,
    extract_entities=False,
    extract_relationships=False,
    link_entities=True,
)

stats
In [ ]:
kg.stats()

6) Explore the graph with ContextGraph

The graph supports keyword querying and neighbor expansion.

In [ ]:
kg.query("machine learning")
In [ ]:
kg.get_neighbors("e_python", hops=2)

7) Entity linking with EntityLinker

EntityLinker assigns stable URIs and can link related or duplicate entities across sources.

In [ ]:
from semantica.context import EntityLinker

linker = EntityLinker(knowledge_graph={"entities": [{"id": "e_py", "text": "Python", "type": "PROGRAMMING_LANGUAGE"}]})

entities = [
    {"id": "e1", "text": "Python", "type": "PROGRAMMING_LANGUAGE"},
    {"id": "e2", "text": "PyTorch", "type": "FRAMEWORK"},
]

linked = linker.link("Python and PyTorch", entities=entities)
[(e.entity_id, e.uri, len(e.linked_entities)) for e in linked]
In [ ]:
linker.link_entities("e1", "e2", link_type="related_to", confidence=0.8)
linker.get_entity_links("e1")[:2]
In [ ]:
linker.build_entity_web()["statistics"]

8) Low-level building blocks: AgentMemory and ContextRetriever

If you want more control than AgentContext, you can wire the parts directly.

In [ ]:
from semantica.context import AgentMemory, ContextRetriever

memory = AgentMemory(vector_store=vs, knowledge_graph=kg, retention_policy="unlimited")
memory.store("Python powers Semantica.", metadata={"type": "fact", "conversation_id": "conv_2"})

retriever = ContextRetriever(memory_store=memory, knowledge_graph=kg, vector_store=vs)
results = retriever.retrieve("Python Semantica", max_results=5)

[(r.content, r.source, round(r.score, 3)) for r in results]

9) Methods, registry, and configuration

The methods layer exposes convenience functions, while registry lets you plug in your own implementations. config provides runtime configuration.

In [ ]:
from semantica.context.config import context_config

context_config.set("retention_policy", "7_days")
context_config.get("retention_policy")
In [ ]:
from semantica.context.methods import build_context_graph
from semantica.context.registry import method_registry

def custom_graph_method(entities, relationships, conversations=None, **kwargs):
    return {
        "nodes": [],
        "edges": [],
        "statistics": {"node_count": 0, "edge_count": 0},
    }

method_registry.register("graph", "custom_demo", custom_graph_method)
method_registry.list_all("graph")
In [ ]:
build_context_graph(
    entities=[{"id": "e1", "text": "Python", "type": "PROGRAMMING_LANGUAGE"}],
    relationships=[{"source_id": "e1", "target_id": "e2", "type": "related_to"}],
    method="custom_demo",
)