How to Add Nodes and Edges to a Semantica Context Graph: 3 Proven Methods

To add nodes and edges to a Semantica context graph, append entity dictionaries to the entities list and relationship dictionaries to the relationships list of the KnowledgeGraph class, or instantiate the class directly from a complete dictionary structure.

Semantica represents context graphs using the immutable-friendly KnowledgeGraph dataclass defined in semantica/kg/knowledge_graph.py. This lightweight structure stores entities as nodes and relationships as edges in plain Python collections, making it straightforward to incrementally build or batch-construct knowledge graphs for downstream AI components.

Understanding the KnowledgeGraph Structure

According to the source code in semantica/kg/knowledge_graph.py (lines 20-35), the KnowledgeGraph dataclass consists of three collections:

  • entities: A list of dictionaries, each containing at least an id and type field representing graph nodes.
  • relationships: A list of dictionaries, each containing source, target, and type fields representing directed edges between nodes.
  • metadata: An optional dictionary for graph-level annotations.

Because KnowledgeGraph is a thin wrapper around standard Python lists, you can mutate these collections directly or construct them upfront using dictionary unpacking.

Method 1: Incremental Construction

For dynamic graph building, instantiate an empty KnowledgeGraph and append entity and relationship dictionaries to their respective lists.

from semantica.kg.knowledge_graph import KnowledgeGraph

# Initialize empty graph

kg = KnowledgeGraph()

# Add nodes (entities)

kg.entities.append({
    "id": "person_1",
    "type": "Person",
    "name": "Alice"
})
kg.entities.append({
    "id": "company_1", 
    "type": "Organization",
    "name": "Acme Corp."
})

# Add edges (relationships)

kg.relationships.append({
    "source": "person_1",
    "target": "company_1",
    "type": "EMPLOYED_BY"
})

# Optional metadata

kg.metadata["created_at"] = "2024-09-04T12:00:00Z"

Each entity must include a unique id and a type, while relationships require source and target IDs matching existing entity IDs, plus a relationship type.

Method 2: Batch Construction from Dictionaries

For static or pre-computed graphs, build the structure as a plain dictionary and unpack it into KnowledgeGraph. This approach mirrors the test suite pattern found in tests/visualization/test_visualization_comprehensive.py (lines 63-70).

from semantica.kg.knowledge_graph import KnowledgeGraph

graph_dict = {
    "entities": [
        {"id": "node_a", "type": "Concept", "label": "AI"},
        {"id": "node_b", "type": "Concept", "label": "ML"}
    ],
    "relationships": [
        {"source": "node_a", "target": "node_b", "type": "RELATED_TO"}
    ],
    "metadata": {"source": "manual"}
}

# Direct instantiation

kg = KnowledgeGraph(**graph_dict)

This method is ideal when loading graphs from JSON files, databases, or API responses where the complete structure exists before instantiation.

Method 3: Integrating with AgentContext

Once populated, pass the KnowledgeGraph instance to AgentContext (defined in semantica/core/lifecycle.py) to make the graph available to visualizers, exporters, and other downstream tools.

from semantica.core.lifecycle import AgentContext
from semantica.kg.knowledge_graph import KnowledgeGraph

# Create graph with initial entities

kg = KnowledgeGraph(
    entities=[{"id": "doc_1", "type": "Document", "title": "Report"}],
    relationships=[]
)

# Inject into context

ctx = AgentContext(knowledge_graph=kg)

# The context enables downstream processing

# Visualizers at semantica/visualization/kg_visualizer.py can render ctx.knowledge_graph

The AgentContext holds the graph reference, allowing components like semantica/visualization/kg_visualizer.py to render network diagrams without additional conversion steps.

Summary

  • Append to lists: Add nodes by appending to kg.entities and edges by appending to kg.relationships for incremental construction.
  • Dict unpacking: Build graphs from raw dictionaries using KnowledgeGraph(**dict) for batch imports.
  • Required fields: Entities need id and type; relationships need source, target, and type.
  • Context integration: Pass completed graphs to AgentContext to enable visualization and agent processing.
  • Source location: Core implementation lives in semantica/kg/knowledge_graph.py with usage examples in tests/visualization/test_visualization_comprehensive.py.

Frequently Asked Questions

What fields are required when adding nodes to a Semantica context graph?

When adding nodes (entities), each dictionary must contain at least an id (unique identifier) and a type (classification). Additional fields like name or label are optional and depend on your specific use case or visualization requirements.

Can I modify a KnowledgeGraph after passing it to AgentContext?

Yes. Because KnowledgeGraph uses mutable Python lists for entities and relationships, you can continue appending nodes and edges even after the graph is passed to AgentContext. Changes reflect immediately in the context and any associated visualizers.

How do I visualize the graph after adding nodes and edges?

Pass the KnowledgeGraph instance to the visualization module located in semantica/visualization/kg_visualizer.py. The visualizer consumes the entities and relationships lists directly to render network diagrams, as demonstrated in the comprehensive test suite at tests/visualization/test_visualization_comprehensive.py.

Is KnowledgeGraph immutable or mutable?

While designed with "immutable-friendly" patterns, the KnowledgeGraph dataclass exposes mutable lists for entities and relationships. This allows both functional-style reconstruction and imperative appending, giving you flexibility in how you add nodes and edges to your Semantica context graph.

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 →