mirror of
https://github.com/semantica-agi/semantica.git
synced 2026-08-29 04:26:20 +00:00
16 KiB
16 KiB
In [ ]:
!pip install -qU semantica In [ ]:
import sys
import os
import time
from typing import Any, List, Dict, Optional
# Add project root to path to import semantica
sys.path.append(os.path.abspath(os.path.join(os.getcwd(), "../../")))
# Core Imports
from semantica.context import AgentContext, ContextGraph, AgentMemory
from semantica.vector_store import VectorStore
from semantica.graph_store import GraphStore
print("Libraries imported successfully.")In [ ]:
try:
# Initialize FAISS Vector Store
# You can also use: backend="weaviate", backend="qdrant", etc.
vs = VectorStore(backend="faiss", dimension=768)
print("VectorStore initialized (Backend: FAISS)")
except ImportError:
print("FAISS not installed. Using in-memory fallback (not persistent).")
vs = VectorStore(backend="inmemory", dimension=768)
except Exception as e:
print(f"VectorStore Error: {e}")
vs = NoneIn [ ]:
try:
# Initialize Neo4j Graph Store
# Ensure your Docker container is running!
gs = GraphStore(
backend="neo4j",
uri="bolt://localhost:7687",
user="neo4j",
password="password"
)
# Test connection
if gs.connect():
print("GraphStore connected (Backend: Neo4j)")
else:
raise ConnectionError("Could not connect to Neo4j")
except Exception as e:
print(f"GraphStore Connection Failed: {e}")
print(" Switching to in-memory ContextGraph (Non-persistent fallback)")
gs = ContextGraph() # Fallback implementationIn [ ]:
if vs:
context = AgentContext(
vector_store=vs,
knowledge_graph=gs,
retention_days=90, # Remember things for 3 months
use_graph_expansion=True, # Enable GraphRAG
max_expansion_hops=2, # 2-Hop reasoning
hybrid_alpha=0.6 # Balanced retrieval
)
print("Agent Context is online and ready.")
else:
print("Cannot proceed without VectorStore.")In [ ]:
user_id = "user_123"
session_id = "session_alpha"
# Store a user preference
mem_id = context.store(
content="I am working on a new project called 'Project Apollo' which uses Python and React.",
conversation_id=session_id,
user_id=user_id,
metadata={"type": "user_preference"}
)
print(f"Memory Stored: {mem_id}")In [ ]:
documents = [
{
"content": "Project Apollo is a next-gen web framework designed for high scalability.",
"metadata": {"source": "internal_wiki", "category": "projects"}
},
{
"content": "Python 3.12 introduces significant performance improvements for async workloads.",
"metadata": {"source": "tech_news", "category": "languages"}
}
]
# Store documents and trigger graph build
stats = context.store(
documents,
extract_entities=True, # Extract entities from text
extract_relationships=True, # Infer relationships
link_entities=True # Connect to existing graph nodes
)
print("Knowledge Ingestion Stats:", stats)In [ ]:
# 1. Define Nodes
entities = [
{"id": "alice", "type": "PERSON", "text": "Alice", "properties": {"role": "Admin"}},
{"id": "project_apollo", "type": "PROJECT", "text": "Project Apollo"},
{"id": "python", "type": "TECH", "text": "Python"},
{"id": "react", "type": "TECH", "text": "React"}
]
# 2. Define Edges (The Knowledge)
relationships = [
{"source": "alice", "target": "project_apollo", "type": "MANAGES", "weight": 1.0},
{"source": "project_apollo", "target": "python", "type": "USES_TECH", "weight": 1.0},
{"source": "project_apollo", "target": "react", "type": "USES_TECH", "weight": 1.0}
]
# 3. Inject into Graph
graph_stats = context.build_graph(
entities=entities,
relationships=relationships
)
print("Manual Graph Build Complete:", graph_stats)In [ ]:
# Helper to print graph neighbors
def inspect_node(node_id):
if hasattr(gs, "get_neighbors"):
neighbors = gs.get_neighbors(node_id)
print(f"\nNeighbors of '{node_id}':")
for n in neighbors:
# Handle different return formats between stores
rel_type = n.get('relationship') or n.get('type') or 'linked'
target = n.get('id') or n.get('node_id')
print(f" └── [{rel_type}] ──> {target}")
else:
print("Graph store does not support neighbor inspection.")
inspect_node("project_apollo")In [ ]:
query = "Who is responsible for the Python web framework project?"
print(f"Asking: '{query}'...\n")
results = context.retrieve(
query,
max_results=3,
use_graph=True, # Vital for finding Alice
expand_graph=True, # Hop to neighbors
include_entities=True # Return structured entity data
)
print(f"Retrieved {len(results)} context items:\n")
for i, res in enumerate(results, 1):
print(f"{i}. [Score: {res['score']:.2f}] {res['content'][:120]}...")
# Did we find graph connections?
if 'related_entities' in res and res['related_entities']:
print(" Graph Insights:")
for ent in res['related_entities'][:3]:
print(f" - {ent.get('text', 'Entity')} ({ent.get('type', 'Unknown')})")
print("")In [ ]:
# Get recent chat history for context window
history = context.conversation(
conversation_id=session_id,
limit=5
)
print(f"Chat History for {session_id}:")
for msg in history:
print(f" - {msg['content']}")In [ ]:
stats = context.stats()
print("System Vital Signs:")
print(f" - Total Memories: {stats.get('total_items', 0)}")
print(f" - Graph Nodes: {stats.get('graph_stats', {}).get('node_count', 'N/A')}")
print(f" - Graph Edges: {stats.get('graph_stats', {}).get('edge_count', 'N/A')}")