Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Refactor Context Module: Architecture 2.0, Hierarchical Memory, and Doc Updates

KaifAhmad1da08354a96f7
diff --git a/cookbook/advanced/11_Advanced_Context_Engineering.ipynb b/cookbook/advanced/11_Advanced_Context_Engineering.ipynb
new file mode 100644
index 00000000..b8100959
--- /dev/null
+++ b/cookbook/advanced/11_Advanced_Context_Engineering.ipynb
@@ -0,0 +1,247 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/advanced/11_Advanced_Context_Engineering.ipynb)\n",
+ "\n",
+ "# Advanced Context Engineering\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook covers advanced topics in context engineering using Semantica. We will explore custom memory management strategies, tuning hybrid retrieval, and extending the system with custom graph builders.\n",
+ "\n",
+ "### Learning Objectives\n",
+ "\n",
+ "- **Custom Memory Pruning**: Implement importance-based pruning instead of FIFO.\n",
+ "- **Hybrid Retrieval Tuning**: Optimize weights for vector, graph, and keyword search.\n",
+ "- **Custom Extensions**: Register custom graph building methods.\n",
+ "- **Performance Optimization**: Balance token limits and retrieval latency.\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## 1. Setup\n",
+ "\n",
+ "We'll start by setting up a mock vector store and importing necessary components."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from typing import List, Dict, Any, Optional\n",
+ "from semantica.context import AgentMemory, AgentContext, ContextGraph, ContextRetriever, VectorStore\n",
+ "from semantica.context import registry\n",
+ "\n",
+ "# Mock Vector Store (same as in introduction)\n",
+ "class MockVectorStore(VectorStore):\n",
+ " def __init__(self):\n",
+ " self.items = {}\n",
+ " self.counter = 0\n",
+ " def add(self, texts, metadata=None, **kwargs):\n",
+ " ids = []\n",
+ " for i, text in enumerate(texts):\n",
+ " id_ = f\"id_{self.counter}\"\n",
+ " self.items[id_] = {\"text\": text, \"metadata\": metadata[i] if metadata else {}}\n",
+ " ids.append(id_)\n",
+ " self.counter += 1\n",
+ " return ids\n",
+ " def search(self, query, limit=5, **kwargs):\n",
+ " return [{\n",
+ " \"id\": k, \"content\": v[\"text\"], \"score\": 0.85, \"metadata\": v[\"metadata\"]\n",
+ " } for k, v in list(self.items.items())[:limit]]\n",
+ " def delete(self, ids, **kwargs):\n",
+ " return True\n",
+ "\n",
+ "vs = MockVectorStore()\n",
+ "kg = ContextGraph()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Custom Memory Pruning Strategy\n",
+ "\n",
+ "By default, `AgentMemory` uses a FIFO (First-In-First-Out) strategy combined with a token limit to prune short-term memory. However, you might want to keep \"important\" memories longer regardless of their age.\n",
+ "\n",
+ "Let's subclass `AgentMemory` to implement an importance-based pruning strategy."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class ImportanceAwareMemory(AgentMemory):\n",
+ " def _prune_short_term_memory(self):\n",
+ " \"\"\"\n",
+ " Custom pruning: Always keep items marked as 'important' in metadata,\n",
+ " then prune others based on token limits.\n",
+ " \"\"\"\n",
+ " if not self.short_term_memory:\n",
+ " return\n",
+ "\n",
+ " # Separate important items\n",
+ " important_items = [item for item in self.short_term_memory if item.metadata.get(\"important\")]\n",
+ " other_items = [item for item in self.short_term_memory if not item.metadata.get(\"important\")]\n",
+ " \n",
+ " # Calculate tokens used by important items\n",
+ " important_tokens = sum(self._count_tokens(item.content) for item in important_items)\n",
+ " \n",
+ " # Calculate remaining budget\n",
+ " remaining_tokens = max(0, self.token_limit - important_tokens)\n",
+ " \n",
+ " # Prune other items to fit remaining budget\n",
+ " kept_others = []\n",
+ " current_tokens = 0\n",
+ " \n",
+ " # Iterate in reverse (newest first) to keep recent items\n",
+ " for item in reversed(other_items):\n",
+ " item_tokens = self._count_tokens(item.content)\n",
+ " if current_tokens + item_tokens <= remaining_tokens:\n",
+ " kept_others.insert(0, item)\n",
+ " current_tokens += item_tokens\n",
+ " else:\n",
+ " break # Stop once we hit the limit\n",
+ " \n",
+ " # Reconstruct memory: Important items + kept recent items\n",
+ " # Sort by timestamp to maintain order\n",
+ " all_kept = sorted(important_items + kept_others, key=lambda x: x.timestamp)\n",
+ " self.short_term_memory = all_kept\n",
+ "\n",
+ "# Test the custom memory\n",
+ "memory = ImportanceAwareMemory(vector_store=vs, token_limit=100)\n",
+ "\n",
+ "# Add an old important memory\n",
+ "memory.store(\"IMPORTANT: User's name is Alice\", metadata={\"important\": True})\n",
+ "\n",
+ "# Fill with filler memories\n",
+ "for i in range(20):\n",
+ " memory.store(f\"Filler memory {i} \" * 5) # Consumes tokens\n",
+ "\n",
+ "print(f\"Short-term items: {len(memory.short_term_memory)}\")\n",
+ "print(\"First item (should be the important one):\", memory.short_term_memory[0].content)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. Tuning Hybrid Retrieval\n",
+ "\n",
+ "Hybrid retrieval combines scores from vector search and graph traversal. You can tune the `hybrid_alpha` parameter to weight these components.\n",
+ "\n",
+ "- `hybrid_alpha = 0.0`: Pure Vector Search\n",
+ "- `hybrid_alpha = 1.0`: Pure Graph Search\n",
+ "- `hybrid_alpha = 0.5`: Balanced (Default)\n",
+ "\n",
+ "Additionally, `max_expansion_hops` controls how far we traverse the graph from retrieved nodes."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Populate graph with some structure\n",
+ "kg.add_node(\"python\", \"concept\", \"Python\")\n",
+ "kg.add_node(\"ml\", \"concept\", \"Machine Learning\")\n",
+ "kg.add_edge(\"python\", \"ml\", \"used_for\")\n",
+ "\n",
+ "retriever = ContextRetriever(\n",
+ " memory_store=memory,\n",
+ " knowledge_graph=kg,\n",
+ " vector_store=vs,\n",
+ " hybrid_alpha=0.7, # Favor graph connections\n",
+ " max_expansion_hops=2 # Traverse deeper\n",
+ ")\n",
+ "\n",
+ "results = retriever.retrieve(\"Python\")\n",
+ "for res in results:\n",
+ " print(f\"Source: {res.source}, Score: {res.score:.2f}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. Extending with Custom Methods\n",
+ "\n",
+ "Semantica's registry system allows you to plug in custom logic. Let's register a custom graph builder that creates a star graph topology."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def star_graph_builder(center_entity, satellites, **kwargs):\n",
+ " \"\"\"\n",
+ " Builds a star graph where all satellites connect to the center.\n",
+ " \"\"\"\n",
+ " nodes = []\n",
+ " edges = []\n",
+ " \n",
+ " # Center node\n",
+ " nodes.append({\"id\": \"center\", \"label\": center_entity, \"type\": \"CENTER\"})\n",
+ " \n",
+ " for i, sat in enumerate(satellites):\n",
+ " sat_id = f\"sat_{i}\"\n",
+ " nodes.append({\"id\": sat_id, \"label\": sat, \"type\": \"SATELLITE\"})\n",
+ " edges.append({\"source\": \"center\", \"target\": sat_id, \"relation\": \"connects_to\"})\n",
+ " \n",
+ " return {\"nodes\": nodes, \"edges\": edges}\n",
+ "\n",
+ "# Register the method\n",
+ "registry.method_registry.register(\"graph\", \"star_builder\", star_graph_builder)\n",
+ "\n",
+ "# Verify registration\n",
+ "print(\"Available graph methods:\", registry.method_registry.list_all(\"graph\"))\n",
+ "\n",
+ "# Use it (conceptual - typically used via build_context_graph wrapper)\n",
+ "graph_data = star_graph_builder(\"Central Hub\", [\"Spoke 1\", \"Spoke 2\"])\n",
+ "print(f\"Created graph with {len(graph_data['nodes'])} nodes and {len(graph_data['edges'])} edges.\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 5. Best Practices for Production\n",
+ "\n",
+ "1. **Token Limits**: Align `token_limit` with your LLM's context window minus the prompt template size.\n",
+ "2. **Vector Store**: Use a production-grade vector store (e.g., Pinecone, Weaviate, Qdrant) instead of the mock store.\n",
+ "3. **Asynchronous Operations**: For high-throughput systems, consider wrapping storage operations in async tasks (though the core logic is synchronous for simplicity).\n",
+ "4. **Entity Resolution**: Implement a robust `EntityLinker` strategy to prevent graph fragmentation (e.g., \"Alice\" vs \"Alice S.\")."
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.8.10"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/cookbook/introduction/19_Context_Module.ipynb b/cookbook/introduction/19_Context_Module.ipynb
index e06175a2..1c7da4b1 100644
--- a/cookbook/introduction/19_Context_Module.ipynb
+++ b/cookbook/introduction/19_Context_Module.ipynb
@@ -1,1872 +1,279 @@
{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/introduction/19_Context_Module.ipynb)\n",
- "\n",
- "# Context Engineering Module\n",
- "\n",
- "## Overview\n",
- "\n",
- "This notebook provides a comprehensive guide to Semantica's **Context Engineering Module** - a powerful system for building context graphs, managing agent memory, retrieving context, and linking entities. You'll learn how to use all classes, functions, and submodules to build intelligent agents with persistent memory and context awareness.\n",
- "\n",
- "**Documentation**: [API Reference](https://semantica.readthedocs.io/reference/context/)\n",
- "\n",
- "### Learning Objectives\n",
- "\n",
- "- **Context Graph Construction**: Build dynamic graphs from entities, relationships, and conversations\n",
- "- **Agent Memory Management**: Store and retrieve memories with RAG integration\n",
- "- **Context Retrieval**: Hybrid retrieval combining vector, graph, and memory search\n",
- "- **Entity Linking**: Link entities across documents with URI assignment\n",
- "- **Methods Submodule**: Use convenient functions for all context operations\n",
- "- **Registry System**: Register and use custom context methods\n",
- "- **Configuration**: Manage module settings and method configurations\n",
- "\n",
- "### Key Features\n",
- "\n",
- "- **Context Graphs**: Build graphs from multiple sources (entities, relationships, conversations)\n",
- "- **Agent Memory**: Persistent memory with vector store and knowledge graph integration\n",
- "- **Hybrid Retrieval**: Combine vector, graph, and keyword search for optimal context\n",
- "- **Entity Linking**: Link entities across documents with similarity and graph-based matching\n",
- "- **Method Registry**: Extensible system for custom context methods\n",
- "- **Configuration**: Flexible configuration via environment variables and config files\n",
- "\n",
- "---\n",
- "\n",
- "## Installation\n",
- "\n",
- "Install Semantica from PyPI:\n",
- "\n",
- "```bash\n",
- "pip install semantica\n",
- "# Or with all optional dependencies:\n",
- "pip install semantica[all]\n",
- "```\n",
- "\n",
- "---\n",
- "\n",
- "## Module Structure\n",
- "\n",
- "The context module is organized into:\n",
- "\n",
- "- **Main Classes**: `ContextGraphBuilder`, `AgentMemory`, `EntityLinker`, `ContextRetriever`, `AgentContext`\n",
- "- **Methods Submodule**: Convenient functions for all operations (`methods.build_context_graph`, etc.)\n",
- "- **Registry Submodule**: Method registry for custom methods (`registry.method_registry`)\n",
- "- **Config Submodule**: Configuration management (`config.context_config`)\n",
- "\n",
- "Let's explore each component in detail!\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 1: Imports and Setup\n",
- "\n",
- "First, let's import all the necessary components from the context module.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Import main classes\n",
- "from semantica.context import (\n",
- " AgentContext,\n",
- " ContextGraphBuilder,\n",
- " AgentMemory,\n",
- " EntityLinker,\n",
- " ContextRetriever,\n",
- " ContextNode,\n",
- " ContextEdge,\n",
- " MemoryItem,\n",
- " RetrievedContext\n",
- ")\n",
- "\n",
- "# Import submodules\n",
- "from semantica.context import methods, registry, config\n",
- "\n",
- "# Import methods functions\n",
- "from semantica.context.methods import (\n",
- " build_context_graph,\n",
- " store_memory,\n",
- " retrieve_context,\n",
- " link_entities,\n",
- " get_context_method,\n",
- " list_available_methods\n",
- ")\n",
- "\n",
- "print(\"All context module components imported successfully!\")\n",
- "print(f\"\\nAvailable methods: {list_available_methods()}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 2: Quick Start with AgentContext\n",
- "\n",
- "The `AgentContext` class provides a high-level, simplified interface for common use cases. It uses generic method names (`store`, `retrieve`, `forget`, `conversation`) that auto-detect content types and retrieval strategies.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 2.1 Simple RAG with AgentContext\n",
- "\n",
- "The simplest way to use the context module for RAG.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Initialize AgentContext with vector store\n",
- "context = AgentContext(vector_store=vs)\n",
- "\n",
- "# Store a memory\n",
- "memory_id = context.store(\n",
- " \"User likes Python programming and machine learning\",\n",
- " conversation_id=\"conv1\",\n",
- " user_id=\"user123\"\n",
- ")\n",
- "\n",
- "print(f\"Stored memory with ID: {memory_id}\")\n",
- "\n",
- "# Retrieve context\n",
- "results = context.retrieve(\n",
- " \"Python programming\",\n",
- " max_results=5,\n",
- " use_graph=False # Boolean flag: force vector-only retrieval\n",
- ")\n",
- "\n",
- "print(f\"\\nRetrieved {len(results)} results\")\n",
- "for i, result in enumerate(results, 1):\n",
- " print(f\"\\n{i}. Content: {result['content'][:60]}...\")\n",
- " print(f\" Score: {result['score']:.2f}\")\n",
- " print(f\" Source: {result['source']}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 2.2 GraphRAG with AgentContext\n",
- "\n",
- "Store documents and retrieve with graph context.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Initialize with vector store and knowledge graph\n",
- "context = AgentContext(\n",
- " vector_store=vs,\n",
- " knowledge_graph=kg,\n",
- " use_graph_expansion=True, # Boolean flag\n",
- " max_expansion_hops=2\n",
- ")\n",
- "\n",
- "# Store documents (auto-builds graph)\n",
- "documents = [\n",
- " \"Python is a programming language used for machine learning and data science\",\n",
- " \"TensorFlow and PyTorch are popular machine learning frameworks\",\n",
- " \"Machine learning involves training models on data to make predictions\"\n",
- "]\n",
- "\n",
- "stats = context.store(\n",
- " documents,\n",
- " extract_entities=True, # Boolean flag: extract entities\n",
- " extract_relationships=True, # Boolean flag: extract relationships\n",
- " link_entities=True # Boolean flag: link entities across documents\n",
- ")\n",
- "\n",
- "print(f\"Stored {stats['stored_count']} documents\")\n",
- "print(f\"Built graph with {stats['graph_nodes']} nodes and {stats['graph_edges']} edges\")\n",
- "\n",
- "# Retrieve with graph context (auto-detects GraphRAG)\n",
- "results = context.retrieve(\n",
- " \"Python machine learning\",\n",
- " max_results=5,\n",
- " use_graph=None, # Auto-detect (uses graph since knowledge_graph available)\n",
- " include_entities=True, # Boolean flag: include related entities\n",
- " include_relationships=False, # Boolean flag: don't include relationships\n",
- " expand_graph=True # Boolean flag: use graph expansion\n",
- ")\n",
- "\n",
- "print(f\"\\nRetrieved {len(results)} results with graph context\")\n",
- "for i, result in enumerate(results, 1):\n",
- " print(f\"\\n{i}. Content: {result['content'][:60]}...\")\n",
- " print(f\" Score: {result['score']:.2f}\")\n",
- " print(f\" Source: {result['source']}\")\n",
- " if result.get('related_entities'):\n",
- " print(f\" Related entities: {len(result['related_entities'])}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 2.3 Conversation Management with AgentContext\n",
- "\n",
- "Manage conversation history easily.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "context = AgentContext(vector_store=vs, retention_days=30)\n",
- "\n",
- "# Store multiple memories in a conversation\n",
- "context.store(\"Hello, I'm interested in Python\", conversation_id=\"conv1\", user_id=\"user123\")\n",
- "context.store(\"What can you tell me about machine learning?\", conversation_id=\"conv1\", user_id=\"user123\")\n",
- "context.store(\"I prefer TensorFlow over PyTorch\", conversation_id=\"conv1\", user_id=\"user123\")\n",
- "\n",
- "# Get conversation history\n",
- "history = context.conversation(\n",
- " \"conv1\",\n",
- " reverse=True, # Boolean flag: most recent first\n",
- " include_metadata=True # Boolean flag: include full metadata\n",
- ")\n",
- "\n",
- "print(f\"Retrieved {len(history)} items from conversation\")\n",
- "for item in history:\n",
- " print(f\" - {item.get('timestamp', 'N/A')}: {item['content']}\")\n",
- "\n",
- "# Retrieve context from conversation\n",
- "results = context.retrieve(\n",
- " \"Python\",\n",
- " conversation_id=\"conv1\", # Filter by conversation\n",
- " max_results=3\n",
- ")\n",
- "\n",
- "print(f\"\\nRetrieved {len(results)} results from conversation\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 2.4 Additional Memory Management Methods\n",
- "\n",
- "AgentContext provides many additional methods for memory management, search, and analytics.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Memory Management Methods\n",
- "print(\"=== Memory Management ===\")\n",
- "\n",
- "# Check if memory exists\n",
- "exists = context.exists(memory_id) if memory_id else False\n",
- "print(f\"Memory exists: {exists}\")\n",
- "\n",
- "# Get memory count\n",
- "total = context.count()\n",
- "conv_count = context.count(conversation_id=\"conv1\")\n",
- "print(f\"Total memories: {total}, Conversation memories: {conv_count}\")\n",
- "\n",
- "# Get memory by ID\n",
- "if memory_id:\n",
- " memory = context.get(memory_id)\n",
- " if memory:\n",
- " print(f\"Retrieved memory: {memory['content'][:50]}...\")\n",
- "\n",
- "# Update memory\n",
- "# context.update(memory_id, content=\"Updated content\", metadata={\"key\": \"value\"})\n",
- "\n",
- "# List memories with pagination\n",
- "memories = context.list(conversation_id=\"conv1\", limit=10, offset=0)\n",
- "print(f\"Listed {len(memories)} memories\")\n",
- "\n",
- "# Batch operations\n",
- "# ids = context.batch_store([\"Item 1\", \"Item 2\", \"Item 3\"])\n",
- "# deleted = context.batch_delete([\"mem1\", \"mem2\"])\n",
- "\n",
- "# Search Methods\n",
- "print(\"\\n=== Search Methods ===\")\n",
- "results = context.search(\"Python\", max_results=5)\n",
- "similar = context.find_similar(\"Python programming\", limit=5)\n",
- "context_data = context.get_context(\"Python\", max_results=5)\n",
- "print(f\"Search results: {len(results)}, Similar: {len(similar)}, Context: {len(context_data)}\")\n",
- "\n",
- "# Conversation Methods\n",
- "print(\"\\n=== Conversation Methods ===\")\n",
- "conversations = context.list_conversations(user_id=\"user123\", limit=50)\n",
- "summary = context.conversation_summary(\"conv1\")\n",
- "print(f\"Conversations: {len(conversations)}, Summary: {summary.get('message_count', 0)} messages\")\n",
- "\n",
- "# Export/Import\n",
- "print(\"\\n=== Export/Import ===\")\n",
- "# backup_data = context.backup()\n",
- "# restored = context.restore(backup_data)\n",
- "\n",
- "# Statistics\n",
- "print(\"\\n=== Statistics ===\")\n",
- "stats = context.stats()\n",
- "health = context.health()\n",
- "usage = context.usage_stats(period='day')\n",
- "print(f\"Stats: {stats.get('total_items', 0)} items\")\n",
- "print(f\"Health: {health['status']}\")\n",
- "print(f\"Usage: {usage.get('recent_memories', 0)} recent memories\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Step 3: Context Graph Construction\n",
- "\n",
- "The `ContextGraphBuilder` class allows you to build context graphs from various sources. Let's explore different ways to construct graphs.\n",
- "\n",
- "### 3.1 Building from Entities and Relationships\n",
- "\n",
- "The most straightforward way to build a context graph is from entities and relationships.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Initialize the builder\n",
- "builder = ContextGraphBuilder()\n",
- "\n",
- "# Define entities\n",
- "entities = [\n",
- " {\"id\": \"e1\", \"text\": \"Python\", \"type\": \"PROGRAMMING_LANGUAGE\", \"confidence\": 0.95},\n",
- " {\"id\": \"e2\", \"text\": \"Machine Learning\", \"type\": \"CONCEPT\", \"confidence\": 0.9},\n",
- " {\"id\": \"e3\", \"text\": \"TensorFlow\", \"type\": \"FRAMEWORK\", \"confidence\": 0.92},\n",
- " {\"id\": \"e4\", \"text\": \"PyTorch\", \"type\": \"FRAMEWORK\", \"confidence\": 0.91},\n",
- "]\n",
- "\n",
- "# Define relationships\n",
- "relationships = [\n",
- " {\"source_id\": \"e1\", \"target_id\": \"e2\", \"type\": \"used_for\", \"confidence\": 0.9},\n",
- " {\"source_id\": \"e3\", \"target_id\": \"e2\", \"type\": \"implements\", \"confidence\": 0.95},\n",
- " {\"source_id\": \"e4\", \"target_id\": \"e2\", \"type\": \"implements\", \"confidence\": 0.94},\n",
- " {\"source_id\": \"e3\", \"target_id\": \"e1\", \"type\": \"built_with\", \"confidence\": 0.88},\n",
- " {\"source_id\": \"e4\", \"target_id\": \"e1\", \"type\": \"built_with\", \"confidence\": 0.87},\n",
- "]\n",
- "\n",
- "# Build the graph\n",
- "graph = builder.build_from_entities_and_relationships(entities, relationships)\n",
- "\n",
- "print(f\"Graph built successfully!\")\n",
- "print(f\"Statistics:\")\n",
- "print(f\" - Nodes: {graph['statistics']['node_count']}\")\n",
- "print(f\" - Edges: {graph['statistics']['edge_count']}\")\n",
- "print(f\" - Node types: {list(graph['statistics']['node_types'].keys())}\")\n",
- "print(f\" - Edge types: {list(graph['statistics']['edge_types'].keys())}\")\n",
- "\n",
- "# Display some nodes\n",
- "print(f\"\\nSample Nodes:\")\n",
- "for node_id, node_data in list(graph['nodes'].items())[:3]:\n",
- " print(f\" - {node_id}: {node_data['text']} ({node_data['type']})\")\n",
- "\n",
- "# Display some edges\n",
- "print(f\"\\nSample Edges:\")\n",
- "for edge in list(graph['edges'])[:3]:\n",
- " print(f\" - {edge['source_id']} --[{edge['type']}]--> {edge['target_id']}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 3.2 Building from Conversations\n",
- "\n",
- "You can also build graphs from conversation data, which automatically extracts entities, relationships, intents, and sentiments.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Define conversations\n",
- "conversations = [\n",
- " {\n",
- " \"id\": \"conv1\",\n",
- " \"content\": \"User asked about Python programming and machine learning\",\n",
- " \"timestamp\": \"2024-01-01T10:00:00\",\n",
- " \"entities\": [\n",
- " {\"id\": \"e1\", \"text\": \"Python\", \"type\": \"PROGRAMMING_LANGUAGE\"},\n",
- " {\"id\": \"e2\", \"text\": \"Machine Learning\", \"type\": \"CONCEPT\"}\n",
- " ],\n",
- " \"relationships\": [\n",
- " {\"source_id\": \"e1\", \"target_id\": \"e2\", \"type\": \"used_for\"}\n",
- " ]\n",
- " },\n",
- " {\n",
- " \"id\": \"conv2\",\n",
- " \"content\": \"User asked about TensorFlow and PyTorch frameworks\",\n",
- " \"timestamp\": \"2024-01-01T11:00:00\",\n",
- " \"entities\": [\n",
- " {\"id\": \"e3\", \"text\": \"TensorFlow\", \"type\": \"FRAMEWORK\"},\n",
- " {\"id\": \"e4\", \"text\": \"PyTorch\", \"type\": \"FRAMEWORK\"}\n",
- " ],\n",
- " \"relationships\": [\n",
- " {\"source_id\": \"e3\", \"target_id\": \"e4\", \"type\": \"related_to\"}\n",
- " ]\n",
- " }\n",
- "]\n",
- "\n",
- "# Build graph from conversations with additional features\n",
- "graph = builder.build_from_conversations(\n",
- " conversations,\n",
- " link_entities=True, # Link similar entities across conversations\n",
- " extract_intents=True, # Extract conversation intents\n",
- " extract_sentiments=True # Extract sentiment information\n",
- ")\n",
- "\n",
- "print(f\"Graph built from {len(conversations)} conversations!\")\n",
- "print(f\"Statistics:\")\n",
- "print(f\" - Nodes: {graph['statistics']['node_count']}\")\n",
- "print(f\" - Edges: {graph['statistics']['edge_count']}\")\n",
- "print(f\" - Conversations processed: {len(conversations)}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 3.3 Additional Graph Construction Methods\n",
- "\n",
- "ContextGraphBuilder provides high-level methods for easy graph construction.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# High-level construction methods\n",
- "builder = ContextGraphBuilder()\n",
- "\n",
- "# Build from text\n",
- "graph = builder.from_text(\"Python is used for machine learning\")\n",
- "print(f\"From text: {graph.get('statistics', {}).get('node_count', 0)} nodes\")\n",
- "\n",
- "# Build from documents\n",
- "docs = [\"Doc 1 about Python\", \"Doc 2 about ML\"]\n",
- "graph = builder.from_documents(docs)\n",
- "print(f\"From documents: {graph.get('statistics', {}).get('node_count', 0)} nodes\")\n",
- "\n",
- "# Simple add method\n",
- "stats = builder.add(entities=entities, relationships=relationships)\n",
- "print(f\"Add method: {stats.get('node_count', 0)} nodes, {stats.get('edge_count', 0)} edges\")\n",
- "\n",
- "# Query methods\n",
- "results = builder.find(\"Python\")\n",
- "node = builder.find_node(\"e1\")\n",
- "nodes = builder.find_nodes(node_type=\"PROGRAMMING_LANGUAGE\")\n",
- "edges = builder.find_edges(edge_type=\"used_for\")\n",
- "path = builder.find_path(\"e1\", \"e2\", max_hops=5)\n",
- "\n",
- "print(f\"\\nQuery results:\")\n",
- "print(f\" Find: {len(results)} results\")\n",
- "print(f\" Find node: {node is not None}\")\n",
- "print(f\" Find nodes: {len(nodes)} nodes\")\n",
- "print(f\" Find edges: {len(edges)} edges\")\n",
- "print(f\" Find path: {len(path)} nodes in path\")\n",
- "\n",
- "# Graph operations\n",
- "subgraph = builder.get_subgraph([\"e1\", \"e2\"])\n",
- "cloned = builder.clone()\n",
- "stats = builder.stats()\n",
- "node_count = builder.node_count(node_type=\"PROGRAMMING_LANGUAGE\")\n",
- "edge_count = builder.edge_count(edge_type=\"used_for\")\n",
- "density = builder.density()\n",
- "\n",
- "print(f\"\\nGraph operations:\")\n",
- "print(f\" Subgraph: {subgraph.get('statistics', {}).get('node_count', 0)} nodes\")\n",
- "print(f\" Cloned: {cloned.stats().get('node_count', 0)} nodes\")\n",
- "print(f\" Stats: {stats.get('node_count', 0)} nodes, {stats.get('edge_count', 0)} edges\")\n",
- "print(f\" Node count: {node_count}\")\n",
- "print(f\" Edge count: {edge_count}\")\n",
- "print(f\" Density: {density:.3f}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 4: Agent Memory Management\n",
- "\n",
- "The `AgentMemory` class provides persistent memory for agents with RAG integration. It stores memories with vector embeddings and integrates with knowledge graphs.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 4.1 Initializing Agent Memory\n",
- "\n",
- "First, we need to set up a vector store and knowledge graph. For demonstration, we'll use mock objects.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Note: In a real scenario, you would use actual vector store and knowledge graph instances\n",
- "# For demonstration, we'll create mock objects\n",
- "\n",
- "class MockVectorStore:\n",
- " \"\"\"Mock vector store for demonstration.\"\"\"\n",
- " def __init__(self):\n",
- " self.vectors = {}\n",
- " self.metadata = {}\n",
- " \n",
- " def add(self, ids, embeddings, metadatas=None):\n",
- " for i, id_val in enumerate(ids):\n",
- " self.vectors[id_val] = embeddings[i]\n",
- " if metadatas:\n",
- " self.metadata[id_val] = metadatas[i]\n",
- " \n",
- " def query(self, query_embeddings, n_results=5, where=None):\n",
- " # Simplified mock query\n",
- " results = []\n",
- " for i, (id_val, vector) in enumerate(list(self.vectors.items())[:n_results]):\n",
- " results.append({\n",
- " 'id': id_val,\n",
- " 'score': 0.9 - i * 0.1,\n",
- " 'metadata': self.metadata.get(id_val, {})\n",
- " })\n",
- " return {'ids': [[r['id'] for r in results]], 'metadatas': [[r['metadata'] for r in results]]}\n",
- "\n",
- "class MockKnowledgeGraph:\n",
- " \"\"\"Mock knowledge graph for demonstration.\"\"\"\n",
- " def __init__(self):\n",
- " self.entities = {}\n",
- " self.relationships = []\n",
- " self.nodes = []\n",
- " self.edges = []\n",
- " \n",
- " def add_entity(self, entity_id, entity_data):\n",
- " self.entities[entity_id] = entity_data\n",
- " \n",
- " def add_relationship(self, source, target, rel_type):\n",
- " self.relationships.append({\n",
- " 'source_id': source,\n",
- " 'target_id': target,\n",
- " 'type': rel_type\n",
- " })\n",
- "\n",
- "# Initialize mock stores\n",
- "vs = MockVectorStore()\n",
- "kg = MockKnowledgeGraph()\n",
- "\n",
- "# Initialize AgentMemory\n",
- "memory = AgentMemory(\n",
- " vector_store=vs,\n",
- " knowledge_graph=kg,\n",
- " retention_policy=\"30_days\", # Keep memories for 30 days\n",
- " max_memory_size=10000 # Maximum number of memories\n",
- ")\n",
- "\n",
- "print(\"AgentMemory initialized successfully!\")\n",
- "print(f\"Configuration:\")\n",
- "print(f\" - Retention policy: 30_days\")\n",
- "print(f\" - Max memory size: 10000\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 4.2 Storing Memories\n",
- "\n",
- "Store memories with metadata and associated entities.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Store a memory with metadata\n",
- "memory_id = memory.store(\n",
- " \"User asked about Python programming and machine learning\",\n",
- " metadata={\n",
- " \"type\": \"conversation\",\n",
- " \"conversation_id\": \"conv_123\",\n",
- " \"user_id\": \"user_456\",\n",
- " \"timestamp\": \"2024-01-01T10:00:00\"\n",
- " },\n",
- " entities=[\n",
- " {\"id\": \"e1\", \"text\": \"Python\", \"type\": \"PROGRAMMING_LANGUAGE\"},\n",
- " {\"id\": \"e2\", \"text\": \"Machine Learning\", \"type\": \"CONCEPT\"}\n",
- " ]\n",
- ")\n",
- "\n",
- "print(f\"Memory stored with ID: {memory_id}\")\n",
- "\n",
- "# Store another memory\n",
- "memory_id_2 = memory.store(\n",
- " \"User asked about TensorFlow framework for deep learning\",\n",
- " metadata={\n",
- " \"type\": \"conversation\",\n",
- " \"conversation_id\": \"conv_124\",\n",
- " \"user_id\": \"user_456\"\n",
- " },\n",
- " entities=[\n",
- " {\"id\": \"e3\", \"text\": \"TensorFlow\", \"type\": \"FRAMEWORK\"},\n",
- " {\"id\": \"e2\", \"text\": \"Deep Learning\", \"type\": \"CONCEPT\"}\n",
- " ]\n",
- ")\n",
- "\n",
- "print(f\"Second memory stored with ID: {memory_id_2}\")\n",
- "\n",
- "# Get statistics\n",
- "stats = memory.get_statistics()\n",
- "print(f\"\\nMemory Statistics:\")\n",
- "print(f\" - Total items: {stats['total_items']}\")\n",
- "print(f\" - Items by type: {stats.get('items_by_type', {})}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 4.3 Additional Memory Management Methods\n",
- "\n",
- "AgentMemory provides many additional methods for memory operations.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Basic operations\n",
- "print(\"=== Basic Operations ===\")\n",
- "exists = memory.exists(memory_id) if memory_id else False\n",
- "count = memory.count()\n",
- "mem = memory.get(memory_id) if memory_id else None\n",
- "print(f\"Exists: {exists}, Count: {count}, Retrieved: {mem is not None}\")\n",
- "\n",
- "# Search methods\n",
- "print(\"\\n=== Search Methods ===\")\n",
- "results = memory.search(\"Python\", max_results=5)\n",
- "similar = memory.find_similar(\"Python programming\", limit=5)\n",
- "by_entity = memory.find_by_entity(\"e1\", limit=10)\n",
- "by_relationship = memory.find_by_relationship(\"used_for\", limit=10)\n",
- "print(f\"Search: {len(results)}, Similar: {len(similar)}, By entity: {len(by_entity)}, By relationship: {len(by_relationship)}\")\n",
- "\n",
- "# List and filter methods\n",
- "print(\"\\n=== List and Filter Methods ===\")\n",
- "memories = memory.list(conversation_id=\"conv_123\", limit=10)\n",
- "conv_memories = memory.get_by_conversation(\"conv_123\", limit=100)\n",
- "user_memories = memory.get_by_user(\"user_456\", limit=100)\n",
- "recent = memory.get_recent(limit=10)\n",
- "print(f\"List: {len(memories)}, Conversation: {len(conv_memories)}, User: {len(user_memories)}, Recent: {len(recent)}\")\n",
- "\n",
- "# Batch operations\n",
- "print(\"\\n=== Batch Operations ===\")\n",
- "# ids = memory.batch_store([\"Item 1\", \"Item 2\"])\n",
- "# deleted = memory.batch_delete([\"mem1\", \"mem2\"])\n",
- "# updated = memory.batch_update([{\"memory_id\": \"mem1\", \"content\": \"New\"}])\n",
- "\n",
- "# Statistics\n",
- "print(\"\\n=== Statistics ===\")\n",
- "stats = memory.stats()\n",
- "type_counts = memory.count_by_type()\n",
- "user_counts = memory.count_by_user()\n",
- "conv_counts = memory.count_by_conversation()\n",
- "print(f\"Stats: {stats.get('total_items', 0)} items\")\n",
- "print(f\"By type: {type_counts}\")\n",
- "print(f\"By user: {user_counts}\")\n",
- "print(f\"By conversation: {conv_counts}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 4.4 Conversation History\n",
- "\n",
- "Retrieve conversation history for a specific conversation.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Get conversation history\n",
- "history = memory.get_conversation_history(\n",
- " conversation_id=\"conv_123\",\n",
- " max_items=100\n",
- ")\n",
- "\n",
- "print(f\"Retrieved {len(history)} items from conversation history\")\n",
- "for item in history:\n",
- " print(f\" - {item.get('timestamp', 'N/A')}: {item.get('content', '')[:50]}...\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 4.5 Memory Management\n",
- "\n",
- "Delete and manage memories with various filters.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Delete a specific memory\n",
- "if memory_id_2:\n",
- " memory.delete(memory_id_2)\n",
- " print(f\"Deleted memory: {memory_id_2}\")\n",
- "\n",
- "# Clear memories by filters\n",
- "deleted_count = memory.clear(\n",
- " type=\"conversation\",\n",
- " start_date=\"2024-01-01\",\n",
- " end_date=\"2024-12-31\"\n",
- ")\n",
- "\n",
- "print(f\"Cleared {deleted_count} memories matching filters\")\n",
- "\n",
- "# Get updated statistics\n",
- "stats = memory.get_statistics()\n",
- "print(f\"\\nUpdated Statistics:\")\n",
- "print(f\" - Total items: {stats['total_items']}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 5: Context Retrieval\n",
- "\n",
- "The `ContextRetriever` class provides hybrid context retrieval combining vector search, graph traversal, and memory search.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 5.1 Basic Context Retrieval\n",
- "\n",
- "Initialize and use the context retriever for hybrid retrieval.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Initialize ContextRetriever\n",
- "retriever = ContextRetriever(\n",
- " memory_store=memory,\n",
- " knowledge_graph=kg,\n",
- " vector_store=vs,\n",
- " use_graph_expansion=True, # Enable graph expansion for related entities\n",
- " max_expansion_hops=2 # Maximum hops for graph expansion\n",
- ")\n",
- "\n",
- "# Retrieve context\n",
- "results = retriever.retrieve(\n",
- " \"Python programming\",\n",
- " max_results=5,\n",
- " min_relevance_score=0.5\n",
- ")\n",
- "\n",
- "print(f\"Retrieved {len(results)} context items\")\n",
- "print(f\"\\nResults:\")\n",
- "for i, result in enumerate(results, 1):\n",
- " print(f\"\\n{i}. Content: {result.content[:60]}...\")\n",
- " print(f\" Score: {result.score:.2f}\")\n",
- " print(f\" Source: {result.source}\")\n",
- " print(f\" Related entities: {len(result.related_entities)}\")\n",
- " if result.related_entities:\n",
- " print(f\" - {', '.join([e.get('content', '') for e in result.related_entities[:3]])}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 5.2 Additional Retrieval Methods\n",
- "\n",
- "ContextRetriever provides many additional methods for different retrieval strategies.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Search methods\n",
- "print(\"=== Search Methods ===\")\n",
- "results = retriever.search(\"Python\", max_results=5)\n",
- "vector_results = retriever.vector_search(\"Python\")\n",
- "graph_results = retriever.graph_search(\"Python\")\n",
- "memory_results = retriever.memory_search(\"Python\")\n",
- "hybrid_results = retriever.hybrid_search(\"Python\")\n",
- "print(f\"Search: {len(results)}, Vector: {len(vector_results)}, Graph: {len(graph_results)}, Memory: {len(memory_results)}, Hybrid: {len(hybrid_results)}\")\n",
- "\n",
- "# Advanced retrieval\n",
- "print(\"\\n=== Advanced Retrieval ===\")\n",
- "similar = retriever.find_similar(\"Python programming\", limit=5)\n",
- "context = retriever.get_context(\"Python\", max_results=5)\n",
- "expanded = retriever.expand_query(\"Python\", max_hops=2)\n",
- "related = retriever.get_related(\"e1\", max_hops=2) if hasattr(kg, 'nodes') else []\n",
- "path = retriever.get_path(\"e1\", \"e2\", max_hops=5) if hasattr(kg, 'nodes') else []\n",
- "print(f\"Similar: {len(similar)}, Context: {len(context)}, Expanded: {len(expanded)}, Related: {len(related)}, Path: {len(path)}\")\n",
- "\n",
- "# Filter methods\n",
- "print(\"\\n=== Filter Methods ===\")\n",
- "# by_entity = retriever.filter_by_entity(\"e1\", \"Python\")\n",
- "# by_type = retriever.filter_by_type(\"PROGRAMMING_LANGUAGE\", \"Python\")\n",
- "# by_date = retriever.filter_by_date(\"2024-01-01\", \"2024-12-31\", \"Python\")\n",
- "# by_score = retriever.filter_by_score(0.7, \"Python\")\n",
- "\n",
- "# Batch operations\n",
- "print(\"\\n=== Batch Operations ===\")\n",
- "# batch_results = retriever.batch_search([\"Python\", \"Java\", \"C++\"])\n",
- "# batch_contexts = retriever.batch_get_context([\"Python\", \"Java\"], max_results=5)\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Step 6: Entity Linking\n",
- "\n",
- "The `EntityLinker` class links entities across documents with URI assignment and similarity matching.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 6.1 Basic Entity Linking\n",
- "\n",
- "Link entities in text and assign URIs.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Initialize EntityLinker\n",
- "linker = EntityLinker(\n",
- " knowledge_graph=kg,\n",
- " similarity_threshold=0.8,\n",
- " base_uri=\"https://semantica.dev/entity/\"\n",
- ")\n",
- "\n",
- "# Assign URI to an entity\n",
- "uri = linker.assign_uri(\n",
- " \"entity_1\",\n",
- " \"Python\",\n",
- " \"PROGRAMMING_LANGUAGE\"\n",
- ")\n",
- "print(f\"Assigned URI: {uri}\")\n",
- "\n",
- "# Link entities in text\n",
- "entities = [\n",
- " {\"id\": \"e1\", \"text\": \"Python\", \"type\": \"PROGRAMMING_LANGUAGE\"},\n",
- " {\"id\": \"e2\", \"text\": \"Machine Learning\", \"type\": \"CONCEPT\"},\n",
- "]\n",
- "\n",
- "linked_entities = linker.link(\n",
- " \"Python is used for machine learning\",\n",
- " entities=entities\n",
- ")\n",
- "\n",
- "print(f\"\\nLinked {len(linked_entities)} entities\")\n",
- "for entity in linked_entities:\n",
- " print(f\" - {entity.text}: {entity.uri}\")\n",
- " print(f\" Linked to {len(entity.linked_entities)} entities\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 6.2 Additional Entity Linking Methods\n",
- "\n",
- "EntityLinker provides many additional methods for linking and searching entities.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Create explicit link between entities\n",
- "linker.link_entities(\n",
- " \"entity_1\",\n",
- " \"entity_2\",\n",
- " link_type=\"related_to\",\n",
- " confidence=0.9,\n",
- " source=\"manual\"\n",
- ")\n",
- "\n",
- "# Get entity links\n",
- "links = linker.get_entity_links(\"entity_1\")\n",
- "print(f\"✅ Found {len(links)} links for entity_1\")\n",
- "for link in links:\n",
- " print(f\" - {link.source_entity_id} --[{link.link_type}]--> {link.target_entity_id}\")\n",
- "\n",
- "# Get entity URI\n",
- "uri = linker.get_entity_uri(\"entity_1\")\n",
- "if uri:\n",
- " print(f\"\\n✅ Entity URI: {uri}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 5.3 Finding Similar Entities\n",
- "\n",
- "Find similar entities using similarity matching.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Find similar entities\n",
- "similar = linker.find_similar_entities(\n",
- " \"Python\",\n",
- " entity_type=\"PROGRAMMING_LANGUAGE\",\n",
- " threshold=0.8\n",
- ")\n",
- "\n",
- "print(f\"✅ Found {len(similar)} similar entities\")\n",
- "for entity_id, similarity in similar:\n",
- " print(f\" - {entity_id}: {similarity:.2f} similarity\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 5.4 Building Entity Web\n",
- "\n",
- "Build a complete entity web showing all connections.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Link multiple entities\n",
- "linker.link_entities(\"e1\", \"e2\", \"related_to\", confidence=0.9)\n",
- "linker.link_entities(\"e2\", \"e3\", \"related_to\", confidence=0.85)\n",
- "\n",
- "# Build entity web\n",
- "web = linker.build_entity_web()\n",
- "\n",
- "print(f\"✅ Entity Web Statistics:\")\n",
- "print(f\" - Total entities: {web['statistics']['total_entities']}\")\n",
- "print(f\" - Total links: {web['statistics']['total_links']}\")\n",
- "\n",
- "for entity_id, info in list(web['entities'].items())[:5]:\n",
- " print(f\"\\n Entity {entity_id}:\")\n",
- " print(f\" - URI: {info.get('uri', 'N/A')}\")\n",
- " print(f\" - Links: {info.get('links', 0)}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 🎯 Step 6: Methods Submodule\n",
- "\n",
- "The `methods` submodule provides convenient functions for all context operations. These functions use the method registry system and support multiple algorithms.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 6.1 Building Context Graphs with Methods\n",
- "\n",
- "Use the `build_context_graph` function with different methods.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Build from entities and relationships\n",
- "graph = methods.build_context_graph(\n",
- " entities=entities,\n",
- " relationships=relationships,\n",
- " method=\"entities_relationships\"\n",
- ")\n",
- "\n",
- "print(f\"✅ Built graph using 'entities_relationships' method\")\n",
- "print(f\" - Nodes: {graph['statistics']['node_count']}\")\n",
- "print(f\" - Edges: {graph['statistics']['edge_count']}\")\n",
- "\n",
- "# Build from conversations\n",
- "graph = methods.build_context_graph(\n",
- " conversations=conversations,\n",
- " method=\"conversations\"\n",
- ")\n",
- "\n",
- "print(f\"\\n✅ Built graph using 'conversations' method\")\n",
- "print(f\" - Nodes: {graph['statistics']['node_count']}\")\n",
- "\n",
- "# Hybrid construction\n",
- "graph = methods.build_context_graph(\n",
- " entities=entities,\n",
- " relationships=relationships,\n",
- " conversations=conversations,\n",
- " method=\"hybrid\"\n",
- ")\n",
- "\n",
- "print(f\"\\n✅ Built graph using 'hybrid' method\")\n",
- "print(f\" - Nodes: {graph['statistics']['node_count']}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 6.2 Storing Memories with Methods\n",
- "\n",
- "Use the `store_memory` function with different storage methods.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Store memory using method\n",
- "memory_id = methods.store_memory(\n",
- " \"User asked about Python programming\",\n",
- " vector_store=vs,\n",
- " knowledge_graph=kg,\n",
- " method=\"store\",\n",
- " metadata={\"type\": \"conversation\"}\n",
- ")\n",
- "\n",
- "print(f\"✅ Stored memory with ID: {memory_id}\")\n",
- "\n",
- "# Store conversation memory\n",
- "memory_id = methods.store_memory(\n",
- " \"User asked about machine learning frameworks\",\n",
- " vector_store=vs,\n",
- " knowledge_graph=kg,\n",
- " method=\"conversation\",\n",
- " metadata={\"conversation_id\": \"conv_125\"}\n",
- ")\n",
- "\n",
- "print(f\"✅ Stored conversation memory with ID: {memory_id}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 6.3 Retrieving Context with Methods\n",
- "\n",
- "Use the `retrieve_context` function with different retrieval methods.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Vector-based retrieval only\n",
- "results = methods.retrieve_context(\n",
- " \"Python programming\",\n",
- " vector_store=vs,\n",
- " method=\"vector\",\n",
- " max_results=5\n",
- ")\n",
- "print(f\"✅ Vector retrieval: {len(results)} results\")\n",
- "\n",
- "# Graph-based retrieval only\n",
- "results = methods.retrieve_context(\n",
- " \"Python programming\",\n",
- " knowledge_graph=kg,\n",
- " method=\"graph\",\n",
- " max_results=5\n",
- ")\n",
- "print(f\"✅ Graph retrieval: {len(results)} results\")\n",
- "\n",
- "# Memory-based retrieval only\n",
- "results = methods.retrieve_context(\n",
- " \"Python programming\",\n",
- " memory_store=memory,\n",
- " method=\"memory\",\n",
- " max_results=5\n",
- ")\n",
- "print(f\"✅ Memory retrieval: {len(results)} results\")\n",
- "\n",
- "# Hybrid retrieval (all sources)\n",
- "results = methods.retrieve_context(\n",
- " \"Python programming\",\n",
- " memory_store=memory,\n",
- " knowledge_graph=kg,\n",
- " vector_store=vs,\n",
- " method=\"hybrid\",\n",
- " max_results=5\n",
- ")\n",
- "print(f\"✅ Hybrid retrieval: {len(results)} results\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 6.4 Linking Entities with Methods\n",
- "\n",
- "Use the `link_entities` function with different linking methods.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# URI assignment only\n",
- "linked = methods.link_entities(\n",
- " entities,\n",
- " method=\"uri\"\n",
- ")\n",
- "print(f\"✅ URI linking: {len(linked)} entities linked\")\n",
- "\n",
- "# Similarity-based linking\n",
- "linked = methods.link_entities(\n",
- " entities,\n",
- " knowledge_graph=kg,\n",
- " method=\"similarity\"\n",
- ")\n",
- "print(f\"✅ Similarity linking: {len(linked)} entities linked\")\n",
- "\n",
- "# Knowledge graph-based linking\n",
- "linked = methods.link_entities(\n",
- " entities,\n",
- " knowledge_graph=kg,\n",
- " method=\"knowledge_graph\"\n",
- ")\n",
- "print(f\"✅ Knowledge graph linking: {len(linked)} entities linked\")\n",
- "\n",
- "# Cross-document linking\n",
- "linked = methods.link_entities(\n",
- " entities,\n",
- " knowledge_graph=kg,\n",
- " method=\"cross_document\",\n",
- " context=[{\"source\": \"doc1\"}, {\"source\": \"doc2\"}]\n",
- ")\n",
- "print(f\"✅ Cross-document linking: {len(linked)} entities linked\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 6.5 Listing Available Methods\n",
- "\n",
- "Discover all available methods for different tasks.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# List all available methods\n",
- "all_methods = methods.list_available_methods()\n",
- "print(\"📋 All Available Methods:\")\n",
- "for task, method_list in all_methods.items():\n",
- " print(f\" {task}: {method_list}\")\n",
- "\n",
- "# List methods for specific task\n",
- "graph_methods = methods.list_available_methods(\"graph\")\n",
- "print(f\"\\n📊 Graph Methods: {graph_methods}\")\n",
- "\n",
- "# Get a specific method\n",
- "custom_method = methods.get_context_method(\"graph\", \"entities_relationships\")\n",
- "if custom_method:\n",
- " print(f\"\\n✅ Retrieved method: {custom_method.__name__}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 🎛️ Step 7: Registry Submodule\n",
- "\n",
- "The `registry` submodule allows you to register custom context methods for extensibility.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 7.1 Registering Custom Methods\n",
- "\n",
- "Register your own custom context methods.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Define a custom graph builder function\n",
- "def custom_graph_builder(entities, relationships, **kwargs):\n",
- " \"\"\"Custom graph building method with additional processing.\"\"\"\n",
- " # Custom implementation\n",
- " nodes = {}\n",
- " edges = []\n",
- " \n",
- " # Process entities\n",
- " for entity in entities:\n",
- " nodes[entity['id']] = {\n",
- " 'text': entity.get('text', ''),\n",
- " 'type': entity.get('type', ''),\n",
- " 'confidence': entity.get('confidence', 1.0)\n",
- " }\n",
- " \n",
- " # Process relationships\n",
- " for rel in relationships:\n",
- " edges.append({\n",
- " 'source_id': rel['source_id'],\n",
- " 'target_id': rel['target_id'],\n",
- " 'type': rel['type'],\n",
- " 'weight': rel.get('confidence', 1.0)\n",
- " })\n",
- " \n",
- " return {\n",
- " 'nodes': nodes,\n",
- " 'edges': edges,\n",
- " 'statistics': {\n",
- " 'node_count': len(nodes),\n",
- " 'edge_count': len(edges)\n",
- " }\n",
- " }\n",
- "\n",
- "# Register custom method\n",
- "registry.method_registry.register(\"graph\", \"custom_builder\", custom_graph_builder)\n",
- "\n",
- "print(\"✅ Registered custom method: 'custom_builder'\")\n",
- "\n",
- "# Use custom method\n",
- "graph = methods.build_context_graph(\n",
- " entities=entities,\n",
- " relationships=relationships,\n",
- " method=\"custom_builder\"\n",
- ")\n",
- "\n",
- "print(f\"✅ Built graph using custom method\")\n",
- "print(f\" - Nodes: {graph['statistics']['node_count']}\")\n",
- "print(f\" - Edges: {graph['statistics']['edge_count']}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 7.2 Managing Registered Methods\n",
- "\n",
- "List and manage registered methods.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# List all registered methods for a task\n",
- "methods_list = registry.method_registry.list_all(\"graph\")\n",
- "print(f\"📋 Registered graph methods: {methods_list}\")\n",
- "\n",
- "# Get a registered method\n",
- "retrieved_method = registry.method_registry.get(\"graph\", \"custom_builder\")\n",
- "if retrieved_method:\n",
- " print(f\"✅ Retrieved method: {retrieved_method.__name__}\")\n",
- "\n",
- "# Unregister a method\n",
- "registry.method_registry.unregister(\"graph\", \"custom_builder\")\n",
- "print(f\"✅ Unregistered method: 'custom_builder'\")\n",
- "\n",
- "# Verify unregistration\n",
- "methods_list = registry.method_registry.list_all(\"graph\")\n",
- "print(f\"📋 Updated methods list: {methods_list}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## ⚙️ Step 8: Configuration Submodule\n",
- "\n",
- "The `config` submodule provides centralized configuration management for the context module.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 8.1 Basic Configuration\n",
- "\n",
- "Get and set configuration values.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Get configuration values\n",
- "retention = config.context_config.get(\"retention_policy\", default=\"unlimited\")\n",
- "max_size = config.context_config.get(\"max_memory_size\", default=10000)\n",
- "\n",
- "print(f\"📋 Current Configuration:\")\n",
- "print(f\" - Retention policy: {retention}\")\n",
- "print(f\" - Max memory size: {max_size}\")\n",
- "\n",
- "# Set configuration values\n",
- "config.context_config.set(\"retention_policy\", \"30_days\")\n",
- "config.context_config.set(\"max_memory_size\", 5000)\n",
- "\n",
- "print(f\"\\n✅ Updated Configuration:\")\n",
- "print(f\" - Retention policy: {config.context_config.get('retention_policy')}\")\n",
- "print(f\" - Max memory size: {config.context_config.get('max_memory_size')}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 8.2 Method-Specific Configuration\n",
- "\n",
- "Configure settings for specific methods.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Set method-specific configuration\n",
- "config.context_config.set_method_config(\"graph\", {\n",
- " \"extract_entities\": True,\n",
- " \"extract_relationships\": True,\n",
- " \"max_depth\": 3\n",
- "})\n",
- "\n",
- "# Get method-specific configuration\n",
- "method_config = config.context_config.get_method_config(\"graph\")\n",
- "print(f\"📋 Graph Method Configuration:\")\n",
- "print(f\" {method_config}\")\n",
- "\n",
- "# Set memory method configuration\n",
- "config.context_config.set_method_config(\"memory\", {\n",
- " \"retention_policy\": \"unlimited\",\n",
- " \"embedding_dimensions\": 1536\n",
- "})\n",
- "\n",
- "memory_config = config.context_config.get_method_config(\"memory\")\n",
- "print(f\"\\n📋 Memory Method Configuration:\")\n",
- "print(f\" {memory_config}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 8.3 Getting All Configuration\n",
- "\n",
- "Retrieve all configuration values at once.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Get all configurations\n",
- "all_configs = config.context_config.get_all()\n",
- "\n",
- "print(f\"📋 All Configuration Values:\")\n",
- "for key, value in all_configs.items():\n",
- " if isinstance(value, dict):\n",
- " print(f\" {key}:\")\n",
- " for sub_key, sub_value in value.items():\n",
- " print(f\" {sub_key}: {sub_value}\")\n",
- " else:\n",
- " print(f\" {key}: {value}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 8.4 Environment Variables\n",
- "\n",
- "Configuration can also be set via environment variables. The module automatically reads:\n",
- "- `CONTEXT_RETENTION_POLICY`\n",
- "- `CONTEXT_MAX_MEMORY_SIZE`\n",
- "- `CONTEXT_SIMILARITY_THRESHOLD`\n",
- "- And more...\n",
- "\n",
- "```bash\n",
- "# Example environment variable setup\n",
- "export CONTEXT_RETENTION_POLICY=30_days\n",
- "export CONTEXT_MAX_MEMORY_SIZE=5000\n",
- "export CONTEXT_SIMILARITY_THRESHOLD=0.8\n",
- "```\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 🚀 Step 9: Advanced Examples\n",
- "\n",
- "Let's combine everything we've learned into complete workflows for building intelligent agents with context awareness.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 9.1 Complete Agent Context Workflow\n",
- "\n",
- "A complete workflow from building context graphs to retrieving context for agent responses.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Step 1: Build context graph from entities and relationships\n",
- "builder = ContextGraphBuilder()\n",
- "graph = builder.build_from_entities_and_relationships(entities, relationships)\n",
- "\n",
- "print(f\"✅ Step 1: Built context graph with {graph['statistics']['node_count']} nodes\")\n",
- "\n",
- "# Step 2: Initialize agent memory\n",
- "memory = AgentMemory(vector_store=vs, knowledge_graph=kg)\n",
- "\n",
- "# Step 3: Store conversation in memory\n",
- "conversation_id = \"conv_126\"\n",
- "memory_id = memory.store(\n",
- " \"User asked about Python programming and machine learning frameworks\",\n",
- " metadata={\n",
- " \"type\": \"conversation\",\n",
- " \"conversation_id\": conversation_id,\n",
- " \"user_id\": \"user_789\",\n",
- " \"timestamp\": \"2024-01-01T12:00:00\"\n",
- " },\n",
- " entities=[\n",
- " {\"id\": \"e1\", \"text\": \"Python\", \"type\": \"PROGRAMMING_LANGUAGE\"},\n",
- " {\"id\": \"e2\", \"text\": \"Machine Learning\", \"type\": \"CONCEPT\"}\n",
- " ]\n",
- ")\n",
- "\n",
- "print(f\"✅ Step 2-3: Stored conversation memory with ID: {memory_id}\")\n",
- "\n",
- "# Step 4: Link entities\n",
- "linker = EntityLinker(knowledge_graph=kg)\n",
- "linked = linker.link(\n",
- " \"Python is used for machine learning\",\n",
- " entities=entities\n",
- ")\n",
- "\n",
- "print(f\"✅ Step 4: Linked {len(linked)} entities\")\n",
- "\n",
- "# Step 5: Retrieve context for agent response\n",
- "retriever = ContextRetriever(\n",
- " memory_store=memory,\n",
- " knowledge_graph=kg,\n",
- " vector_store=vs\n",
- ")\n",
- "\n",
- "results = retriever.retrieve(\"Python programming\", max_results=5)\n",
- "\n",
- "print(f\"✅ Step 5: Retrieved {len(results)} context items\")\n",
- "print(f\"\\n📋 Context for Agent Response:\")\n",
- "for i, result in enumerate(results[:3], 1):\n",
- " print(f\"\\n{i}. {result.content[:60]}...\")\n",
- " print(f\" Score: {result.score:.2f}, Source: {result.source}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": []
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Initialize retriever with multiple sources\n",
- "retriever = ContextRetriever(\n",
- " memory_store=memory,\n",
- " knowledge_graph=kg,\n",
- " vector_store=vs,\n",
- " hybrid_alpha=0.5, # Balance between vector and graph\n",
- " use_graph_expansion=True,\n",
- " max_expansion_hops=2\n",
- ")\n",
- "\n",
- "# Retrieve with hybrid approach\n",
- "results = retriever.retrieve(\n",
- " \"Python machine learning frameworks\",\n",
- " max_results=10,\n",
- " use_graph_expansion=True,\n",
- " max_hops=2\n",
- ")\n",
- "\n",
- "print(f\"✅ Retrieved {len(results)} results from multiple sources\")\n",
- "print(f\"\\n📋 Multi-Source Results:\")\n",
- "for i, result in enumerate(results[:5], 1):\n",
- " print(f\"\\n{i}. Source: {result.source}\")\n",
- " print(f\" Content: {result.content[:80]}...\")\n",
- " print(f\" Score: {result.score:.2f}\")\n",
- " print(f\" Related entities: {len(result.related_entities)}\")\n",
- " if result.related_entities:\n",
- " print(f\" - {', '.join([e.get('content', '') for e in result.related_entities[:3]])}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 9.3 Conversation-Based Context Building\n",
- "\n",
- "Build context graphs from conversation history and maintain conversation context.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Process multiple conversations\n",
- "conversations = [\n",
- " {\n",
- " \"id\": \"conv1\",\n",
- " \"content\": \"User asked about Python programming\",\n",
- " \"timestamp\": \"2024-01-01T10:00:00\",\n",
- " \"entities\": [{\"id\": \"e1\", \"text\": \"Python\", \"type\": \"PROGRAMMING_LANGUAGE\"}]\n",
- " },\n",
- " {\n",
- " \"id\": \"conv2\",\n",
- " \"content\": \"User asked about machine learning\",\n",
- " \"timestamp\": \"2024-01-01T11:00:00\",\n",
- " \"entities\": [{\"id\": \"e2\", \"text\": \"Machine Learning\", \"type\": \"CONCEPT\"}]\n",
- " },\n",
- " {\n",
- " \"id\": \"conv3\",\n",
- " \"content\": \"User asked about TensorFlow and PyTorch\",\n",
- " \"timestamp\": \"2024-01-01T12:00:00\",\n",
- " \"entities\": [\n",
- " {\"id\": \"e3\", \"text\": \"TensorFlow\", \"type\": \"FRAMEWORK\"},\n",
- " {\"id\": \"e4\", \"text\": \"PyTorch\", \"type\": \"FRAMEWORK\"}\n",
- " ]\n",
- " }\n",
- "]\n",
- "\n",
- "# Build graph from conversations\n",
- "builder = ContextGraphBuilder()\n",
- "graph = builder.build_from_conversations(\n",
- " conversations,\n",
- " link_entities=True,\n",
- " extract_intents=True\n",
- ")\n",
- "\n",
- "print(f\"✅ Built graph from {len(conversations)} conversations\")\n",
- "print(f\" - Nodes: {graph['statistics']['node_count']}\")\n",
- "print(f\" - Edges: {graph['statistics']['edge_count']}\")\n",
- "\n",
- "# Store conversations in memory\n",
- "for conv in conversations:\n",
- " memory.store(\n",
- " conv[\"content\"],\n",
- " metadata={\n",
- " \"type\": \"conversation\",\n",
- " \"conversation_id\": conv[\"id\"],\n",
- " \"timestamp\": conv[\"timestamp\"]\n",
- " },\n",
- " entities=conv.get(\"entities\", [])\n",
- " )\n",
- "\n",
- "print(f\"\\n✅ Stored {len(conversations)} conversations in memory\")\n",
- "\n",
- "# Retrieve conversation history\n",
- "history = memory.get_conversation_history(conversation_id=\"conv1\")\n",
- "print(f\"\\n📋 Conversation History for conv1: {len(history)} items\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 9.4 Entity Web Construction\n",
- "\n",
- "Build a complete entity web showing all entity connections and relationships.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Initialize linker\n",
- "linker = EntityLinker(\n",
- " knowledge_graph=kg,\n",
- " similarity_threshold=0.8\n",
- ")\n",
- "\n",
- "# Define entities\n",
- "entities = [\n",
- " {\"id\": \"e1\", \"text\": \"Python\", \"type\": \"PROGRAMMING_LANGUAGE\"},\n",
- " {\"id\": \"e2\", \"text\": \"Machine Learning\", \"type\": \"CONCEPT\"},\n",
- " {\"id\": \"e3\", \"text\": \"TensorFlow\", \"type\": \"FRAMEWORK\"},\n",
- " {\"id\": \"e4\", \"text\": \"PyTorch\", \"type\": \"FRAMEWORK\"},\n",
- " {\"id\": \"e5\", \"text\": \"Deep Learning\", \"type\": \"CONCEPT\"},\n",
- "]\n",
- "\n",
- "# Link entities\n",
- "linked = linker.link(\"\", entities=entities)\n",
- "\n",
- "# Create explicit links\n",
- "linker.link_entities(\"e1\", \"e2\", \"used_for\", confidence=0.9)\n",
- "linker.link_entities(\"e3\", \"e2\", \"implements\", confidence=0.95)\n",
- "linker.link_entities(\"e4\", \"e2\", \"implements\", confidence=0.94)\n",
- "linker.link_entities(\"e3\", \"e5\", \"implements\", confidence=0.92)\n",
- "linker.link_entities(\"e4\", \"e5\", \"implements\", confidence=0.91)\n",
- "linker.link_entities(\"e3\", \"e4\", \"related_to\", confidence=0.8)\n",
- "\n",
- "# Build entity web\n",
- "web = linker.build_entity_web()\n",
- "\n",
- "print(f\"✅ Entity Web Statistics:\")\n",
- "print(f\" - Total entities: {web['statistics']['total_entities']}\")\n",
- "print(f\" - Total links: {web['statistics']['total_links']}\")\n",
- "\n",
- "print(f\"\\n📋 Entity Details:\")\n",
- "for entity_id, info in web['entities'].items():\n",
- " print(f\"\\n Entity {entity_id}:\")\n",
- " print(f\" - URI: {info.get('uri', 'N/A')}\")\n",
- " print(f\" - Links: {info.get('links', 0)}\")\n",
- " print(f\" - Type: {info.get('type', 'N/A')}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### 9.5 Using Methods for Complete Workflow\n",
- "\n",
- "Use the methods submodule for a streamlined workflow.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Complete workflow using methods submodule\n",
- "\n",
- "# 1. Build context graph\n",
- "graph = methods.build_context_graph(\n",
- " entities=entities,\n",
- " relationships=relationships,\n",
- " method=\"hybrid\"\n",
- ")\n",
- "print(f\"✅ Step 1: Built graph with {graph['statistics']['node_count']} nodes\")\n",
- "\n",
- "# 2. Store memory\n",
- "memory_id = methods.store_memory(\n",
- " \"User conversation about Python and machine learning\",\n",
- " vector_store=vs,\n",
- " knowledge_graph=kg,\n",
- " method=\"store\",\n",
- " metadata={\"type\": \"conversation\", \"conversation_id\": \"conv_127\"}\n",
- ")\n",
- "print(f\"✅ Step 2: Stored memory with ID: {memory_id}\")\n",
- "\n",
- "# 3. Retrieve context\n",
- "results = methods.retrieve_context(\n",
- " \"Python programming\",\n",
- " memory_store=memory,\n",
- " knowledge_graph=kg,\n",
- " vector_store=vs,\n",
- " method=\"hybrid\",\n",
- " max_results=5\n",
- ")\n",
- "print(f\"✅ Step 3: Retrieved {len(results)} context items\")\n",
- "\n",
- "# 4. Link entities\n",
- "linked = methods.link_entities(\n",
- " entities,\n",
- " knowledge_graph=kg,\n",
- " method=\"knowledge_graph\"\n",
- ")\n",
- "print(f\"✅ Step 4: Linked {len(linked)} entities\")\n",
- "\n",
- "print(f\"\\n🎉 Complete workflow executed successfully!\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 📚 Summary\n",
- "\n",
- "In this notebook, we've covered:\n",
- "\n",
- "### ✅ What We Learned\n",
- "\n",
- "1. **Context Graph Construction**\n",
- " - Building graphs from entities, relationships, and conversations\n",
- " - Manual graph construction with nodes and edges\n",
- " - Graph traversal and querying\n",
- "\n",
- "2. **Agent Memory Management**\n",
- " - Storing memories with metadata and entities\n",
- " - Retrieving memories with vector similarity search\n",
- " - Conversation history management\n",
- " - Memory cleanup and statistics\n",
- "\n",
- "3. **Context Retrieval**\n",
- " - Hybrid retrieval combining multiple sources\n",
- " - Graph expansion for related entities\n",
- " - Multi-hop context discovery\n",
- "\n",
- "4. **Entity Linking**\n",
- " - URI assignment for entities\n",
- " - Similarity-based and graph-based linking\n",
- " - Entity web construction\n",
- " - Cross-document entity linking\n",
- "\n",
- "5. **Methods Submodule**\n",
- " - Convenient functions for all operations\n",
- " - Multiple algorithm support\n",
- " - Method discovery and retrieval\n",
- "\n",
- "6. **Registry System**\n",
- " - Registering custom methods\n",
- " - Method management and discovery\n",
- "\n",
- "7. **Configuration**\n",
- " - Global and method-specific settings\n",
- " - Environment variable support\n",
- "\n",
- "### 🎯 Key Takeaways\n",
- "\n",
- "- The context module provides a complete solution for building context-aware agents\n",
- "- Multiple approaches (classes vs. methods) for different use cases\n",
- "- Extensible architecture with custom method registration\n",
- "- Hybrid retrieval provides the best context quality\n",
- "- Entity linking enables cross-document knowledge integration\n",
- "\n",
- "### 📖 Next Steps\n",
- "\n",
- "- Explore the [API Reference](https://semantica.readthedocs.io/reference/context/) for detailed documentation\n",
- "- Check out advanced use cases in the cookbook\n",
- "- Build your own custom context methods\n",
- "- Integrate with other Semantica modules for complete workflows\n",
- "\n",
- "---\n",
- "\n",
- "**Happy Context Engineering! 🚀**\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": []
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/introduction/19_Context_Module.ipynb)\n",
+ "\n",
+ "# Context Engineering Module\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook provides a comprehensive guide to Semantica's **Context Engineering Module** - a powerful system for building context graphs, managing agent memory, retrieving context, and linking entities. You'll learn how to use the new synchronous Architecture 2.0 features, including hierarchical memory with token management.\n",
+ "\n",
+ "**Documentation**: [API Reference](https://semantica.readthedocs.io/reference/context/)\n",
+ "\n",
+ "### Learning Objectives\n",
+ "\n",
+ "- **Hierarchical Memory**: Manage short-term (token-buffered) and long-term (vector-stored) memory\n",
+ "- **Context Graph**: Build and query dynamic knowledge graphs\n",
+ "- **Hybrid Retrieval**: Combine vector search, graph traversal, and keyword matching\n",
+ "- **Entity Linking**: Resolve entities across conversations\n",
+ "- **Configuration**: Customize behavior via YAML or environment variables\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n",
+ "\n",
+ "```bash\n",
+ "pip install semantica\n",
+ "```"
+ ]
},
- "nbformat": 4,
- "nbformat_minor": 2
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Setup: Create a mock vector store for demonstration\n",
+ "from typing import List, Dict, Any, Optional\n",
+ "from semantica.context import VectorStore\n",
+ "\n",
+ "class MockVectorStore(VectorStore):\n",
+ " def __init__(self):\n",
+ " self.items = {}\n",
+ " self.counter = 0\n",
+ " \n",
+ " def add(self, texts: List[str], metadata: Optional[List[Dict[str, Any]]] = None, **kwargs) -> List[str]:\n",
+ " ids = []\n",
+ " for i, text in enumerate(texts):\n",
+ " id_ = f\"id_{self.counter}\"\n",
+ " self.items[id_] = {\"text\": text, \"metadata\": metadata[i] if metadata else {}}\n",
+ " ids.append(id_)\n",
+ " self.counter += 1\n",
+ " return ids\n",
+ " \n",
+ " def search(self, query: str, limit: int = 5, **kwargs) -> List[Dict[str, Any]]:\n",
+ " # Simple keyword match for mock\n",
+ " results = []\n",
+ " for id_, item in self.items.items():\n",
+ " if any(w.lower() in item[\"text\"].lower() for w in query.split()):\n",
+ " results.append({\n",
+ " \"id\": id_,\n",
+ " \"content\": item[\"text\"],\n",
+ " \"score\": 0.9,\n",
+ " \"metadata\": item[\"metadata\"]\n",
+ " })\n",
+ " return results[:limit]\n",
+ " \n",
+ " def delete(self, ids: List[str], **kwargs) -> bool:\n",
+ " for id_ in ids:\n",
+ " self.items.pop(id_, None)\n",
+ " return True\n",
+ "\n",
+ "vs = MockVectorStore()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. High-Level Interface: AgentContext\n",
+ "\n",
+ "The `AgentContext` class is the easiest way to get started. It unifies vector storage, knowledge graphs, and memory management."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.context import AgentContext, ContextGraph\n",
+ "\n",
+ "# Initialize with vector store and a new in-memory knowledge graph\n",
+ "kg = ContextGraph()\n",
+ "context = AgentContext(\n",
+ " vector_store=vs,\n",
+ " knowledge_graph=kg,\n",
+ " token_limit=2000, # Max tokens in short-term memory\n",
+ " short_term_limit=10 # Max items in short-term memory\n",
+ ")\n",
+ "\n",
+ "# Store a memory (automatically goes to short-term and long-term)\n",
+ "context.store(\n",
+ " \"The user, Alice, is a data scientist interested in Python.\",\n",
+ " conversation_id=\"conv_1\",\n",
+ " user_id=\"alice_01\"\n",
+ ")\n",
+ "\n",
+ "# Retrieve context (automatically uses hybrid retrieval)\n",
+ "results = context.retrieve(\"What does Alice do?\")\n",
+ "\n",
+ "for res in results:\n",
+ " print(f\"Found: {res['content']} (Score: {res['score']})\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Hierarchical Memory Management\n",
+ "\n",
+ "Semantica uses a two-tier memory system:\n",
+ "1. **Short-Term Memory**: A fast, in-memory buffer limited by tokens (to fit in LLM context windows) and item count.\n",
+ "2. **Long-Term Memory**: Persistent storage backed by the vector store.\n",
+ "\n",
+ "Let's observe how the token limit works."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.context import AgentMemory\n",
+ "\n",
+ "# Initialize memory with strict limits for demonstration\n",
+ "memory = AgentMemory(\n",
+ " vector_store=vs,\n",
+ " token_limit=50, # Very small token limit\n",
+ " short_term_limit=5 # Max 5 items\n",
+ ")\n",
+ "\n",
+ "# Add memories\n",
+ "for i in range(10):\n",
+ " memory.store(f\"Memory item {i}: This is a sentence with some tokens.\")\n",
+ " print(f\"Added item {i}. Short-term size: {len(memory.short_term_memory)}\")\n",
+ "\n",
+ "print(\"\\nFinal short-term memory content:\")\n",
+ "for item in memory.short_term_memory:\n",
+ " print(f\"- {item.content}\")\n",
+ " \n",
+ "# Notice that older items are pruned to respect the token limit and item count."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. Context Graph & GraphRAG\n",
+ "\n",
+ "The `ContextGraph` allows you to structure information as nodes and edges, enabling \"GraphRAG\" - retrieving information based on relationships rather than just semantic similarity."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.context import ContextGraph\n",
+ "\n",
+ "graph = ContextGraph()\n",
+ "\n",
+ "# Manually building a graph\n",
+ "graph.add_node(\"n1\", \"person\", \"Alice\")\n",
+ "graph.add_node(\"n2\", \"language\", \"Python\")\n",
+ "graph.add_node(\"n3\", \"library\", \"Semantica\")\n",
+ "\n",
+ "graph.add_edge(\"n1\", \"n2\", \"uses\")\n",
+ "graph.add_edge(\"n2\", \"n3\", \"powers\")\n",
+ "\n",
+ "# Query the graph\n",
+ "neighbors = graph.get_neighbors(\"n2\", hops=1)\n",
+ "print(\"Neighbors of Python:\", neighbors)\n",
+ "\n",
+ "# Using the graph in AgentContext\n",
+ "context = AgentContext(vector_store=vs, knowledge_graph=graph)\n",
+ "\n",
+ "# Retrieve with graph expansion\n",
+ "results = context.retrieve(\n",
+ " \"Alice\",\n",
+ " use_graph=True,\n",
+ " expand_graph=True # Will pull in 'Python' because Alice uses it\n",
+ ")\n",
+ "\n",
+ "print(\"\\nGraph-enhanced Retrieval:\")\n",
+ "for res in results:\n",
+ " print(f\"- {res['content']}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. Entity Linking\n",
+ "\n",
+ "The `EntityLinker` helps ensure that \"Alice\", \"Alice Smith\", and \"she\" (in context) refer to the same entity ID."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.context import EntityLinker\n",
+ "\n",
+ "linker = EntityLinker()\n",
+ "\n",
+ "# Generate a canonical URI\n",
+ "uri = linker.generate_uri(\"Python Programming Language\")\n",
+ "print(f\"Canonical URI: {uri}\")\n",
+ "\n",
+ "# Check similarity\n",
+ "score = linker._calculate_text_similarity(\"Python\", \"Python Lang\")\n",
+ "print(f\"Similarity Score: {score}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 5. Configuration\n",
+ "\n",
+ "You can configure the context module using the `config` object or environment variables."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.context import config\n",
+ "\n",
+ "# Set global configuration\n",
+ "config.context_config.set(\"token_limit\", 4096)\n",
+ "config.context_config.set(\"retention_days\", 30)\n",
+ "\n",
+ "print(f\"Current Token Limit: {config.context_config.get('token_limit')}\")"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.8.10"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
}
diff --git a/docs/reference/context.md b/docs/reference/context.md
index f4cde427..3e304aca 100644
--- a/docs/reference/context.md
+++ b/docs/reference/context.md
@@ -1,482 +1,161 @@
-# Context
+# Context Module Reference
-> **Context engineering and memory management system for intelligent agents using RAG and Knowledge Graphs.**
+> **The central nervous system for intelligent agents, managing memory, knowledge graphs, and context retrieval.**
---
-## 🎯 Overview
+## 🎯 System Overview
-<div class="grid cards" markdown>
+The **Context Module** provides agents with a persistent, searchable, and structured memory system. It is built on a **Synchronous Architecture 2.0**, ensuring predictable state management and compatibility with modern vector stores and graph databases.
-- :material-graph:{ .lg .middle } **Context Graph**
+### Key Capabilities
- ---
-
- Build dynamic context graphs from conversations and entities
-
-- :material-brain:{ .lg .middle } **Agent Memory**
-
- ---
-
- Persistent memory management with vector storage integration
-
-- :material-link-variant:{ .lg .middle } **Entity Linking**
-
- ---
-
- Link entities across documents and conversations
-
-- :material-magnify:{ .lg .middle } **Hybrid Retrieval**
-
- ---
-
- Retrieve context using Vector + Graph + Keyword search
-
-- :material-history:{ .lg .middle } **Conversation History**
-
- ---
-
- Manage and synthesize conversation history
-
-- :material-bullseye-arrow:{ .lg .middle } **Intent Analysis**
-
- ---
-
- Extract and track user intent and sentiment
-
-</div>
-
-!!! tip "When to Use"
- - **Agent Development**: When building agents that need long-term memory
- - **RAG Applications**: For advanced Retrieval-Augmented Generation
- - **Personalization**: To maintain user-specific context and preferences
+* **Hierarchical Memory**: A two-tier memory system that mimics human memory (Short-term "Working" Memory + Long-term "Episodic" Memory).
+* **GraphRAG**: Combines unstructured vector search with structured knowledge graph traversal for richer context.
+* **Hybrid Retrieval**: Intelligently blends results from keyword matching, vector similarity, and graph connections.
+* **Token Management**: Automatically prunes short-term memory to fit within LLM context windows using token-based constraints.
+* **Entity Linking**: Resolves ambiguities by linking text mentions to unique entities in the knowledge graph.
---
-## ⚙️ Algorithms Used
+## 🏗️ Architecture Components
-### Context Graph Construction
-- **Graph Building**: Node/Edge construction from extracted entities
-- **Graph Traversal**: BFS/DFS for multi-hop context discovery
-- **Intent Extraction**: NLP-based intent classification
-- **Sentiment Analysis**: Sentiment scoring and extraction
+### 1. AgentContext (The Orchestrator)
+The high-level facade that unifies all context operations. It routes data to the appropriate subsystems (Memory, Graph, Vector Store) and manages the lifecycle of context.
-### Agent Memory
-- **Vector Embedding**: Dense vector generation for memory items
-- **Vector Search**: Cosine similarity search (k-NN)
-- **Retention Policy**: Time-based decay and cleanup
-- **Memory Indexing**: Deque-based sliding window for short-term memory
+#### **Constructor Parameters**
+* `vector_store` (Required): The backing vector database instance (e.g., FAISS, Pinecone).
+* `knowledge_graph` (Optional): The graph store instance for structured knowledge.
+* `token_limit` (Default: `2000`): The maximum number of tokens allowed in short-term memory before pruning occurs.
+* `short_term_limit` (Default: `10`): The maximum number of distinct memory items in short-term memory.
+* `hybrid_alpha` (Default: `0.5`): The weighting factor for retrieval (0.0 = Pure Vector, 1.0 = Pure Graph).
+* `use_graph_expansion` (Default: `True`): Whether to fetch neighbors of retrieved nodes from the graph.
-### Entity Linking
-- **URI Generation**: Hash-based deterministic IDs
-- **Text Similarity**: Jaccard/Levenshtein for name matching
-- **Graph Lookup**: Entity resolution against Knowledge Graph
-- **Bidirectional Linking**: Symmetric link creation
+#### **Core Methods**
-### Context Retrieval
-- **Hybrid Scoring**: `α * VectorScore + β * GraphScore + γ * KeywordScore`
-- **Graph Expansion**: Retrieving neighbors of retrieved entities
-- **Deduplication**: Content-based result merging
-- **Result Ranking**: Weighted aggregation of scores
+* **`store(content, ...)`**: Writes information to memory.
+ * *Auto-Detection*: Automatically determines if input is a simple string (memory) or a list of documents.
+ * *Write-Through*: Saves to both Short-term (RAM) and Long-term (Vector Store) memory simultaneously.
+ * *Entity Extraction*: If enabled, extracts entities and relationships to update the Knowledge Graph.
+* **`retrieve(query, ...)`**: Fetches relevant context.
+ * *Hybrid Search*: Queries Vector Store, Short-term Memory, and Knowledge Graph in parallel.
+ * *Reranking*: Merges and ranks results based on relevance scores.
+ * *Context Window Optimization*: Returns results that fit within the agent's context window.
---
-## Main Classes
-
-### AgentContext
-
-High-level interface for agent context management, RAG, and GraphRAG. Provides generic methods (`store`, `retrieve`, `forget`, `conversation`) that auto-detect content types and retrieval strategies.
-
-**Methods:**
-
-| Method | Description | Parameters |
-|--------|-------------|------------|
-| `store(content, ...)` | Store content (memory or documents) | `extract_entities: bool = True`, `extract_relationships: bool = True`, `link_entities: bool = True`, `auto_extract: bool = False` |
-| `retrieve(query, ...)` | Retrieve relevant context | `use_graph: Optional[bool] = None`, `include_entities: bool = True`, `include_relationships: bool = False`, `expand_graph: bool = True`, `deduplicate: bool = True` |
-| `forget(...)` | Delete memories | `memory_id`, `conversation_id`, `user_id`, `days_old` |
-| `conversation(conversation_id, ...)` | Get conversation history | `reverse: bool = False`, `include_metadata: bool = True` |
-| `get_memory(memory_id)` | Get specific memory by ID | `memory_id: str` |
-| `stats()` | Get memory statistics | None |
-| `link(text, entities, ...)` | Link entities in text | `similarity_threshold: float = 0.8` |
-| `build_graph(...)` | Build context graph manually | `entities`, `relationships`, `conversations`, `link_entities: bool = True` |
-
-**Initialization:**
-
-```python
-AgentContext(
- vector_store, # Required
- knowledge_graph=None, # Optional (enables GraphRAG)
- retention_days=30, # Optional
- max_memories=10000, # Optional
- use_graph_expansion=True, # Boolean flag
- max_expansion_hops=2, # Optional
- hybrid_alpha=0.5 # Optional
-)
-```
-
-**Example:**
-
-```python
-from semantica.context import AgentContext
-
-# Simple RAG
-context = AgentContext(vector_store=vs)
-memory_id = context.store("User likes Python", conversation_id="conv1")
-results = context.retrieve("Python programming")
-
-# GraphRAG
-context = AgentContext(vector_store=vs, knowledge_graph=kg)
-stats = context.store(["Doc 1", "Doc 2"], extract_entities=True)
-results = context.retrieve("Python", use_graph=None) # Auto-detects GraphRAG
-
-# Conversation management
-history = context.conversation("conv1", reverse=True)
-deleted = context.forget(conversation_id="conv1")
-```
-
-**Boolean Flags:**
-
-- **Store**: `extract_entities`, `extract_relationships`, `link_entities`
-- **Retrieve**: `use_graph` (None=auto-detect), `include_entities`, `include_relationships`, `expand_graph`
-- **Conversation**: `reverse`, `include_metadata`
-
-### ContextGraphBuilder
-
-Builds and manages the context graph.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `build_from_entities_and_relationships(entities, relationships)` | Build graph from entities and relationships | Node/Edge creation |
-| `build_from_conversations(conversations, link_entities, extract_intents, extract_sentiments)` | Build graph from conversations | Intent/Entity extraction |
-| `add_node(node_id, node_type, content, **metadata)` | Add node to graph | Node creation |
-| `add_edge(source_id, target_id, edge_type, weight, **metadata)` | Add edge to graph | Edge creation |
-| `get_neighbors(node_id, max_hops)` | Get neighbor nodes | BFS Traversal |
-| `query(node_type, edge_type, **filters)` | Query graph nodes and edges | Type-based filtering |
-
-**Example:**
-
-```python
-from semantica.context import ContextGraphBuilder
-
-builder = ContextGraphBuilder()
-graph = builder.build_from_entities_and_relationships(
- entities=extracted_entities,
- relationships=extracted_rels
-)
-
-# Add nodes and edges manually
-builder.add_node("node1", "entity", "Python programming")
-builder.add_edge("node1", "node2", "related_to", weight=0.9)
-
-# Query and traverse
-neighbors = builder.get_neighbors("node1", max_hops=2)
-results = builder.query(node_type="entity", confidence=0.8)
-```
-
-### AgentMemory
-
-Manages persistent agent memory.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `store(content, metadata, entities, relationships, **options)` | Store memory item | Embedding + Vector Store |
-| `retrieve(query, max_results, min_score, **filters)` | Retrieve relevant memories | Vector Similarity |
-| `get_memory(memory_id)` | Get specific memory item | Dictionary lookup |
-| `delete_memory(memory_id)` | Delete memory item | Cascading deletion |
-| `clear_memory(**filters)` | Clear memories by filters | Filter-based deletion |
-| `get_conversation_history(conversation_id, max_items)` | Get conversation history | Temporal filtering |
-| `get_statistics()` | Get memory statistics | Counter aggregation |
-
-**Example:**
-
-```python
-from semantica.context import AgentMemory
-
-memory = AgentMemory(vector_store=vs, knowledge_graph=kg)
-memory_id = memory.store("User prefers Python over Java", metadata={"type": "preference"})
-relevant = memory.retrieve("What language does the user like?", max_results=5)
-
-# Get specific memory
-memory_item = memory.get_memory(memory_id)
-
-# Get statistics
-stats = memory.get_statistics()
-```
-
-### EntityLinker
-
-Links entities across different contexts.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `assign_uri(entity_id, entity_text, entity_type)` | Assign unique URI to entity | Hash-based/Text-based URI |
-| `link(text, entities, context)` | Link entities in text to knowledge graph | Similarity matching |
-| `link_entities(entity1_id, entity2_id, link_type, confidence, source, **metadata)` | Create explicit link between entities | Bidirectional linking |
-| `get_entity_links(entity_id)` | Get all links for an entity | Dictionary lookup |
-| `get_entity_uri(entity_id)` | Get URI for an entity | Registry lookup |
-| `find_similar_entities(entity_text, entity_type, threshold)` | Find similar entities in knowledge graph | Text similarity |
-| `build_entity_web()` | Build entity connection web | Graph construction |
-
-**Example:**
-
-```python
-from semantica.context import EntityLinker
-
-linker = EntityLinker(knowledge_graph=kg, similarity_threshold=0.8)
-uri = linker.assign_uri("entity_1", "Python", "PROGRAMMING_LANGUAGE")
-linked_entities = linker.link("Python is used for ML", entities=entities)
-linker.link_entities("e1", "e2", "related_to", confidence=0.9)
-similar = linker.find_similar_entities("Python", entity_type="PROGRAMMING_LANGUAGE")
-web = linker.build_entity_web()
-```
-
-### ContextRetriever
-
-Orchestrates hybrid retrieval.
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `retrieve(query, max_results, use_graph_expansion, min_relevance_score, **options)` | Retrieve relevant context for query | Hybrid (Vector+Graph+Memory) |
-
-**Example:**
-
-```python
-from semantica.context import ContextRetriever
-
-retriever = ContextRetriever(
- memory_store=memory,
- knowledge_graph=kg,
- vector_store=vs,
- use_graph_expansion=True,
- max_expansion_hops=2
-)
-
-results = retriever.retrieve("Python programming", max_results=5, min_relevance_score=0.5)
-for result in results:
- print(f"{result.content}: {result.score:.2f}")
- print(f"Related entities: {len(result.related_entities)}")
-```
+### 2. AgentMemory (The Storage Engine)
+Manages the storage and lifecycle of memory items. It implements the **Hierarchical Memory** pattern.
+
+#### **Features & Functions**
+* **Short-Term Memory (Working Memory)**
+ * *Structure*: An in-memory list of recent `MemoryItem` objects.
+ * *Purpose*: Provides immediate context for the ongoing conversation.
+ * *Pruning Logic*:
+ * **FIFO**: Removes the oldest items first when limits are reached.
+ * **Token-Aware**: Calculates token counts to ensure the total buffer size stays under `token_limit`.
+* **Long-Term Memory (Episodic Memory)**
+ * *Structure*: Vector embeddings stored in the `vector_store`.
+ * *Purpose*: Persists history indefinitely for semantic retrieval.
+ * *Synchronization*: Automatically syncs with Short-term memory during `store()` operations.
+* **Retention Policy**
+ * *Time-Based*: Can automatically delete memories older than `retention_days`.
+ * *Count-Based*: Can limit the total number of memories to `max_memories`.
+
+#### **Key Methods**
+* `store_vectors()`: Handles the low-level interaction with concrete Vector Store implementations.
+* `_prune_short_term_memory()`: Internal algorithm that enforces token and count limits.
+* `get_conversation_history()`: Retrieves a chronological list of interactions for a specific session.
---
-## Methods Module
-
-The methods module provides simple, reusable functions for context operations.
-
-**Functions:**
-
-| Function | Description |
-|----------|-------------|
-| `build_context_graph(entities, relationships, conversations, method, **kwargs)` | Build context graph using specified method |
-| `store_memory(content, vector_store, knowledge_graph, method, **kwargs)` | Store memory using specified method |
-| `retrieve_context(query, memory_store, knowledge_graph, vector_store, method, max_results, **kwargs)` | Retrieve context using specified method |
-| `link_entities(entities, knowledge_graph, method, **kwargs)` | Link entities using specified method |
-| `get_context_method(task, name)` | Get registered context method |
-| `list_available_methods(task)` | List all available context methods |
-
-**Example:**
-
-```python
-from semantica.context.methods import (
- build_context_graph,
- store_memory,
- retrieve_context,
- link_entities,
- get_context_method,
- list_available_methods
-)
-
-# Build graph
-graph = build_context_graph(entities, relationships, method="entities_relationships")
-
-# Store memory
-memory_id = store_memory("User asked about Python", vector_store=vs, method="store")
-
-# Retrieve context
-results = retrieve_context("Python programming", vector_store=vs, method="hybrid")
-
-# Link entities
-linked = link_entities(entities, knowledge_graph=kg, method="similarity")
-
-# List available methods
-all_methods = list_available_methods()
-graph_methods = list_available_methods("graph")
-```
-
-## Registry Module
-
-The registry module allows registering custom context methods.
-
-**MethodRegistry Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `register(task, name, method_func)` | Register a method for a specific task |
-| `get(task, name)` | Get a registered method |
-| `list_all(task)` | List all registered methods |
-| `unregister(task, name)` | Unregister a method |
-
-**Example:**
-
-```python
-from semantica.context import registry
-
-def custom_graph_builder(entities, relationships, **kwargs):
- """Custom graph building method."""
- return {"nodes": [], "edges": [], "statistics": {}}
-
-# Register custom method
-registry.method_registry.register("graph", "custom_builder", custom_graph_builder)
-
-# List registered methods
-methods = registry.method_registry.list_all("graph")
-
-# Unregister method
-registry.method_registry.unregister("graph", "custom_builder")
-```
-
-## Configuration Module
+### 3. ContextGraph (The Knowledge Structure)
+Manages the structured relationships between entities. It provides the "World Model" for the agent.
+
+#### **Features & Functions**
+* **Dictionary-Based Interface**
+ * *Design*: Uses standard Python dictionaries for nodes and edges, removing dependencies on complex interface classes.
+ * *Benefit*: simpler serialization and easier integration with external APIs.
+* **Graph Traversal**
+ * *Adjacency List*: optimized internal structure for fast neighbor lookups.
+ * *Multi-Hop Search*: Can traverse `k` hops from a starting node to find indirect connections.
+* **Node & Edge Types**
+ * *Typed Schema*: Supports distinct types for nodes (e.g., "Person", "Concept") and edges (e.g., "KNOWS", "RELATED_TO").
+
+#### **Key Methods**
+* `add_nodes(nodes)`: Bulk adds nodes using a list of dictionaries.
+* `add_edges(edges)`: Bulk adds edges using a list of dictionaries.
+* `get_neighbors(node_id, hops)`: Returns connected nodes within a specified distance.
+* `query(query_str)`: Performs keyword-based search specifically on graph nodes.
-The configuration module provides centralized configuration management.
-
-**ContextConfig Methods:**
-
-| Method | Description |
-|--------|-------------|
-| `set(key, value)` | Set a configuration value |
-| `get(key, default)` | Get a configuration value |
-| `set_method_config(method_name, config)` | Set method-specific configuration |
-| `get_method_config(method_name)` | Get method-specific configuration |
-| `get_all()` | Get all configurations |
-
-**Example:**
-
-```python
-from semantica.context import config
-
-# Get configuration
-retention = config.context_config.get("retention_policy", default="unlimited")
-max_size = config.context_config.get("max_memory_size", default=10000)
-
-# Set configuration
-config.context_config.set("retention_policy", "30_days")
-config.context_config.set("max_memory_size", 5000)
-
-# Method-specific configuration
-config.context_config.set_method_config("graph", {
- "extract_entities": True,
- "extract_relationships": True
-})
+---
-method_config = config.context_config.get_method_config("graph")
+### 4. ContextRetriever (The Search Engine)
+The retrieval logic that powers the `retrieve()` command. It implements the **Hybrid Retrieval** algorithm.
-# Load from config file
-context_config = config.ContextConfig(config_file="context_config.yaml")
-all_configs = context_config.get_all()
-```
+#### **Retrieval Strategy**
+1. **Short-Term Check**: Scans the in-memory buffer for immediate, exact-match relevance.
+2. **Vector Search**: Queries the `vector_store` for semantically similar long-term memories.
+3. **Graph Expansion**:
+ * Identifies entities in the query.
+ * Finds those entities in the `ContextGraph`.
+ * Traverses edges to find related concepts that might not match keywords (e.g., finding "Python" when searching for "Coding").
+4. **Hybrid Scoring**:
+ * Formula: `Final_Score = (Vector_Score * (1 - α)) + (Graph_Score * α)`
+ * Allows tuning the balance between semantic similarity and structural relevance.
---
-## Configuration
+## ⚙️ Configuration & Tuning
-### Environment Variables
+### Token Management
+* **`CONTEXT_TOKEN_LIMIT`**: Environment variable to set the global default for short-term memory size.
+* **`short_term_limit`**: Configurable per-agent to limit the *count* of recent items.
-```bash
-export CONTEXT_RETENTION_POLICY=30_days
-export CONTEXT_MAX_MEMORY_SIZE=5000
-export CONTEXT_SIMILARITY_THRESHOLD=0.8
-```
-
-### YAML Configuration
-
-```yaml
-context:
- retention_policy:
- max_days: 30
- max_items: 1000
-
- retrieval:
- hybrid_weights:
- vector: 0.6
- graph: 0.3
- keyword: 0.1
-
- graph:
- max_depth: 2
- include_attributes: true
-```
+### Tuning Retrieval
+* **`hybrid_alpha`**:
+ * `0.0`: Relies entirely on Vector Search (Standard RAG).
+ * `0.5`: Balanced approach (Recommended).
+ * `1.0`: Relies entirely on Graph traversal (Graph RAG).
+* **`max_expansion_hops`**:
+ * `1`: Only direct neighbors.
+ * `2`: Friends of friends (Recommended for discovery).
+ * `3+`: Can introduce noise but finds deep connections.
---
-## Integration Examples
-
-### Chatbot with Memory
+## 📝 Data Structures
+### MemoryItem
+The fundamental unit of storage.
```python
-from semantica.context import AgentMemory, ContextRetriever
-from semantica.llm import LLMClient
-
-# 1. Initialize
-memory = AgentMemory(vector_store=vs)
-retriever = ContextRetriever(memory=memory, graph=kg)
-llm = LLMClient()
-
-def chat(user_input):
- # 2. Retrieve Context
- context = retriever.retrieve(user_input)
-
- # 3. Generate Response
- response = llm.generate(user_input, context=context)
-
- # 4. Update Memory
- memory.store(f"User: {user_input}")
- memory.store(f"Agent: {response}")
-
- return response
+@dataclass
+class MemoryItem:
+ content: str # The actual text content
+ timestamp: datetime # When it was created
+ metadata: Dict # Arbitrary tags (user_id, source, etc.)
+ embedding: List[float] # The vector representation
+ entities: List[Dict] # Entities found in this content
```
----
-
-## Best Practices
-
-1. **Prune Regularly**: Use retention policies to keep memory relevant and performant.
-2. **Use Hybrid Retrieval**: Relying solely on vector search misses structural relationships; use graph context too.
-3. **Enrich Metadata**: Store rich metadata (timestamp, source, type) with memories for better filtering.
-4. **Link Entities**: Ensure `EntityLinker` is used to connect mentions of the same entity across conversations.
-
----
-
-## Troubleshooting
-
-**Issue**: Retrieval returns irrelevant old memories.
-**Solution**: Adjust retention policy or increase vector similarity threshold.
-
+### Graph Node (Dict Format)
```python
-memory = AgentMemory(
- retention_policy="7_days",
- max_memory_size=1000
-)
+{
+ "id": "node_unique_id",
+ "type": "concept",
+ "properties": {
+ "content": "Description of the node",
+ "weight": 1.0
+ }
+}
```
-**Issue**: Context graph growing too large.
-**Solution**: Use `prune_graph` or limit hop depth during retrieval.
-
----
-
-## See Also
-
-- [Vector Store Module](vector_store.md) - Underlying storage for memory
-- [Knowledge Graph Module](kg.md) - Underlying graph structure
-- [Embeddings Module](embeddings.md) - Vector generation
-
-## Cookbook
-
-- [Context Module](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/introduction/19_Context_Module.ipynb)
+### Graph Edge (Dict Format)
+```python
+{
+ "source_id": "origin_node",
+ "target_id": "destination_node",
+ "type": "related_to",
+ "weight": 0.8
+}
+```
diff --git a/semantica/context/__init__.py b/semantica/context/__init__.py
index 5c3e8bc8..0f15d6bb 100644
--- a/semantica/context/__init__.py
+++ b/semantica/context/__init__.py
@@ -99,7 +99,7 @@ License: MIT
from .agent_context import AgentContext
from .agent_memory import AgentMemory, MemoryItem
-from .context_graph import ContextEdge, ContextGraphBuilder, ContextNode
+from .context_graph import ContextEdge, ContextGraph, ContextNode
from .context_retriever import ContextRetriever, RetrievedContext
from .entity_linker import EntityLink, EntityLinker, LinkedEntity
from . import methods
@@ -110,7 +110,7 @@ __all__ = [
# High-level interface
"AgentContext",
# Main classes
- "ContextGraphBuilder",
+ "ContextGraph",
"ContextNode",
"ContextEdge",
"EntityLinker",
@@ -125,3 +125,6 @@ __all__ = [
"registry",
"config",
]
+
+# Backward compatibility alias
+ContextGraphBuilder = ContextGraph
diff --git a/semantica/context/agent_context.py b/semantica/context/agent_context.py
index 5f42a86d..7e6c59cc 100644
--- a/semantica/context/agent_context.py
+++ b/semantica/context/agent_context.py
@@ -25,7 +25,7 @@ from typing import Any, Dict, List, Optional, Union
from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
from .agent_memory import AgentMemory
-from .context_graph import ContextGraphBuilder
+from .context_graph import ContextGraph
from .context_retriever import ContextRetriever, RetrievedContext
from .entity_linker import EntityLinker
@@ -42,7 +42,7 @@ class AgentContext:
knowledge_graph: Knowledge graph instance (optional)
memory: AgentMemory instance (via property)
retriever: ContextRetriever instance (via property, if knowledge_graph available)
- graph_builder: ContextGraphBuilder instance (via property, if knowledge_graph available)
+ graph_builder: ContextGraph instance (via property, if knowledge_graph supports building)
Main Methods:
- store(): Store memory or documents (auto-detects type)
@@ -64,8 +64,8 @@ class AgentContext:
def __init__(
self,
- vector_store,
- knowledge_graph=None,
+ vector_store: Any,
+ knowledge_graph: Optional[Any] = None,
retention_days: Optional[int] = 30,
max_memories: int = 10000,
use_graph_expansion: bool = True,
@@ -127,11 +127,10 @@ class AgentContext:
else:
self._retriever = None
- # Initialize ContextGraphBuilder if knowledge_graph available
- if knowledge_graph:
- self._graph_builder = ContextGraphBuilder()
- else:
- self._graph_builder = None
+ # Initialize ContextGraphBuilder if knowledge_graph available and supports building
+ self._graph_builder = None
+ if knowledge_graph and hasattr(knowledge_graph, "build_from_conversations"):
+ self._graph_builder = knowledge_graph
# Store config
self.config = {
@@ -153,8 +152,8 @@ class AgentContext:
return self._retriever
@property
- def graph_builder(self) -> Optional[ContextGraphBuilder]:
- """Access underlying ContextGraphBuilder instance."""
+ def graph_builder(self) -> Optional[Any]:
+ """Access underlying ContextGraph instance for building."""
return self._graph_builder
def store(
@@ -453,11 +452,20 @@ class AgentContext:
elif isinstance(doc, dict):
if "content" not in doc:
raise ValueError(f"Document dict must have 'content' key: {doc}")
- documents.append({
+
+ doc_dict = {
"content": doc["content"],
"id": doc.get("id", f"doc_{i}"),
"metadata": doc.get("metadata", {})
- })
+ }
+
+ # Preserve entities and relationships if present
+ if "entities" in doc:
+ doc_dict["entities"] = doc["entities"]
+ if "relationships" in doc:
+ doc_dict["relationships"] = doc["relationships"]
+
+ documents.append(doc_dict)
else:
raise ValueError(f"Unsupported document type: {type(doc)}")
return documents
diff --git a/semantica/context/agent_memory.py b/semantica/context/agent_memory.py
index a7dc0887..72f65ee8 100644
--- a/semantica/context/agent_memory.py
+++ b/semantica/context/agent_memory.py
@@ -60,8 +60,11 @@ from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional, Union
+import numpy as np
+
from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
+from ..utils.progress_tracker import get_progress_tracker
from ..utils.types import EntityDict, RelationshipDict
@@ -80,14 +83,11 @@ class MemoryItem:
class AgentMemory:
"""
- Agent memory manager with RAG integration.
-
- • Persistent memory storage for agents
- • Context retrieval from vector stores
- • Knowledge graph context integration
- • Conversation history management
- • Context accumulation over time
- • Memory retrieval for agent decision-making
+ Agent memory manager with RAG integration and Hierarchical Memory.
+
+ • Short-term Memory: In-memory buffer for recent context
+ • Long-term Memory: Vector store for persistent semantic history
+ • Knowledge Graph: Structured context integration
"""
def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
@@ -99,9 +99,9 @@ class AgentMemory:
**kwargs: Additional configuration options:
- vector_store: Vector store instance
- knowledge_graph: Knowledge graph instance
- - retention_policy: Memory retention policy (e.g., "30_days", "unlimited")
- - max_memory_size: Maximum number of memory items
- - embedding_model: Embedding model for memory items
+ - retention_policy: Memory retention policy
+ - max_memory_size: Max items in memory index
+ - short_term_limit: Size of short-term memory buffer (default: 10)
"""
self.logger = get_logger("agent_memory")
self.config = config or {}
@@ -112,10 +112,16 @@ class AgentMemory:
self.retention_policy = self.config.get("retention_policy", "unlimited")
self.max_memory_size = self.config.get("max_memory_size", 10000)
+ self.short_term_limit = self.config.get("short_term_limit", 10)
+ self.token_limit = self.config.get("token_limit", 2000) # Default 2000 tokens for short-term
# In-memory storage
self.memory_items: Dict[str, MemoryItem] = {}
self.memory_index: deque = deque(maxlen=self.max_memory_size)
+
+ # Hierarchical Memory: Short-term buffer
+ # Note: We use a list instead of deque for short-term to support flexible pruning (tokens & count)
+ self.short_term_memory: List[MemoryItem] = []
# Initialize progress tracker
self.progress_tracker = get_progress_tracker()
@@ -132,7 +138,7 @@ class AgentMemory:
**options,
) -> str:
"""
- Store memory item.
+ Store memory item (Write-Through to Short-term and Long-term).
Args:
content: Memory content
@@ -142,6 +148,7 @@ class AgentMemory:
**options: Additional options:
- memory_id: Custom memory ID
- timestamp: Custom timestamp
+ - skip_vector: If True, skip vector store (Short-term only)
Returns:
Memory ID
@@ -168,8 +175,13 @@ class AgentMemory:
memory_id=memory_id,
)
- # Generate embedding if vector store available
- if self.vector_store:
+ # 1. Update Short-Term Memory
+ self.short_term_memory.append(memory_item)
+ self._prune_short_term_memory()
+
+ # 2. Update Long-Term Memory (Vector Store)
+ skip_vector = options.get("skip_vector", False)
+ if self.vector_store and not skip_vector:
try:
self.progress_tracker.update_tracking(
tracking_id, message="Generating embedding..."
@@ -178,24 +190,22 @@ class AgentMemory:
memory_item.embedding = embedding
# Store in vector store
- if hasattr(self.vector_store, "add"):
- self.vector_store.add(
- id=memory_id,
- vector=embedding,
- metadata={
- "content": content,
- "timestamp": timestamp.isoformat(),
- **(metadata or {}),
- },
- )
+ if hasattr(self.vector_store, "store_vectors"):
+ # Use concrete VectorStore implementation
+ vectors = [np.array(memory_item.embedding)] if isinstance(memory_item.embedding, list) else [memory_item.embedding]
+ meta = [memory_item.metadata]
+ self.vector_store.store_vectors(vectors=vectors, metadata=meta)
+ elif hasattr(self.vector_store, "add"):
+ # Use VectorStore protocol
+ self.vector_store.add([memory_item])
except Exception as e:
- self.logger.warning(f"Failed to generate embedding: {e}")
+ self.logger.warning(f"Failed to store in vector store: {e}")
- # Store in memory
+ # Store in main memory dict (Persistent Layer Abstraction)
self.memory_items[memory_id] = memory_item
self.memory_index.append(memory_id)
- # Update knowledge graph if available
+ # 3. Update Knowledge Graph
if self.knowledge_graph and entities:
self.progress_tracker.update_tracking(
tracking_id, message="Updating knowledge graph..."
@@ -225,6 +235,10 @@ class AgentMemory:
)
raise
+ def forget(self, memory_id: str) -> bool:
+ """Forget a memory (Implementation of MemoryManager)."""
+ return self.delete_memory(memory_id)
+
def retrieve(
self, query: str, max_results: int = 5, min_score: float = 0.0, **filters
) -> List[Dict[str, Any]]:
@@ -253,20 +267,50 @@ class AgentMemory:
try:
results = []
+ seen_ids = set()
+
+ # 1. Check Short-Term Memory (Recent Context)
+ short_term_results = self._search_short_term(query, filters)
+ for res in short_term_results:
+ if res["memory_id"] not in seen_ids:
+ results.append(res)
+ seen_ids.add(res["memory_id"])
- # Vector-based retrieval
+ # 2. Vector-based retrieval (Long-Term Memory)
if self.vector_store:
self.progress_tracker.update_tracking(
tracking_id, message="Searching vector store..."
)
try:
- if hasattr(self.vector_store, "search"):
+ vector_results = []
+ if hasattr(self.vector_store, "search_vectors"):
+ # Use concrete VectorStore implementation
+ query_vector = self._generate_embedding(query)
+ query_vector = np.array(query_vector) if isinstance(query_vector, list) else query_vector
+
+ raw_results = self.vector_store.search_vectors(
+ query_vector=query_vector, k=max_results * 2
+ )
+ # Convert dict results to objects with .id attribute
+ class ResultObj:
+ def __init__(self, d):
+ self.id = d.get("id")
+ self.score = d.get("score")
+ self.metadata = d.get("metadata")
+ vector_results = [ResultObj(r) for r in raw_results]
+
+ elif hasattr(self.vector_store, "search"):
vector_results = self.vector_store.search(
- query=query, top_k=max_results * 2
+ query=query, limit=max_results * 2
)
for result in vector_results:
- memory_id = result.get("id")
+ memory_id = result.id
+
+ # Skip if already found in short-term
+ if memory_id in seen_ids:
+ continue
+
if memory_id in self.memory_items:
memory_item = self.memory_items[memory_id]
@@ -278,17 +322,18 @@ class AgentMemory:
{
"memory_id": memory_id,
"content": memory_item.content,
- "score": result.get("score", 0.0),
+ "score": result.score,
"timestamp": memory_item.timestamp.isoformat(),
"metadata": memory_item.metadata,
"entities": memory_item.entities,
"relationships": memory_item.relationships,
}
)
+ seen_ids.add(memory_id)
except Exception as e:
self.logger.warning(f"Vector retrieval failed: {e}")
- # Fallback to keyword search if no vector store
+ # 3. Fallback to keyword search if no results yet
if not results:
self.progress_tracker.update_tracking(
tracking_id, message="Performing keyword search..."
@@ -435,6 +480,40 @@ class AgentMemory:
return history
+ def _search_short_term(
+ self, query: str, filters: Dict[str, Any]
+ ) -> List[Dict[str, Any]]:
+ """Search short-term memory (simple keyword match)."""
+ results = []
+ query_terms = query.lower().split()
+
+ # Iterate through short-term memory (most recent first)
+ for item in reversed(self.short_term_memory):
+ if not self._matches_filters(item, filters):
+ continue
+
+ content_lower = item.content.lower()
+
+ # Simple scoring based on term overlap
+ matches = sum(1 for term in query_terms if term in content_lower)
+ if matches > 0:
+ score = matches / len(query_terms)
+ # Boost score for recent items (short-term)
+ score = min(1.0, score + 0.1)
+
+ results.append({
+ "memory_id": item.memory_id,
+ "content": item.content,
+ "score": score,
+ "timestamp": item.timestamp.isoformat(),
+ "metadata": item.metadata,
+ "entities": item.entities,
+ "relationships": item.relationships,
+ "source": "short_term"
+ })
+
+ return results
+
def _generate_memory_id(self) -> str:
"""Generate unique memory ID."""
import hashlib
@@ -446,6 +525,36 @@ class AgentMemory:
return f"mem_{memory_hash}"
+ def _prune_short_term_memory(self) -> None:
+ """
+ Prune short-term memory based on count and token limits.
+
+ Removes oldest items until constraints are met.
+ """
+ # 1. Prune by count
+ while len(self.short_term_memory) > self.short_term_limit:
+ self.short_term_memory.pop(0) # Remove oldest
+
+ # 2. Prune by tokens
+ current_tokens = sum(self._count_tokens(item.content) for item in self.short_term_memory)
+
+ while current_tokens > self.token_limit and self.short_term_memory:
+ removed_item = self.short_term_memory.pop(0) # Remove oldest
+ current_tokens -= self._count_tokens(removed_item.content)
+
+ def _count_tokens(self, text: str) -> int:
+ """
+ Estimate token count (approximation).
+
+ Args:
+ text: Input text
+
+ Returns:
+ Estimated token count
+ """
+ # Simple approximation: 1 token ≈ 4 characters
+ return len(text) // 4
+
def _generate_embedding(self, content: str) -> Any:
"""Generate embedding for content."""
# This would use an embedding model
@@ -463,6 +572,43 @@ class AgentMemory:
if not self.knowledge_graph:
return
+ # Check for GraphStore protocol (add_nodes method)
+ if hasattr(self.knowledge_graph, "add_nodes"):
+ # Convert to dicts for ContextGraph
+ graph_nodes = []
+ for entity in entities:
+ entity_id = entity.get("id") or entity.get("entity_id")
+ if entity_id:
+ graph_nodes.append({
+ "id": entity_id,
+ "type": entity.get("type", "entity"),
+ "properties": {
+ "content": entity.get("text") or entity.get("label") or entity_id,
+ **entity
+ }
+ })
+ if graph_nodes:
+ self.knowledge_graph.add_nodes(graph_nodes)
+
+ if relationships:
+ graph_edges = []
+ for rel in relationships:
+ source = rel.get("source_id")
+ target = rel.get("target_id")
+ if source and target:
+ graph_edges.append({
+ "source_id": source,
+ "target_id": target,
+ "type": rel.get("type", "related_to"),
+ "weight": rel.get("confidence", 1.0),
+ "properties": rel
+ })
+ if graph_edges:
+ self.knowledge_graph.add_edges(graph_edges)
+
+ return
+
+ # Legacy dict update
# Add entities to graph
graph_entities = self.knowledge_graph.get("entities", [])
existing_ids = {e.get("id") for e in graph_entities}
diff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.py
index 08fd82e3..fef51c23 100644
--- a/semantica/context/context_graph.py
+++ b/semantica/context/context_graph.py
@@ -1,140 +1,359 @@
"""
-Context Graph Builder
+Context Graph Implementation
-This module provides comprehensive context graph construction capabilities,
-formalizing context as a graph of connections. It turns context from intuition
-into infrastructure, enabling meaningful connections between concepts, entities,
-and conversations.
+This module provides a synchronous, in-memory implementation of the GraphStore protocol,
+designed for building and querying context graphs from conversations and entities.
-Algorithms Used:
-
-Graph Construction:
- - Node Creation: Dictionary-based node storage with type indexing
- - Edge Creation: List-based edge storage with type indexing
- - Entity Extraction: Entity extraction from conversations and text
- - Relationship Extraction: Relationship extraction from conversations
- - Intent Extraction: Intent classification from conversations
- - Sentiment Analysis: Sentiment extraction from conversations
- - URI Assignment: Entity linker-based URI assignment for entities
-
-Graph Traversal:
- - BFS (Breadth-First Search): Multi-hop neighbor discovery
- - Graph Indexing: Type-based indexing for efficient node/edge lookup
- - Neighbor Discovery: Outgoing and incoming edge traversal
- - Multi-hop Expansion: Iterative expansion for related entities
-
-Graph Querying:
- - Type Filtering: Node type-based filtering
- - Metadata Filtering: Dictionary-based metadata matching
- - Graph Statistics: Node and edge type counting
+It formalizes context as a graph of connections, enabling meaningful connections between
+concepts, entities, and conversations.
Key Features:
- - Builds context graphs from entities, relationships, and conversations
- - Creates meaningful connections between concepts
- - Assigns URLs/URIs to entities for web-like context
- - Formalizes context into graph structure
- - Supports ontology-based context graphs
- - Enables context traversal and querying
- - Conversation-based graph construction
- - Intent and sentiment extraction
- - Multi-hop relationship traversal
- - Graph statistics and analytics
-
-Main Classes:
- - ContextNode: Context graph node data structure with node_id, node_type, content, metadata, properties
- - ContextEdge: Context graph edge data structure with source_id, target_id, edge_type, weight, metadata
- - ContextGraphBuilder: Context graph builder for formalizing context
-
-Example Usage:
- >>> from semantica.context import ContextGraphBuilder
- >>> builder = ContextGraphBuilder()
- >>> graph = builder.build_from_entities_and_relationships(entities, relationships)
- >>> builder.add_node("node1", "entity", "Python programming")
- >>> builder.add_edge("node1", "node2", "related_to", weight=0.9)
- >>> neighbors = builder.get_neighbors("node1", max_hops=2)
- >>> results = builder.query(node_type="entity", confidence=0.8)
-
-Author: Semantica Contributors
-License: MIT
+ - In-memory GraphStore implementation
+ - Entity and relationship extraction from conversations
+ - BFS-based neighbor discovery
+ - Type-based indexing
+ - Export to dictionary format
"""
-from collections import defaultdict
+from collections import defaultdict, deque
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional, Set, Union
+from typing import Any, Dict, List, Optional, Set, Union, Tuple
-from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.exceptions import ProcessingError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
from ..utils.types import EntityDict, RelationshipDict
from .entity_linker import EntityLinker
-
@dataclass
class ContextNode:
- """Context graph node."""
-
+ """Context graph node (Internal implementation)."""
node_id: str
- node_type: str # "entity", "concept", "document", "intent", etc.
+ node_type: str
content: str
metadata: Dict[str, Any] = field(default_factory=dict)
properties: Dict[str, Any] = field(default_factory=dict)
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert to dictionary format."""
+ props = self.properties.copy()
+ props.update(self.metadata)
+ props["content"] = self.content
+ return {
+ "id": self.node_id,
+ "type": self.node_type,
+ "properties": props
+ }
@dataclass
class ContextEdge:
- """Context graph edge."""
-
+ """Context graph edge (Internal implementation)."""
source_id: str
target_id: str
edge_type: str
weight: float = 1.0
metadata: Dict[str, Any] = field(default_factory=dict)
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert to dictionary format."""
+ return {
+ "source_id": self.source_id,
+ "target_id": self.target_id,
+ "type": self.edge_type,
+ "weight": self.weight,
+ "properties": self.metadata
+ }
-class ContextGraphBuilder:
+class ContextGraph:
"""
- Context graph builder for formalizing context as connections.
-
- • Builds context graphs from entities and relationships
- • Creates meaningful connections between concepts
- • Assigns URLs/URIs to entities for web-like context
- • Formalizes context into graph structure
- • Supports ontology-based context graphs
- • Enables context traversal and querying
+ In-memory implementation of context graph.
+
+ Provides capabilities to build, store, and query a context graph.
"""
def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
"""
- Initialize context graph builder.
+ Initialize context graph.
Args:
config: Configuration dictionary
**kwargs: Additional configuration options:
- extract_entities: Extract entities from content (default: True)
- extract_relationships: Extract relationships (default: True)
- - link_external_entities: Link to external entities (default: True)
- entity_linker: Entity linker instance
"""
- self.logger = get_logger("context_graph_builder")
+ self.logger = get_logger("context_graph")
self.config = config or {}
self.config.update(kwargs)
self.extract_entities = self.config.get("extract_entities", True)
self.extract_relationships = self.config.get("extract_relationships", True)
- self.link_external_entities = self.config.get("link_external_entities", True)
-
+
self.entity_linker = self.config.get("entity_linker") or EntityLinker()
# Graph structure
self.nodes: Dict[str, ContextNode] = {}
self.edges: List[ContextEdge] = []
-
- # Initialize progress tracker
- self.progress_tracker = get_progress_tracker()
+
+ # Adjacency list for efficient traversal: source_id -> list of edges
+ self._adjacency: Dict[str, List[ContextEdge]] = defaultdict(list)
# Indexes
self.node_type_index: Dict[str, Set[str]] = defaultdict(set)
self.edge_type_index: Dict[str, List[ContextEdge]] = defaultdict(list)
+
+ # Progress tracker
+ self.progress_tracker = get_progress_tracker()
+
+ # --- GraphStore Protocol Implementation ---
+
+ def add_nodes(self, nodes: List[Dict[str, Any]]) -> int:
+ """
+ Add nodes to graph.
+
+ Args:
+ nodes: List of nodes to add (dicts with id, type, properties)
+
+ Returns:
+ Number of nodes added
+ """
+ count = 0
+ for node in nodes:
+ # Extract content from properties if not explicit
+ node_props = node.get("properties", {})
+ content = node_props.get("content", node.get("id"))
+ metadata = {k: v for k, v in node_props.items() if k != "content"}
+
+ internal_node = ContextNode(
+ node_id=node.get("id"),
+ node_type=node.get("type", "entity"),
+ content=content,
+ metadata=metadata,
+ properties=node_props
+ )
+
+ if self._add_internal_node(internal_node):
+ count += 1
+ return count
+
+ def add_edges(self, edges: List[Dict[str, Any]]) -> int:
+ """
+ Add edges to graph.
+
+ Args:
+ edges: List of edges to add (dicts with source_id, target_id, type, weight, properties)
+
+ Returns:
+ Number of edges added
+ """
+ count = 0
+ for edge in edges:
+ internal_edge = ContextEdge(
+ source_id=edge.get("source_id"),
+ target_id=edge.get("target_id"),
+ edge_type=edge.get("type", "related_to"),
+ weight=edge.get("weight", 1.0),
+ metadata=edge.get("properties", {})
+ )
+
+ if self._add_internal_edge(internal_edge):
+ count += 1
+ return count
+
+ def get_neighbors(self, node_id: str, hops: int = 1) -> List[Dict[str, Any]]:
+ """
+ Get neighbors of a node.
+
+ Returns list of dicts with neighbor info.
+ """
+ if node_id not in self.nodes:
+ return []
+
+ neighbors = []
+ visited = {node_id}
+ queue = deque([(node_id, 0)]) # (current_id, current_hop)
+
+ while queue:
+ current_id, current_hop = queue.popleft()
+
+ if current_hop >= hops:
+ continue
+
+ # Get outgoing edges
+ outgoing_edges = self._adjacency.get(current_id, [])
+ for edge in outgoing_edges:
+ neighbor_id = edge.target_id
+ if neighbor_id not in visited:
+ visited.add(neighbor_id)
+ queue.append((neighbor_id, current_hop + 1))
+
+ if neighbor_id in self.nodes:
+ node = self.nodes[neighbor_id]
+ neighbors.append({
+ "id": node.node_id,
+ "type": node.node_type,
+ "content": node.content,
+ "relationship": edge.edge_type,
+ "weight": edge.weight,
+ "hop": current_hop + 1
+ })
+
+ return neighbors
+
+ def query(self, query: str) -> List[Dict[str, Any]]:
+ """
+ Execute a simple keyword search query on the graph nodes.
+
+ Args:
+ query: Keyword query string
+
+ Returns:
+ List of matching node dicts
+ """
+ results = []
+ query_lower = query.lower().split()
+
+ for node in self.nodes.values():
+ content_lower = node.content.lower()
+ if any(word in content_lower for word in query_lower):
+ # Calculate simple score
+ overlap = sum(1 for word in query_lower if word in content_lower)
+ score = overlap / len(query_lower) if query_lower else 0.0
+
+ results.append({
+ "node": node.to_dict(),
+ "score": score,
+ "content": node.content
+ })
+
+ return sorted(results, key=lambda x: x["score"], reverse=True)
+
+ def add_node(self, node_id: str, node_type: str, content: Optional[str] = None, **properties) -> bool:
+ """
+ Add a single node to the graph.
+
+ Args:
+ node_id: Unique identifier
+ node_type: Node type (e.g., 'entity', 'concept')
+ content: Node content/label
+ **properties: Additional properties
+ """
+ content = content or node_id
+ return self._add_internal_node(ContextNode(
+ node_id=node_id,
+ node_type=node_type,
+ content=content,
+ metadata=properties,
+ properties=properties
+ ))
+
+ def add_edge(self, source_id: str, target_id: str, edge_type: str = "related_to", weight: float = 1.0, **properties) -> bool:
+ """
+ Add a single edge to the graph.
+
+ Args:
+ source_id: Source node ID
+ target_id: Target node ID
+ edge_type: Relationship type
+ weight: Edge weight
+ **properties: Additional properties
+ """
+ return self._add_internal_edge(ContextEdge(
+ source_id=source_id,
+ target_id=target_id,
+ edge_type=edge_type,
+ weight=weight,
+ metadata=properties
+ ))
+
+ def find_node(self, node_id: str) -> Optional[Dict[str, Any]]:
+ """Find a node by ID."""
+ node = self.nodes.get(node_id)
+ if node:
+ return {
+ "id": node.node_id,
+ "type": node.node_type,
+ "content": node.content,
+ "metadata": node.metadata
+ }
+ return None
+
+ def find_nodes(self, node_type: Optional[str] = None) -> List[Dict[str, Any]]:
+ """Find nodes, optionally filtered by type."""
+ if node_type:
+ node_ids = self.node_type_index.get(node_type, set())
+ nodes = [self.nodes[nid] for nid in node_ids]
+ else:
+ nodes = self.nodes.values()
+
+ return [
+ {
+ "id": n.node_id,
+ "type": n.node_type,
+ "content": n.content,
+ "metadata": n.metadata
+ }
+ for n in nodes
+ ]
+
+ def find_edges(self, edge_type: Optional[str] = None) -> List[Dict[str, Any]]:
+ """Find edges, optionally filtered by type."""
+ if edge_type:
+ edges = self.edge_type_index.get(edge_type, [])
+ else:
+ edges = self.edges
+
+ return [
+ {
+ "source": e.source_id,
+ "target": e.target_id,
+ "type": e.edge_type,
+ "weight": e.weight,
+ "metadata": e.metadata
+ }
+ for e in edges
+ ]
+
+ def stats(self) -> Dict[str, Any]:
+ """Get graph statistics."""
+ return {
+ "node_count": len(self.nodes),
+ "edge_count": len(self.edges),
+ "node_types": {k: len(v) for k, v in self.node_type_index.items()},
+ "edge_types": {k: len(v) for k, v in self.edge_type_index.items()},
+ "density": self.density()
+ }
+
+ def density(self) -> float:
+ """Calculate graph density."""
+ n = len(self.nodes)
+ if n < 2:
+ return 0.0
+ max_edges = n * (n - 1) # Directed graph
+ return len(self.edges) / max_edges
+
+ # --- Internal Helpers ---
+
+ def _add_internal_node(self, node: ContextNode) -> bool:
+ """Internal method to add a node."""
+ self.nodes[node.node_id] = node
+ self.node_type_index[node.node_type].add(node.node_id)
+ return True
+
+ def _add_internal_edge(self, edge: ContextEdge) -> bool:
+ """Internal method to add an edge."""
+ # Ensure nodes exist
+ if edge.source_id not in self.nodes:
+ self._add_internal_node(ContextNode(edge.source_id, "entity", edge.source_id))
+ if edge.target_id not in self.nodes:
+ self._add_internal_node(ContextNode(edge.target_id, "entity", edge.target_id))
+
+ self.edges.append(edge)
+ self.edge_type_index[edge.edge_type].append(edge)
+ self._adjacency[edge.source_id].append(edge)
+ return True
+
+ # --- Builder Methods (Legacy/Utility) ---
def build_from_conversations(
self,
@@ -145,991 +364,219 @@ class ContextGraphBuilder:
**options,
) -> Dict[str, Any]:
"""
- Build context graph from conversations.
-
+ Build context graph from conversations and return dict representation.
+
Args:
conversations: List of conversation files or dictionaries
- link_entities: Link entities across conversations
- extract_intents: Extract conversation intents
- extract_sentiments: Extract sentiment information
- **options: Additional options
-
+ ...
+
Returns:
- Context graph dictionary
+ Graph dictionary (nodes, edges)
"""
- # Track context graph building
tracking_id = self.progress_tracker.start_tracking(
file=None,
module="context",
- submodule="ContextGraphBuilder",
+ submodule="ContextGraph",
message=f"Building graph from {len(conversations)} conversations",
)
try:
- self.logger.info(
- f"Building context graph from {len(conversations)} conversations"
- )
-
- self.progress_tracker.update_tracking(
- tracking_id, message="Processing conversations..."
- )
- # Process each conversation
for conv in conversations:
- if isinstance(conv, str):
- # Load conversation from file
- conv_data = self._load_conversation(conv)
- else:
- conv_data = conv
-
+ conv_data = conv if isinstance(conv, dict) else self._load_conversation(conv)
self._process_conversation(
- conv_data,
+ conv_data,
extract_intents=extract_intents,
- extract_sentiments=extract_sentiments,
+ extract_sentiments=extract_sentiments
)
- # Link entities if requested
if link_entities:
- self.progress_tracker.update_tracking(
- tracking_id, message="Linking entities..."
- )
self._link_entities()
- # Build graph structure
- self.progress_tracker.update_tracking(
- tracking_id, message="Building graph structure..."
- )
- graph = self._build_graph_structure()
-
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message=f"Built graph with {len(self.nodes)} nodes, {len(self.edges)} edges",
- )
- self.logger.info(
- f"Built context graph: {len(self.nodes)} nodes, {len(self.edges)} edges"
- )
-
- return graph
+ self.progress_tracker.stop_tracking(tracking_id, status="completed")
+ return self.to_dict()
except Exception as e:
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message=str(e)
- )
+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))
raise
def build_from_entities_and_relationships(
self,
- entities: List[EntityDict],
- relationships: List[RelationshipDict],
- **options,
+ entities: List[Dict[str, Any]],
+ relationships: List[Dict[str, Any]],
+ **kwargs
) -> Dict[str, Any]:
"""
- Build context graph from entities and relationships.
-
+ Build graph from entities and relationships.
+
Args:
- entities: List of entities
- relationships: List of relationships
- **options: Additional options
-
+ entities: List of entity dictionaries
+ relationships: List of relationship dictionaries
+ **kwargs: Additional options
+
Returns:
- Context graph dictionary
+ Graph dictionary (nodes, edges)
"""
- # Track context graph building
tracking_id = self.progress_tracker.start_tracking(
file=None,
module="context",
- submodule="ContextGraphBuilder",
- message=f"Building graph from {len(entities)} entities, {len(relationships)} relationships",
+ submodule="ContextGraph",
+ message=f"Building graph from {len(entities)} entities and {len(relationships)} relationships",
)
try:
- self.progress_tracker.update_tracking(
- tracking_id, message="Adding entities as nodes..."
- )
- # Add entities as nodes
+ # Add entities
for entity in entities:
entity_id = entity.get("id") or entity.get("entity_id")
- if not entity_id:
- continue
-
- node = ContextNode(
- node_id=entity_id,
- node_type="entity",
- content=entity.get("text")
- or entity.get("label")
- or entity.get("name", ""),
- metadata={
- "type": entity.get("type") or entity.get("entity_type"),
- "confidence": entity.get("confidence", 1.0),
- **entity.get("metadata", {}),
- },
- properties=entity.get("properties", {}),
- )
-
- self.nodes[entity_id] = node
- self.node_type_index["entity"].add(entity_id)
-
- # Assign URI if entity linker available
- if self.entity_linker:
- self.entity_linker.assign_uri(
- entity_id, node.content, node.metadata.get("type")
- )
-
- # Add relationships as edges
- self.progress_tracker.update_tracking(
- tracking_id, message="Adding relationships as edges..."
- )
+ if entity_id:
+ self._add_internal_node(ContextNode(
+ node_id=entity_id,
+ node_type=entity.get("type", "entity"),
+ content=entity.get("text") or entity.get("label") or entity_id,
+ metadata=entity,
+ properties=entity
+ ))
+
+ # Add relationships
for rel in relationships:
- source_id = rel.get("source_id")
- target_id = rel.get("target_id")
-
- if not source_id or not target_id:
- continue
-
- # Ensure source and target nodes exist
- if source_id not in self.nodes:
- self.nodes[source_id] = ContextNode(
- node_id=source_id, node_type="entity", content=source_id
- )
-
- if target_id not in self.nodes:
- self.nodes[target_id] = ContextNode(
- node_id=target_id, node_type="entity", content=target_id
- )
-
- edge = ContextEdge(
- source_id=source_id,
- target_id=target_id,
- edge_type=rel.get("type")
- or rel.get("relationship_type", "related_to"),
- weight=rel.get("confidence", 1.0),
- metadata=rel.get("metadata", {}),
- )
-
- self.edges.append(edge)
- self.edge_type_index[edge.edge_type].append(edge)
-
- # Build graph structure
- self.progress_tracker.update_tracking(
- tracking_id, message="Building graph structure..."
- )
- graph = self._build_graph_structure()
-
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message=f"Built graph with {len(self.nodes)} nodes, {len(self.edges)} edges",
- )
- return graph
+ source = rel.get("source_id")
+ target = rel.get("target_id")
+ if source and target:
+ self._add_internal_edge(ContextEdge(
+ source_id=source,
+ target_id=target,
+ edge_type=rel.get("type", "related_to"),
+ weight=rel.get("confidence", 1.0),
+ metadata=rel
+ ))
+
+ self.progress_tracker.stop_tracking(tracking_id, status="completed")
+ return self.to_dict()
except Exception as e:
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message=str(e)
- )
+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))
raise
- def add_node(self, node_id: str, node_type: str, content: str, **metadata) -> bool:
- """
- Add node to context graph.
-
- Args:
- node_id: Node identifier
- node_type: Node type
- content: Node content
- **metadata: Additional metadata
-
- Returns:
- True if node added successfully
- """
- node = ContextNode(
- node_id=node_id, node_type=node_type, content=content, metadata=metadata
- )
-
- self.nodes[node_id] = node
- self.node_type_index[node_type].add(node_id)
-
- self.logger.debug(f"Added node: {node_id} ({node_type})")
- return True
-
- def add_edge(
- self,
- source_id: str,
- target_id: str,
- edge_type: str = "related_to",
- weight: float = 1.0,
- **metadata,
- ) -> bool:
- """
- Add edge to context graph.
-
- Args:
- source_id: Source node ID
- target_id: Target node ID
- edge_type: Edge type
- weight: Edge weight
- **metadata: Additional metadata
-
- Returns:
- True if edge added successfully
- """
- # Ensure nodes exist
- if source_id not in self.nodes:
- self.add_node(source_id, "entity", source_id)
-
- if target_id not in self.nodes:
- self.add_node(target_id, "entity", target_id)
-
- edge = ContextEdge(
- source_id=source_id,
- target_id=target_id,
- edge_type=edge_type,
- weight=weight,
- metadata=metadata,
- )
-
- self.edges.append(edge)
- self.edge_type_index[edge_type].append(edge)
-
- self.logger.debug(f"Added edge: {source_id} --{edge_type}--> {target_id}")
- return True
-
- def _process_conversation(
- self,
- conv_data: Dict[str, Any],
- extract_intents: bool = False,
- extract_sentiments: bool = False,
- ) -> None:
- """Process a conversation and add to graph."""
- # Extract conversation ID
+ def _process_conversation(self, conv_data: Dict[str, Any], **kwargs) -> None:
+ """Process a single conversation."""
conv_id = conv_data.get("id") or f"conv_{hash(str(conv_data)) % 10000}"
+
+ # Add conversation node
+ self._add_internal_node(ContextNode(
+ node_id=conv_id,
+ node_type="conversation",
+ content=conv_data.get("content", "") or conv_data.get("summary", ""),
+ metadata={"timestamp": conv_data.get("timestamp")}
+ ))
- # Add conversation as node
- self.add_node(
- conv_id,
- "conversation",
- conv_data.get("content", "") or conv_data.get("summary", ""),
- **{
- "timestamp": conv_data.get("timestamp"),
- "participants": conv_data.get("participants", []),
- **conv_data.get("metadata", {}),
- },
- )
+ # Track name to ID mapping for relationship resolution
+ name_to_id = {}
# Extract entities
if self.extract_entities:
- entities = conv_data.get("entities", [])
- for entity in entities:
+ for entity in conv_data.get("entities", []):
entity_id = entity.get("id") or entity.get("entity_id")
+ entity_text = entity.get("text") or entity.get("label") or entity.get("name") or entity_id
+ entity_type = entity.get("type", "entity")
+
+ # Generate ID if missing
+ if not entity_id and entity_text and self.entity_linker:
+ # Use EntityLinker to generate ID
+ if hasattr(self.entity_linker, "_generate_entity_id"):
+ entity_id = self.entity_linker._generate_entity_id(entity_text, entity_type)
+ else:
+ # Fallback ID generation
+ import hashlib
+ entity_hash = hashlib.md5(f"{entity_text}_{entity_type}".encode()).hexdigest()[:12]
+ entity_id = f"{entity_type.lower()}_{entity_hash}"
+
if entity_id:
- self.add_node(
- entity_id,
- "entity",
- entity.get("text") or entity.get("label", ""),
- **{
- "type": entity.get("type"),
- "confidence": entity.get("confidence", 1.0),
- },
- )
-
- # Link entity to conversation
- self.add_edge(
- conv_id,
- entity_id,
- "mentions",
- weight=entity.get("confidence", 1.0),
- )
+ if entity_text:
+ name_to_id[entity_text] = entity_id
+
+ self._add_internal_node(ContextNode(
+ node_id=entity_id,
+ node_type="entity",
+ content=entity_text,
+ metadata={"type": entity_type, **entity}
+ ))
+ self._add_internal_edge(ContextEdge(
+ source_id=conv_id,
+ target_id=entity_id,
+ edge_type="mentions"
+ ))
# Extract relationships
if self.extract_relationships:
- relationships = conv_data.get("relationships", [])
- for rel in relationships:
- source_id = rel.get("source_id")
- target_id = rel.get("target_id")
-
- if source_id and target_id:
- self.add_edge(
- source_id,
- target_id,
- rel.get("type", "related_to"),
- weight=rel.get("confidence", 1.0),
- )
-
- # Extract intents
- if extract_intents:
- intents = conv_data.get("intents", [])
- for intent in intents:
- intent_id = f"{conv_id}_intent_{len(intents)}"
- self.add_node(
- intent_id,
- "intent",
- intent.get("text", ""),
- **{"confidence": intent.get("confidence", 1.0)},
- )
- self.add_edge(conv_id, intent_id, "has_intent")
-
- # Extract sentiments
- if extract_sentiments:
- sentiment = conv_data.get("sentiment")
- if sentiment:
- sentiment_id = f"{conv_id}_sentiment"
- self.add_node(
- sentiment_id,
- "sentiment",
- sentiment.get("label", ""),
- **{"score": sentiment.get("score", 0.0)},
- )
- self.add_edge(conv_id, sentiment_id, "has_sentiment")
+ for rel in conv_data.get("relationships", []):
+ source = rel.get("source_id")
+ target = rel.get("target_id")
+
+ # Resolve IDs from names if missing
+ if not source and rel.get("source") and rel.get("source") in name_to_id:
+ source = name_to_id[rel.get("source")]
+
+ if not target and rel.get("target") and rel.get("target") in name_to_id:
+ target = name_to_id[rel.get("target")]
+
+ if source and target:
+ self._add_internal_edge(ContextEdge(
+ source_id=source,
+ target_id=target,
+ edge_type=rel.get("type", "related_to"),
+ weight=rel.get("confidence", 1.0)
+ ))
def _link_entities(self) -> None:
- """Link entities across the graph."""
+ """Link similar entities using EntityLinker."""
if not self.entity_linker:
return
-
- # Get all entity nodes
- entity_nodes = [
- (node_id, node)
- for node_id, node in self.nodes.items()
- if node.node_type == "entity"
- ]
-
- # Link similar entities
- for i, (node_id1, node1) in enumerate(entity_nodes):
- for node_id2, node2 in entity_nodes[i + 1 :]:
- # Check if similar
+
+ entity_nodes = [n for n in self.nodes.values() if n.node_type == "entity"]
+ for i, node1 in enumerate(entity_nodes):
+ for node2 in entity_nodes[i+1:]:
similarity = self.entity_linker._calculate_text_similarity(
node1.content.lower(), node2.content.lower()
)
-
if similarity >= self.entity_linker.similarity_threshold:
- # Link entities
- self.entity_linker.link_entities(
- node_id1,
- node_id2,
- link_type="same_as" if similarity >= 0.9 else "related_to",
- confidence=similarity,
- )
-
- # Add edge to graph
- self.add_edge(
- node_id1,
- node_id2,
- "same_as" if similarity >= 0.9 else "related_to",
- weight=similarity,
- )
+ self._add_internal_edge(ContextEdge(
+ source_id=node1.node_id,
+ target_id=node2.node_id,
+ edge_type="similar_to",
+ weight=similarity
+ ))
def _load_conversation(self, file_path: str) -> Dict[str, Any]:
"""Load conversation from file."""
- from pathlib import Path
-
from ..utils.helpers import read_json_file
+ from pathlib import Path
+ return read_json_file(Path(file_path))
- path = Path(file_path)
- if not path.exists():
- raise ProcessingError(f"Conversation file not found: {file_path}")
-
- return read_json_file(path)
-
- def _build_graph_structure(self) -> Dict[str, Any]:
- """Build graph structure dictionary."""
+ def to_dict(self) -> Dict[str, Any]:
+ """Export graph to dictionary format."""
return {
"nodes": [
{
- "id": node.node_id,
- "type": node.node_type,
- "content": node.content,
- "metadata": node.metadata,
- "properties": node.properties,
+ "id": n.node_id,
+ "type": n.node_type,
+ "content": n.content,
+ "metadata": n.metadata
}
- for node in self.nodes.values()
+ for n in self.nodes.values()
],
"edges": [
{
- "source": edge.source_id,
- "target": edge.target_id,
- "type": edge.edge_type,
- "weight": edge.weight,
- "metadata": edge.metadata,
+ "source": e.source_id,
+ "target": e.target_id,
+ "type": e.edge_type,
+ "weight": e.weight
}
- for edge in self.edges
+ for e in self.edges
],
"statistics": {
"node_count": len(self.nodes),
- "edge_count": len(self.edges),
- "node_types": {
- node_type: len(node_ids)
- for node_type, node_ids in self.node_type_index.items()
- },
- "edge_types": {
- edge_type: len(edges)
- for edge_type, edges in self.edge_type_index.items()
- },
- },
- }
-
- def get_neighbors(self, node_id: str, max_hops: int = 1) -> List[str]:
- """
- Get neighbor nodes.
-
- Args:
- node_id: Node identifier
- max_hops: Maximum number of hops
-
- Returns:
- List of neighbor node IDs
- """
- neighbors = set()
- current_level = {node_id}
-
- for hop in range(max_hops):
- next_level = set()
-
- for current_id in current_level:
- # Find outgoing edges
- for edge in self.edges:
- if edge.source_id == current_id:
- next_level.add(edge.target_id)
- neighbors.add(edge.target_id)
-
- # Find incoming edges
- for edge in self.edges:
- if edge.target_id == current_id:
- next_level.add(edge.source_id)
- neighbors.add(edge.source_id)
-
- current_level = next_level
-
- return list(neighbors)
-
- def query(
- self,
- node_type: Optional[str] = None,
- edge_type: Optional[str] = None,
- **filters,
- ) -> List[Dict[str, Any]]:
- """
- Query graph nodes and edges.
-
- Args:
- node_type: Filter by node type
- edge_type: Filter by edge type
- **filters: Additional filters
-
- Returns:
- List of matching nodes
- """
- results = []
-
- for node_id, node in self.nodes.items():
- # Filter by node type
- if node_type and node.node_type != node_type:
- continue
-
- # Filter by metadata
- match = True
- for key, value in filters.items():
- if key in node.metadata and node.metadata[key] != value:
- match = False
- break
-
- if match:
- results.append(
- {
- "id": node_id,
- "type": node.node_type,
- "content": node.content,
- "metadata": node.metadata,
- }
- )
-
- return results
-
- # High-Level Construction
- def from_text(self, text: str, **options) -> Dict[str, Any]:
- """
- Build graph from plain text.
-
- Args:
- text: Plain text to build graph from
- **options: Additional options
-
- Returns:
- Graph dictionary
-
- Example:
- >>> graph = builder.from_text("Python is used for machine learning")
- """
- # Simple entity extraction (mock - in real implementation would use NLP)
- entities = []
- relationships = []
-
- # Mock extraction
- if "Python" in text:
- entities.append({"id": "e1", "text": "Python", "type": "PROGRAMMING_LANGUAGE"})
- if "machine learning" in text.lower():
- entities.append({"id": "e2", "text": "Machine Learning", "type": "CONCEPT"})
- if len(entities) >= 2:
- relationships.append({"source_id": "e1", "target_id": "e2", "type": "used_for"})
-
- return self.build_from_entities_and_relationships(entities, relationships, **options)
-
- def from_documents(self, docs: List[Union[str, Dict[str, Any]]], **options) -> Dict[str, Any]:
- """
- Build graph from document list.
-
- Args:
- docs: List of documents (strings or dicts with content)
- **options: Additional options
-
- Returns:
- Graph dictionary
-
- Example:
- >>> graph = builder.from_documents(["Doc 1", "Doc 2"])
- """
- conversations = []
- for i, doc in enumerate(docs):
- if isinstance(doc, str):
- conversations.append({
- "id": f"doc_{i}",
- "content": doc,
- "entities": [],
- "relationships": []
- })
- elif isinstance(doc, dict):
- conversations.append({
- "id": doc.get("id", f"doc_{i}"),
- "content": doc.get("content", ""),
- "entities": doc.get("entities", []),
- "relationships": doc.get("relationships", [])
- })
-
- return self.build_from_conversations(conversations, **options)
-
- def from_conversations(self, conversations: List[Dict[str, Any]], **options) -> Dict[str, Any]:
- """
- Build from conversations (alias for build_from_conversations).
-
- Args:
- conversations: List of conversations
- **options: Additional options
-
- Returns:
- Graph dictionary
-
- Example:
- >>> graph = builder.from_conversations(conversations)
- """
- return self.build_from_conversations(conversations, **options)
-
- def add(
- self,
- entities: Optional[List[EntityDict]] = None,
- relationships: Optional[List[RelationshipDict]] = None,
- **options
- ) -> Dict[str, Any]:
- """
- Simple add method.
-
- Args:
- entities: List of entities to add
- relationships: List of relationships to add
- **options: Additional options
-
- Returns:
- Graph statistics
-
- Example:
- >>> stats = builder.add(entities=entities, relationships=relationships)
- """
- if entities and relationships:
- graph = self.build_from_entities_and_relationships(entities, relationships, **options)
- return graph.get("statistics", {})
- elif entities:
- # Add entities only
- for entity in entities:
- self.add_node(
- entity.get("id", f"entity_{len(self.nodes)}"),
- entity.get("type", "entity"),
- entity.get("text", ""),
- **entity.get("metadata", {})
- )
- return {"node_count": len(self.nodes), "edge_count": len(self.edges)}
- else:
- return {"node_count": len(self.nodes), "edge_count": len(self.edges)}
-
- # Query Methods
- def find(self, query: str, **filters) -> List[Dict[str, Any]]:
- """
- Simple search in graph.
-
- Args:
- query: Search query
- **filters: Additional filters
-
- Returns:
- List of matching nodes
-
- Example:
- >>> results = builder.find("Python")
- """
- query_lower = query.lower()
- results = []
-
- for node_id, node in self.nodes.items():
- if query_lower in node.content.lower():
- results.append({
- "id": node_id,
- "type": node.node_type,
- "content": node.content,
- "metadata": node.metadata,
- })
-
- return results
-
- def find_node(self, node_id: str) -> Optional[Dict[str, Any]]:
- """
- Find node by ID.
-
- Args:
- node_id: Node ID
-
- Returns:
- Node dict or None if not found
-
- Example:
- >>> node = builder.find_node("node1")
- """
- if node_id in self.nodes:
- node = self.nodes[node_id]
- return {
- "id": node_id,
- "type": node.node_type,
- "content": node.content,
- "metadata": node.metadata,
- }
- return None
-
- def find_nodes(self, **filters) -> List[Dict[str, Any]]:
- """
- Find nodes by filters.
-
- Args:
- **filters: Filter criteria (node_type, etc.)
-
- Returns:
- List of matching nodes
-
- Example:
- >>> nodes = builder.find_nodes(node_type="entity")
- """
- return self.query(**filters)
-
- def find_edges(self, **filters) -> List[Dict[str, Any]]:
- """
- Find edges by filters.
-
- Args:
- **filters: Filter criteria (edge_type, source_id, target_id, etc.)
-
- Returns:
- List of matching edges
-
- Example:
- >>> edges = builder.find_edges(edge_type="related_to")
- """
- results = []
- edge_type = filters.get("edge_type")
- source_id = filters.get("source_id")
- target_id = filters.get("target_id")
-
- for edge in self.edges:
- if edge_type and edge.edge_type != edge_type:
- continue
- if source_id and edge.source_id != source_id:
- continue
- if target_id and edge.target_id != target_id:
- continue
-
- results.append({
- "source_id": edge.source_id,
- "target_id": edge.target_id,
- "type": edge.edge_type,
- "weight": edge.weight,
- "metadata": edge.metadata,
- })
-
- return results
-
- def find_path(self, source_id: str, target_id: str, max_hops: int = 5) -> List[Dict[str, Any]]:
- """
- Find path between nodes.
-
- Args:
- source_id: Source node ID
- target_id: Target node ID
- max_hops: Maximum hops (default: 5)
-
- Returns:
- List of nodes in path
-
- Example:
- >>> path = builder.find_path("node1", "node2", max_hops=5)
- """
- from collections import deque
-
- if source_id not in self.nodes or target_id not in self.nodes:
- return []
-
- queue = deque([(source_id, [source_id])])
- visited = {source_id}
-
- while queue:
- current_id, path = queue.popleft()
-
- if len(path) > max_hops:
- continue
-
- if current_id == target_id:
- # Return path with node info
- path_info = []
- for node_id in path:
- node = self.nodes.get(node_id)
- if node:
- path_info.append({
- "id": node_id,
- "type": node.node_type,
- "content": node.content,
- })
- return path_info
-
- # Get neighbors
- for edge in self.edges:
- neighbor_id = None
- if edge.source_id == current_id:
- neighbor_id = edge.target_id
- elif edge.target_id == current_id:
- neighbor_id = edge.source_id
-
- if neighbor_id and neighbor_id not in visited:
- visited.add(neighbor_id)
- queue.append((neighbor_id, path + [neighbor_id]))
-
- return []
-
- # Graph Operations
- def get_subgraph(self, node_ids: List[str]) -> Dict[str, Any]:
- """
- Get subgraph.
-
- Args:
- node_ids: List of node IDs to include
-
- Returns:
- Subgraph dict with nodes and edges
-
- Example:
- >>> subgraph = builder.get_subgraph(["node1", "node2"])
- """
- subgraph_nodes = {}
- subgraph_edges = []
-
- node_set = set(node_ids)
-
- # Get nodes
- for node_id in node_ids:
- if node_id in self.nodes:
- subgraph_nodes[node_id] = self.nodes[node_id]
-
- # Get edges between these nodes
- for edge in self.edges:
- if edge.source_id in node_set and edge.target_id in node_set:
- subgraph_edges.append(edge)
-
- return {
- "nodes": {nid: {
- "id": nid,
- "type": node.node_type,
- "content": node.content,
- "metadata": node.metadata,
- } for nid, node in subgraph_nodes.items()},
- "edges": [{
- "source_id": e.source_id,
- "target_id": e.target_id,
- "type": e.edge_type,
- "weight": e.weight,
- } for e in subgraph_edges],
- "statistics": {
- "node_count": len(subgraph_nodes),
- "edge_count": len(subgraph_edges),
+ "edge_count": len(self.edges)
}
}
- def merge(self, other_graph: 'ContextGraphBuilder') -> Dict[str, Any]:
- """
- Merge with another graph.
-
- Args:
- other_graph: Another ContextGraphBuilder instance
-
- Returns:
- Merge statistics
-
- Example:
- >>> stats = builder.merge(other_builder)
- """
- merged_nodes = 0
- merged_edges = 0
-
- # Merge nodes
- for node_id, node in other_graph.nodes.items():
- if node_id not in self.nodes:
- self.nodes[node_id] = node
- self.node_type_index[node.node_type].add(node_id)
- merged_nodes += 1
-
- # Merge edges
- for edge in other_graph.edges:
- # Check if edge already exists
- exists = any(
- e.source_id == edge.source_id and e.target_id == edge.target_id
- for e in self.edges
- )
- if not exists:
- self.edges.append(edge)
- self.edge_type_index[edge.edge_type].append(edge)
- merged_edges += 1
-
- return {
- "merged_nodes": merged_nodes,
- "merged_edges": merged_edges,
- "total_nodes": len(self.nodes),
- "total_edges": len(self.edges),
- }
-
- def clone(self) -> 'ContextGraphBuilder':
- """
- Clone graph.
-
- Returns:
- New ContextGraphBuilder instance with copied graph
-
- Example:
- >>> cloned = builder.clone()
- """
- new_builder = ContextGraphBuilder(
- extract_entities=self.extract_entities,
- extract_relationships=self.extract_relationships,
- link_external_entities=self.link_external_entities,
- )
-
- # Copy nodes
- for node_id, node in self.nodes.items():
- new_builder.nodes[node_id] = ContextNode(
- node_id=node.node_id,
- node_type=node.node_type,
- content=node.content,
- metadata=node.metadata.copy(),
- properties=node.properties.copy(),
- )
- new_builder.node_type_index[node.node_type].add(node_id)
-
- # Copy edges
- for edge in self.edges:
- new_edge = ContextEdge(
- source_id=edge.source_id,
- target_id=edge.target_id,
- edge_type=edge.edge_type,
- weight=edge.weight,
- metadata=edge.metadata.copy(),
- )
- new_builder.edges.append(new_edge)
- new_builder.edge_type_index[edge.edge_type].append(new_edge)
-
- return new_builder
-
- # Statistics
- def stats(self) -> Dict[str, Any]:
- """
- Get statistics (enhance existing).
-
- Returns:
- Statistics dict
-
- Example:
- >>> stats = builder.stats()
- """
- node_types = defaultdict(int)
- edge_types = defaultdict(int)
-
- for node in self.nodes.values():
- node_types[node.node_type] += 1
-
- for edge in self.edges:
- edge_types[edge.edge_type] += 1
-
- return {
- "node_count": len(self.nodes),
- "edge_count": len(self.edges),
- "node_types": dict(node_types),
- "edge_types": dict(edge_types),
- }
-
- def node_count(self, **filters) -> int:
- """
- Count nodes.
-
- Args:
- **filters: Filter criteria
-
- Returns:
- Count of nodes matching filters
-
- Example:
- >>> count = builder.node_count(node_type="entity")
- """
- if not filters:
- return len(self.nodes)
-
- return len(self.find_nodes(**filters))
-
- def edge_count(self, **filters) -> int:
- """
- Count edges.
-
- Args:
- **filters: Filter criteria
-
- Returns:
- Count of edges matching filters
-
- Example:
- >>> count = builder.edge_count(edge_type="related_to")
- """
- if not filters:
- return len(self.edges)
-
- return len(self.find_edges(**filters))
-
- def density(self) -> float:
- """
- Calculate graph density.
-
- Returns:
- Graph density (0-1)
-
- Example:
- >>> density = builder.density()
- """
- n = len(self.nodes)
- if n <= 1:
- return 0.0
-
- # Maximum possible edges in undirected graph
- max_edges = n * (n - 1) / 2
- if max_edges == 0:
- return 0.0
-
- # Actual edges (considering undirected)
- actual_edges = len(self.edges)
-
- return actual_edges / max_edges
\ No newline at end of file
+# For backward compatibility
+ContextGraphBuilder = ContextGraph
diff --git a/semantica/context/context_retriever.py b/semantica/context/context_retriever.py
index e6184fc0..fcd63949 100644
--- a/semantica/context/context_retriever.py
+++ b/semantica/context/context_retriever.py
@@ -227,16 +227,28 @@ class ContextRetriever:
# If vector_store has a search method
if hasattr(self.vector_store, "search"):
search_results = self.vector_store.search(
- query=query, top_k=max_results
+ query=query, limit=max_results
)
for result in search_results:
+ # Handle VectorSearchResult object or dict
+ if hasattr(result, "content"):
+ content = result.content
+ score = result.score
+ source = f"vector:{result.id}"
+ metadata = result.metadata or {}
+ else:
+ content = result.get("content", "")
+ score = result.get("score", 0.0)
+ source = result.get("source")
+ metadata = result.get("metadata", {})
+
results.append(
RetrievedContext(
- content=result.get("content", ""),
- score=result.get("score", 0.0),
- source=result.get("source"),
- metadata=result.get("metadata", {}),
+ content=content,
+ score=score,
+ source=source,
+ metadata=metadata,
)
)
@@ -256,6 +268,50 @@ class ContextRetriever:
results = []
try:
+ # Check if knowledge_graph implements GraphStore protocol (has query method)
+ if hasattr(self.knowledge_graph, "query"):
+ graph_results = self.knowledge_graph.query(query)
+
+ for res in graph_results:
+ # Handle both interface dicts and raw dicts
+ node = res.get("node")
+ if hasattr(node, "id"): # GraphNodeInterface
+ node_id = node.id
+ node_type = node.type
+ content = node.properties.get("content", "")
+ metadata = node.properties
+ else: # Raw dict
+ node_id = res.get("id") or res.get("node", {}).get("id")
+ node_type = res.get("type") or res.get("node", {}).get("type")
+ content = res.get("content") or res.get("node", {}).get("content")
+ metadata = res.get("metadata") or res.get("node", {}).get("metadata")
+
+ score = res.get("score", 0.0)
+
+ # Get related entities
+ related_entities = self._get_related_entities(
+ node_id, max_hops=max_hops
+ )
+
+ results.append(
+ RetrievedContext(
+ content=content,
+ score=score,
+ source=f"graph:{node_id}",
+ metadata={
+ "node_type": node_type,
+ "node_id": node_id,
+ **(metadata or {}),
+ },
+ related_entities=related_entities,
+ )
+ )
+
+ # Sort by score
+ results.sort(key=lambda x: x.score, reverse=True)
+ return results[:max_results]
+
+ # Fallback to dictionary-based graph retrieval
# Extract entities from query (simplified)
query_lower = query.lower()
@@ -384,6 +440,10 @@ class ContextRetriever:
if not self.knowledge_graph:
return []
+ # Check if knowledge_graph implements GraphStore protocol
+ if hasattr(self.knowledge_graph, "get_neighbors"):
+ return self.knowledge_graph.get_neighbors(node_id, hops=max_hops)
+
related = []
visited = set()
current_level = {node_id}
diff --git a/semantica/context/context_usage.md b/semantica/context/context_usage.md
index 0e3d2cb3..72256ee6 100644
--- a/semantica/context/context_usage.md
+++ b/semantica/context/context_usage.md
@@ -1,6 +1,6 @@
# Context Module Usage Guide
-This guide demonstrates how to use the context module for building context graphs, managing agent memory, retrieving context, and linking entities for intelligent agents.
+This guide demonstrates how to use the Semantica context module for building context graphs, managing agent memory, retrieving context, and linking entities.
## Table of Contents
@@ -11,20 +11,21 @@ This guide demonstrates how to use the context module for building context graph
5. [Context Retrieval](#context-retrieval)
6. [Entity Linking](#entity-linking)
7. [Using Methods](#using-methods)
-8. [Using Registry](#using-registry)
-9. [Configuration](#configuration)
-10. [Advanced Examples](#advanced-examples)
## High-Level Interface (Quick Start)
-The `AgentContext` class provides a simplified, generic interface for common use cases. It uses generic method names (`store`, `retrieve`, `forget`, `conversation`) that auto-detect content types and retrieval strategies.
+The `AgentContext` class provides a simplified, generic interface for common use cases. It integrates vector storage, knowledge graphs, and memory management into a unified system.
-### Simple RAG
+### Simple RAG (Vector Only)
```python
from semantica.context import AgentContext
+from semantica.vector_store import VectorStore
-# Initialize with vector store
+# Initialize vector store
+vs = VectorStore(backend="faiss", dimension=768)
+
+# Initialize context
context = AgentContext(vector_store=vs)
# Store a memory
@@ -38,10 +39,15 @@ for result in results:
print(f"Score: {result['score']:.2f}")
```
-### GraphRAG
+### GraphRAG (Vector + Graph)
```python
-# Initialize with vector store and knowledge graph
+from semantica.context import AgentContext, ContextGraph
+
+# Initialize knowledge graph
+kg = ContextGraph()
+
+# Initialize context with vector store and knowledge graph
context = AgentContext(vector_store=vs, knowledge_graph=kg)
# Store documents (auto-builds graph)
@@ -59,12 +65,13 @@ stats = context.store(
)
print(f"Stored {stats['stored_count']} documents")
-print(f"Built graph with {stats['graph_nodes']} nodes and {stats['graph_edges']} edges")
+# Graph stats are available via the graph object directly or context stats
+print(f"Graph nodes: {kg.stats()['node_count']}")
# Retrieve with graph context (auto-detects GraphRAG)
results = context.retrieve(
"Python machine learning",
- use_graph=None, # Auto-detect (uses graph since knowledge_graph available)
+ use_graph=True, # Explicitly use graph
include_entities=True, # Include related entities
expand_graph=True # Use graph expansion
)
@@ -75,15 +82,23 @@ for result in results:
print(f"Related entities: {len(result.get('related_entities', []))}")
```
-### Agent Memory Management
+### Agent Memory Management (Hierarchical)
+
+The system uses a hierarchical memory structure with:
+1. **Short-Term Memory**: Fast, in-memory buffer with token and item count limits.
+2. **Long-Term Memory**: Persistent vector store.
```python
-context = AgentContext(vector_store=vs, retention_days=30)
+context = AgentContext(
+ vector_store=vs,
+ retention_days=30,
+ short_term_limit=10, # Max items in short-term buffer
+ token_limit=2000 # Max tokens in short-term buffer
+)
# Store multiple memories in a conversation
context.store("Hello, I'm interested in Python", conversation_id="conv1", user_id="user123")
context.store("What can you tell me about machine learning?", conversation_id="conv1", user_id="user123")
-context.store("I prefer TensorFlow over PyTorch", conversation_id="conv1", user_id="user123")
# Get conversation history
history = context.conversation(
@@ -95,272 +110,48 @@ history = context.conversation(
for item in history:
print(f"{item['timestamp']}: {item['content']}")
-# Retrieve context from conversation
-results = context.retrieve(
- "Python",
- conversation_id="conv1", # Filter by conversation
- max_results=3
-)
-
# Delete old memories
deleted_count = context.forget(days_old=90)
print(f"Deleted {deleted_count} old memories")
```
-### Boolean Flags for Common Options
-
-The `AgentContext` class uses boolean flags to simplify common operations:
-
-**Store Method:**
-- `extract_entities: bool = True` - Extract entities from documents
-- `extract_relationships: bool = True` - Extract relationships
-- `link_entities: bool = True` - Link entities across documents
-- `auto_extract: bool = False` - Auto-extract entities/relationships if not provided
-
-**Retrieve Method:**
-- `use_graph: Optional[bool] = None` - Auto-detect if None, True/False to force
-- `include_entities: bool = True` - Include related entities in results
-- `include_relationships: bool = False` - Include relationships in results
-- `expand_graph: bool = True` - Use graph expansion
-- `deduplicate: bool = True` - Deduplicate results
-
-**Conversation Method:**
-- `reverse: bool = False` - Reverse chronological order
-- `include_metadata: bool = True` - Include full metadata
-
-**Helper Methods:**
-- `get_memory(memory_id)` - Get specific memory by ID
-- `stats()` - Get memory statistics
-- `link(text, entities, ...)` - Link entities in text
-- `build_graph(...)` - Build context graph manually
-
-**Example with Flags:**
-
-```python
-# Store documents without entity extraction
-stats = context.store(
- documents,
- extract_entities=False, # Skip entity extraction
- extract_relationships=False # Skip relationship extraction
-)
-
-# Retrieve with vector-only (no graph)
-results = context.retrieve(
- "Python",
- use_graph=False, # Force vector-only retrieval
- include_entities=False # Don't include entities
-)
-
-# Retrieve with graph but no expansion
-results = context.retrieve(
- "Python",
- use_graph=True, # Force graph retrieval
- expand_graph=False # Disable graph expansion
-)
-```
-
-### Additional Helper Methods
-
-```python
-# Get a specific memory by ID
-memory = context.get_memory("mem123")
-if memory:
- print(f"Content: {memory['content']}")
- print(f"Metadata: {memory['metadata']}")
-
-# Get statistics about stored memories
-stats = context.stats()
-print(f"Total memories: {stats['total_items']}")
-print(f"By type: {stats.get('items_by_type', {})}")
-
-# Link entities in text (requires knowledge_graph)
-linked = context.link(
- "Python is used for machine learning",
- entities=[
- {"id": "e1", "text": "Python", "type": "PROGRAMMING_LANGUAGE"},
- {"id": "e2", "text": "Machine Learning", "type": "CONCEPT"}
- ],
- similarity_threshold=0.8
-)
-for entity in linked:
- print(f"{entity['text']}: {entity['uri']} ({entity['linked_count']} links)")
-
-# Build graph manually from entities and relationships
-graph_stats = context.build_graph(
- entities=entities,
- relationships=relationships,
- link_entities=True
-)
-print(f"Graph: {graph_stats.get('node_count', 0)} nodes, {graph_stats.get('edge_count', 0)} edges")
-```
-
-### Auto-Detection
-
-The `AgentContext` class automatically detects:
-
-1. **Content Type in `store()`:**
- - Single string → Memory item
- - List of strings/dicts → Documents
-
-2. **Retrieval Strategy in `retrieve()`:**
- - If `knowledge_graph` available → GraphRAG (hybrid retrieval)
- - Otherwise → Simple RAG (vector only)
-
-3. **Graph Usage:**
- - If `use_graph=None` → Auto-detect based on `knowledge_graph` availability
- - If `use_graph=True` → Force graph retrieval (requires `knowledge_graph`)
- - If `use_graph=False` → Force vector-only retrieval
-
-### Additional Memory Management Methods
-
-```python
-context = AgentContext(vector_store=vs, knowledge_graph=kg)
-
-# Check if memory exists
-if context.exists("mem123"):
- print("Memory exists")
-
-# Get memory count
-total = context.count()
-conv_count = context.count(conversation_id="conv1")
-
-# Get memory by ID (alias for get_memory)
-memory = context.get("mem123")
-
-# Update memory
-context.update("mem123", content="Updated content", metadata={"key": "value"})
-
-# Delete memory (alias for forget with memory_id)
-context.delete("mem123")
-
-# Clear memories with filters (alias for forget)
-deleted = context.clear(conversation_id="conv1")
-deleted = context.clear(days_old=90)
-
-# List memories with pagination
-memories = context.list(conversation_id="conv1", limit=50, offset=10)
-
-# Batch operations
-ids = context.batch_store(["Item 1", "Item 2", "Item 3"])
-deleted = context.batch_delete(["mem1", "mem2"])
-updated = context.batch_update([
- {"memory_id": "mem1", "content": "New content"},
- {"memory_id": "mem2", "metadata": {"key": "value"}}
-])
-```
-
-### Additional Search Methods
-
-```python
-# Simple search (alias for retrieve)
-results = context.search("Python", max_results=10)
-
-# Find similar content
-similar = context.find_similar("Python programming", limit=5)
-
-# Get context for query
-context_data = context.get_context("Python", max_results=10)
-
-# Expand query with graph context
-expanded = context.expand_query("Python", max_hops=3)
-```
-
-### Additional Conversation Methods
-
-```python
-# Get conversation (alias for conversation)
-conv = context.get_conversation("conv1", limit=50)
-
-# List all conversations
-conversations = context.list_conversations(user_id="user123", limit=50)
-
-# Delete entire conversation
-deleted = context.delete_conversation("conv1")
-
-# Get conversation summary
-summary = context.conversation_summary("conv1")
-print(f"Messages: {summary['message_count']}")
-print(f"First: {summary['first_message']}")
-print(f"Last: {summary['last_message']}")
-```
-
-### Export/Import Methods
-
-```python
-# Export memories
-data = context.export(conversation_id="conv1", format='json')
-data = context.export(format='dict')
-
-# Import memories
-imported = context.import_data(data, format='json')
-
-# Backup and restore
-backup_data = context.backup()
-restored = context.restore(backup_data)
-```
-
-### Statistics and Analytics
-
-```python
-# Get statistics (enhanced)
-stats = context.stats()
-stats = context.stats(conversation_id="conv1")
-
-# Check system health
-health = context.health()
-print(f"Status: {health['status']}")
-print(f"Total memories: {health['total_memories']}")
-
-# Get usage statistics
-usage = context.usage_stats(period='week')
-print(f"Recent memories: {usage['recent_memories']}")
-```
-
-### Accessing Underlying Components
-
-You can still access underlying components for advanced use cases:
-
-```python
-context = AgentContext(vector_store=vs, knowledge_graph=kg)
-
-# Access underlying components
-memory = context.memory # AgentMemory instance
-retriever = context.retriever # ContextRetriever instance (if knowledge_graph available)
-graph_builder = context.graph_builder # ContextGraphBuilder instance (if knowledge_graph available)
-
-# Use low-level methods
-memory.store("Custom memory", metadata={"custom": "data"})
-results = retriever.retrieve("query", max_results=10)
-```
-
## Basic Usage
-### Using Main Classes
+### Using Main Classes Directly
```python
-from semantica.context import ContextGraphBuilder, AgentMemory, ContextRetriever
+from semantica.context import ContextGraph, AgentMemory, ContextRetriever
# Step 1: Build context graph
-builder = ContextGraphBuilder()
-graph = builder.build_from_entities_and_relationships(entities, relationships)
+graph = ContextGraph()
+# Add entities and relationships manually or via build methods
+entities = [{"id": "e1", "text": "Python", "type": "Language"}]
+relationships = [] # ...
+graph.build_from_entities_and_relationships(entities, relationships)
-# Step 2: Initialize agent memory
-memory = AgentMemory(vector_store=vs, knowledge_graph=kg)
+# Step 2: Initialize agent memory with token limits
+memory = AgentMemory(
+ vector_store=vs,
+ knowledge_graph=graph,
+ token_limit=1000 # Custom token limit
+)
memory_id = memory.store("User asked about Python", metadata={"type": "conversation"})
# Step 3: Retrieve context
-retriever = ContextRetriever(memory_store=memory, knowledge_graph=kg, vector_store=vs)
+retriever = ContextRetriever(memory_store=memory, knowledge_graph=graph, vector_store=vs)
results = retriever.retrieve("Python programming", max_results=5)
```
## Context Graph Construction
+The `ContextGraph` class is an in-memory graph store.
+
### Building from Entities and Relationships
```python
-from semantica.context import ContextGraphBuilder
+from semantica.context import ContextGraph
-builder = ContextGraphBuilder()
+graph = ContextGraph()
entities = [
{"id": "e1", "text": "Python", "type": "PROGRAMMING_LANGUAGE"},
@@ -373,18 +164,18 @@ relationships = [
{"source_id": "e3", "target_id": "e2", "type": "implements", "confidence": 0.95},
]
-graph = builder.build_from_entities_and_relationships(entities, relationships)
+graph_data = graph.build_from_entities_and_relationships(entities, relationships)
-print(f"Nodes: {graph['statistics']['node_count']}")
-print(f"Edges: {graph['statistics']['edge_count']}")
+print(f"Nodes: {graph.stats()['node_count']}")
+print(f"Edges: {graph.stats()['edge_count']}")
```
### Building from Conversations
```python
-from semantica.context import ContextGraphBuilder
+from semantica.context import ContextGraph
-builder = ContextGraphBuilder()
+graph = ContextGraph()
conversations = [
{
@@ -394,108 +185,56 @@ conversations = [
{"id": "e1", "text": "Python", "type": "PROGRAMMING_LANGUAGE"}
],
"relationships": []
- },
- {
- "id": "conv2",
- "content": "User asked about machine learning",
- "entities": [
- {"id": "e2", "text": "Machine Learning", "type": "CONCEPT"}
- ],
- "relationships": []
}
]
-graph = builder.build_from_conversations(
+graph_data = graph.build_from_conversations(
conversations,
link_entities=True,
- extract_intents=True,
- extract_sentiments=True
+ extract_intents=True
)
```
### Adding Nodes and Edges Manually
```python
-from semantica.context import ContextGraphBuilder
+from semantica.context import ContextGraph
-builder = ContextGraphBuilder()
+graph = ContextGraph()
# Add nodes
-builder.add_node("node1", "entity", "Python programming", confidence=0.9)
-builder.add_node("node2", "concept", "Machine Learning", confidence=0.95)
+graph.add_node("node1", "entity", "Python programming", confidence=0.9)
+graph.add_node("node2", "concept", "Machine Learning", confidence=0.95)
# Add edges
-builder.add_edge("node1", "node2", "related_to", weight=0.9)
+graph.add_edge("node1", "node2", "related_to", weight=0.9)
# Get neighbors
-neighbors = builder.get_neighbors("node1", max_hops=2)
+neighbors = graph.get_neighbors("node1", hops=2)
print(f"Neighbors: {neighbors}")
# Query graph
-results = builder.query(node_type="entity", confidence=0.8)
+results = graph.query("Python") # Keyword search on nodes
```
-### Additional Graph Construction Methods
+### Graph Statistics and Analysis
```python
-from semantica.context import ContextGraphBuilder
-
-builder = ContextGraphBuilder()
-
-# High-level construction
-graph = builder.from_text("Python is used for machine learning")
-graph = builder.from_documents(["Doc 1", "Doc 2"])
-graph = builder.from_conversations(conversations)
-stats = builder.add(entities=entities, relationships=relationships)
-
-# Query methods
-results = builder.find("Python")
-node = builder.find_node("node1")
-nodes = builder.find_nodes(node_type="entity")
-edges = builder.find_edges(edge_type="related_to")
-path = builder.find_path("node1", "node2", max_hops=5)
-
-# Graph operations
-subgraph = builder.get_subgraph(["node1", "node2"])
-merge_stats = builder.merge(other_builder)
-cloned = builder.clone()
-
-# Statistics
-stats = builder.stats()
-node_count = builder.node_count(node_type="entity")
-edge_count = builder.edge_count(edge_type="related_to")
-density = builder.density()
-```
+stats = graph.stats()
+print(f"Node types: {stats['node_types']}")
+print(f"Density: {stats['density']:.4f}")
-### Using Graph Construction Methods
-
-```python
-from semantica.context.methods import build_context_graph
-# Build from entities and relationships
-graph = build_context_graph(
- entities=entities,
- relationships=relationships,
- method="entities_relationships"
-)
-
-# Build from conversations
-graph = build_context_graph(
- conversations=conversations,
- method="conversations"
-)
-
-# Hybrid construction
-graph = build_context_graph(
- entities=entities,
- relationships=relationships,
- conversations=conversations,
- method="hybrid"
-)
+# Find specific nodes/edges
+entities = graph.find_nodes(node_type="entity")
+relations = graph.find_edges(edge_type="related_to")
+node = graph.find_node("node1")
```
## Agent Memory Management
-### Storing Memories
+The `AgentMemory` class handles short-term and long-term memory with hierarchical storage and token management.
+
+### Storing and Retrieving
```python
from semantica.context import AgentMemory
@@ -504,174 +243,39 @@ memory = AgentMemory(
vector_store=vs,
knowledge_graph=kg,
retention_policy="30_days",
- max_memory_size=10000
+ max_memory_size=10000,
+ short_term_limit=20, # 20 items max in short-term
+ token_limit=4000 # 4000 tokens max in short-term
)
-# Store a memory
+# Store (automatically updates short-term and long-term)
memory_id = memory.store(
"User asked about Python programming",
- metadata={
- "type": "conversation",
- "conversation_id": "conv_123",
- "user_id": "user_456"
- },
- entities=[
- {"id": "e1", "text": "Python", "type": "PROGRAMMING_LANGUAGE"}
- ]
+ metadata={"conversation_id": "conv_123"}
)
-print(f"Stored memory: {memory_id}")
-```
-
-### Retrieving Memories
-
-```python
-from semantica.context import AgentMemory
-
-memory = AgentMemory(vector_store=vs, knowledge_graph=kg)
+# Store short-term only (fleeting thoughts)
+temp_id = memory.store(
+ "Just checking status...",
+ skip_vector=True
+)
-# Retrieve memories
+# Retrieve
results = memory.retrieve(
"Python programming",
max_results=5,
- min_score=0.5,
type="conversation"
)
-for result in results:
- print(f"Content: {result['content']}")
- print(f"Score: {result['score']:.2f}")
- print(f"Timestamp: {result['timestamp']}")
-```
-
-### Getting Specific Memory
-
-```python
-from semantica.context import AgentMemory
-
-memory = AgentMemory(vector_store=vs, knowledge_graph=kg)
-
-# Get specific memory
-memory_item = memory.get_memory("mem_abc123")
-if memory_item:
- print(f"Content: {memory_item['content']}")
- print(f"Metadata: {memory_item['metadata']}")
-```
-
-### Conversation History
-
-```python
-from semantica.context import AgentMemory
-
-memory = AgentMemory(vector_store=vs, knowledge_graph=kg)
-
-# Get conversation history
-history = memory.get_conversation_history(
- conversation_id="conv_123",
- max_items=100
-)
-
-for item in history:
- print(f"{item['timestamp']}: {item['content']}")
-```
-
-### Memory Management
-
-```python
-from semantica.context import AgentMemory
-
-memory = AgentMemory(vector_store=vs, knowledge_graph=kg)
-
-# Delete specific memory
-memory.delete_memory("mem_abc123")
-
-# Clear memories by filters
-deleted_count = memory.clear_memory(
- type="conversation",
- start_date="2024-01-01",
- end_date="2024-12-31"
-)
-
-print(f"Deleted {deleted_count} memories")
-
-# Get statistics
-stats = memory.get_statistics()
-print(f"Total items: {stats['total_items']}")
-print(f"Items by type: {stats['items_by_type']}")
-```
-
-### Additional Memory Management Methods
-
-```python
-from semantica.context import AgentMemory
-
-memory = AgentMemory(vector_store=vs, knowledge_graph=kg)
-
-# Basic operations
-exists = memory.exists("mem123")
-count = memory.count()
-count = memory.count(conversation_id="conv1")
-memory_item = memory.get("mem123")
-memory.update("mem123", content="Updated", metadata={"key": "value"})
-memory.delete("mem123")
-deleted = memory.clear(conversation_id="conv1")
-
-# Search methods
-results = memory.search("Python", max_results=10)
-similar = memory.find_similar("Python programming", limit=5)
-by_entity = memory.find_by_entity("entity_123", limit=10)
-by_relationship = memory.find_by_relationship("related_to", limit=10)
-
-# List and filter methods
-memories = memory.list(conversation_id="conv1", limit=50, offset=10)
-conv_memories = memory.get_by_conversation("conv1", limit=100)
-user_memories = memory.get_by_user("user123", limit=100)
-recent = memory.get_recent(limit=10)
-by_date = memory.get_by_date("2024-01-01", "2024-12-31", limit=100)
-by_type = memory.get_by_type("conversation", limit=100)
-
-# Batch operations
-ids = memory.batch_store(["Item 1", "Item 2"])
-deleted = memory.batch_delete(["mem1", "mem2"])
-updated = memory.batch_update([{"memory_id": "mem1", "content": "New"}])
-
-# Export/import
-data = memory.export(conversation_id="conv1", format='json')
-imported = memory.import_data(data, format='json')
-
-# Statistics
-stats = memory.stats(conversation_id="conv1")
-type_counts = memory.count_by_type()
-user_counts = memory.count_by_user()
-conv_counts = memory.count_by_conversation()
-```
-
-### Using Memory Methods
-
-```python
-from semantica.context.methods import store_memory
-# Store memory using method
-memory_id = store_memory(
- "User asked about Python",
- vector_store=vs,
- knowledge_graph=kg,
- method="store",
- metadata={"type": "conversation"}
-)
-
-# Store conversation memory
-memory_id = store_memory(
- "User asked about machine learning",
- vector_store=vs,
- knowledge_graph=kg,
- method="conversation",
- metadata={"conversation_id": "conv_123"}
-)
+# Conversation History
+history = memory.get_conversation_history("conv_123")
```
## Context Retrieval
-### Basic Retrieval
+The `ContextRetriever` implements hybrid retrieval strategies.
+
+### Hybrid Retrieval
```python
from semantica.context import ContextRetriever
@@ -681,559 +285,53 @@ retriever = ContextRetriever(
knowledge_graph=kg,
vector_store=vs,
use_graph_expansion=True,
- max_expansion_hops=2
+ max_expansion_hops=2,
+ hybrid_alpha=0.5 # Balance between vector (0.0) and graph (1.0)
)
-# Retrieve context
results = retriever.retrieve(
"Python programming",
- max_results=5,
- min_relevance_score=0.5
-)
-
-for result in results:
- print(f"Content: {result.content}")
- print(f"Score: {result.score:.2f}")
- print(f"Source: {result.source}")
- print(f"Related entities: {len(result.related_entities)}")
-```
-
-### Retrieval Methods
-
-```python
-from semantica.context.methods import retrieve_context
-# Vector-based retrieval only
-results = retrieve_context(
- "Python programming",
- vector_store=vs,
- method="vector",
max_results=5
)
-# Graph-based retrieval only
-results = retrieve_context(
- "Python programming",
- knowledge_graph=kg,
- method="graph",
- max_results=5
-)
-
-# Memory-based retrieval only
-results = retrieve_context(
- "Python programming",
- memory_store=memory,
- method="memory",
- max_results=5
-)
-
-# Hybrid retrieval (all sources)
-results = retrieve_context(
- "Python programming",
- memory_store=memory,
- knowledge_graph=kg,
- vector_store=vs,
- method="hybrid",
- max_results=5
-)
-```
-
-### Graph Expansion
-
-```python
-from semantica.context import ContextRetriever
-
-retriever = ContextRetriever(
- knowledge_graph=kg,
- use_graph_expansion=True,
- max_expansion_hops=3
-)
-
-# Retrieve with graph expansion
-results = retriever.retrieve(
- "Python",
- max_results=10,
- max_hops=3
-)
-
for result in results:
print(f"Content: {result.content}")
- print(f"Related entities: {len(result.related_entities)}")
- for entity in result.related_entities[:3]:
- print(f" - {entity['content']} (hop: {entity['hop']})")
-```
-
-### Additional Retrieval Methods
-
-```python
-from semantica.context import ContextRetriever
-
-retriever = ContextRetriever(memory_store=memory, knowledge_graph=kg, vector_store=vs)
-
-# Search methods
-results = retriever.search("Python", max_results=10)
-vector_results = retriever.vector_search("Python")
-graph_results = retriever.graph_search("Python")
-memory_results = retriever.memory_search("Python")
-hybrid_results = retriever.hybrid_search("Python")
-
-# Advanced retrieval
-similar = retriever.find_similar("Python programming", limit=5)
-context = retriever.get_context("Python", max_results=5)
-expanded = retriever.expand_query("Python", max_hops=3)
-related = retriever.get_related("entity_123", max_hops=2)
-path = retriever.get_path("entity_1", "entity_2", max_hops=5)
-
-# Filter methods
-by_entity = retriever.filter_by_entity("entity_123", "Python")
-by_type = retriever.filter_by_type("PROGRAMMING_LANGUAGE", "Python")
-by_date = retriever.filter_by_date("2024-01-01", "2024-12-31", "Python")
-by_score = retriever.filter_by_score(0.7, "Python")
-
-# Batch operations
-batch_results = retriever.batch_search(["Python", "Java", "C++"])
-batch_contexts = retriever.batch_get_context(["Python", "Java"], max_results=5)
+ print(f"Source: {result.source}") # 'vector', 'graph', or 'memory'
```
## Entity Linking
-### Basic Entity Linking
-
-```python
-from semantica.context import EntityLinker
-
-linker = EntityLinker(
- knowledge_graph=kg,
- similarity_threshold=0.8,
- base_uri="https://semantica.dev/entity/"
-)
-
-# Assign URI to entity
-uri = linker.assign_uri(
- "entity_1",
- "Python",
- "PROGRAMMING_LANGUAGE"
-)
-print(f"URI: {uri}")
-
-# Link entities in text
-entities = [
- {"id": "e1", "text": "Python", "type": "PROGRAMMING_LANGUAGE"},
- {"id": "e2", "text": "Machine Learning", "type": "CONCEPT"},
-]
-
-linked_entities = linker.link(
- "Python is used for machine learning",
- entities=entities
-)
-
-for entity in linked_entities:
- print(f"{entity.text}: {entity.uri}")
- print(f"Linked to {len(entity.linked_entities)} entities")
-```
-
-### Explicit Entity Linking
+The `EntityLinker` helps resolve entities to canonical forms or URIs.
```python
from semantica.context import EntityLinker
-linker = EntityLinker(knowledge_graph=kg)
-
-# Create explicit link
-linker.link_entities(
- "entity_1",
- "entity_2",
- link_type="related_to",
- confidence=0.9,
- source="manual"
-)
-
-# Get entity links
-links = linker.get_entity_links("entity_1")
-for link in links:
- print(f"{link.source_entity_id} --{link.link_type}--> {link.target_entity_id}")
+linker = EntityLinker()
+uri = linker.generate_uri("Python Programming Language")
+print(uri) # e.g., "python_programming_language"
-# Get entity URI
-uri = linker.get_entity_uri("entity_1")
-if uri:
- print(f"Entity URI: {uri}")
-```
-
-### Finding Similar Entities
-
-```python
-from semantica.context import EntityLinker
-
-linker = EntityLinker(knowledge_graph=kg)
-
-# Find similar entities
-similar = linker.find_similar_entities(
- "Python",
- entity_type="PROGRAMMING_LANGUAGE",
- threshold=0.8
-)
-
-for entity_id, similarity in similar:
- print(f"{entity_id}: {similarity:.2f}")
-```
-
-### Building Entity Web
-
-```python
-from semantica.context import EntityLinker
-
-linker = EntityLinker(knowledge_graph=kg)
-
-# Link multiple entities
-linker.link_entities("e1", "e2", "related_to", confidence=0.9)
-linker.link_entities("e2", "e3", "related_to", confidence=0.85)
-
-# Build entity web
-web = linker.build_entity_web()
-
-print(f"Total entities: {web['statistics']['total_entities']}")
-print(f"Total links: {web['statistics']['total_links']}")
-
-for entity_id, info in web['entities'].items():
- print(f"{entity_id}: {info['uri']} ({info['links']} links)")
-```
-
-### Additional Entity Linking Methods
-
-```python
-from semantica.context import EntityLinker
-
-linker = EntityLinker(knowledge_graph=kg)
-
-# Linking methods
-linked = linker.link_text("Python is used for ML", entities=[...])
-batch_linked = linker.link_batch(entities)
-
-# Search methods
-similar = linker.find_similar("Python", threshold=0.8)
-by_text = linker.find_by_text("Python", threshold=0.8)
-by_type = linker.find_by_type("PROGRAMMING_LANGUAGE", limit=10)
-related = linker.find_related("entity_123", max_hops=2)
-
-# URI methods
-uri = linker.get_uri("entity_123")
-all_uris = linker.get_all_uris()
-entity = linker.resolve_uri("https://semantica.dev/entity/python")
-
-# Statistics
-link_count = linker.link_count("entity_123")
-stats = linker.stats()
-most_linked = linker.most_linked(limit=10)
-```
-
-### Using Linking Methods
-
-```python
-from semantica.context.methods import link_entities
-# URI assignment only
-linked = link_entities(
- entities,
- method="uri"
-)
-
-# Similarity-based linking
-linked = link_entities(
- entities,
- knowledge_graph=kg,
- method="similarity"
-)
-
-# Knowledge graph-based linking
-linked = link_entities(
- entities,
- knowledge_graph=kg,
- method="knowledge_graph"
-)
-
-# Cross-document linking
-linked = link_entities(
- entities,
- knowledge_graph=kg,
- method="cross_document",
- context=[{"source": "doc1"}, {"source": "doc2"}]
-)
+# Similarity matching
+score = linker._calculate_text_similarity("Python", "Python Language")
```
## Using Methods
-### Available Methods
+The methods module provides simple, reusable functions for context operations.
```python
from semantica.context.methods import (
build_context_graph,
store_memory,
retrieve_context,
- link_entities,
- get_context_method,
- list_available_methods
-)
-
-# List all available methods
-all_methods = list_available_methods()
-print(all_methods)
-
-# List methods for specific task
-graph_methods = list_available_methods("graph")
-print(f"Graph methods: {graph_methods}")
-
-# Get custom method
-custom_method = get_context_method("graph", "custom_method")
-if custom_method:
- result = custom_method(entities, relationships)
-```
-
-## Using Registry
-
-### Registering Custom Methods
-
-```python
-from semantica.context import registry
-def custom_graph_builder(entities, relationships, **kwargs):
- """Custom graph building method."""
- # Custom implementation
- return {"nodes": [], "edges": [], "statistics": {}}
-
-# Register custom method
-registry.method_registry.register("graph", "custom_builder", custom_graph_builder)
-
-# Use custom method
-from semantica.context.methods import build_context_graph
-graph = build_context_graph(entities, relationships, method="custom_builder")
-
-# List registered methods
-methods = registry.method_registry.list_all("graph")
-print(f"Registered graph methods: {methods}")
-
-# Unregister method
-registry.method_registry.unregister("graph", "custom_builder")
-```
-
-## Configuration
-
-### Using Configuration
-
-```python
-from semantica.context import config
-
-# Get configuration
-retention = config.context_config.get("retention_policy", default="unlimited")
-max_size = config.context_config.get("max_memory_size", default=10000)
-
-# Set configuration
-config.context_config.set("retention_policy", "30_days")
-config.context_config.set("max_memory_size", 5000)
-
-# Method-specific configuration
-config.context_config.set_method_config("graph", {
- "extract_entities": True,
- "extract_relationships": True
-})
-
-method_config = config.context_config.get_method_config("graph")
-
-# Get all configurations
-all_configs = config.context_config.get_all()
-```
-
-### Environment Variables
-
-```bash
-# Set environment variables
-export CONTEXT_RETENTION_POLICY=30_days
-export CONTEXT_MAX_MEMORY_SIZE=5000
-export CONTEXT_SIMILARITY_THRESHOLD=0.8
-```
-
-### Config Files
-
-```yaml
-# context_config.yaml
-context:
- retention_policy: 30_days
- max_memory_size: 5000
- similarity_threshold: 0.8
-
-context_methods:
- graph:
- extract_entities: true
- extract_relationships: true
- memory:
- retention_policy: unlimited
-```
-
-```python
-from semantica.context import config
-
-# Load from config file
-context_config = config.ContextConfig(config_file="context_config.yaml")
-```
-
-## Advanced Examples
-
-### Complete Agent Context Workflow
-
-```python
-from semantica.context import (
- AgentMemory,
- ContextRetriever,
- EntityLinker,
- ContextGraphBuilder
-)
-
-# Step 1: Build context graph
-builder = ContextGraphBuilder()
-graph = builder.build_from_entities_and_relationships(entities, relationships)
-
-# Step 2: Initialize memory
-memory = AgentMemory(vector_store=vs, knowledge_graph=kg)
-
-# Step 3: Store conversation
-conversation_id = "conv_123"
-memory.store(
- "User asked about Python programming",
- metadata={
- "type": "conversation",
- "conversation_id": conversation_id
- }
-)
-
-# Step 4: Link entities
-linker = EntityLinker(knowledge_graph=kg)
-linked = linker.link("Python is used for machine learning", entities=entities)
-
-# Step 5: Retrieve context
-retriever = ContextRetriever(
- memory_store=memory,
- knowledge_graph=kg,
- vector_store=vs
+ link_entities
)
-results = retriever.retrieve("Python programming", max_results=5)
-
-# Step 6: Use retrieved context
-for result in results:
- print(f"Context: {result.content}")
- print(f"Relevance: {result.score:.2f}")
- if result.related_entities:
- print(f"Related: {[e['content'] for e in result.related_entities]}")
-```
-
-### Multi-Source Context Integration
+# Build graph
+graph = build_context_graph(entities, relationships, method="entities_relationships")
-```python
-from semantica.context import ContextRetriever
+# Store memory
+memory_id = store_memory("User asked about Python", vector_store=vs, method="store")
-# Initialize retriever with multiple sources
-retriever = ContextRetriever(
- memory_store=memory,
- knowledge_graph=kg,
- vector_store=vs,
- hybrid_alpha=0.5 # Balance between vector and graph
-)
-
-# Retrieve with hybrid approach
-results = retriever.retrieve(
- "Python machine learning frameworks",
- max_results=10,
- use_graph_expansion=True,
- max_hops=2
-)
-
-# Process results
-for result in results:
- print(f"Source: {result.source}")
- print(f"Content: {result.content[:100]}...")
- print(f"Score: {result.score:.2f}")
- print(f"Related entities: {len(result.related_entities)}")
- print("---")
-```
-
-### Conversation-Based Context Building
-
-```python
-from semantica.context import ContextGraphBuilder, AgentMemory
-
-builder = ContextGraphBuilder()
-memory = AgentMemory(vector_store=vs, knowledge_graph=kg)
-
-# Process conversations
-conversations = [
- {
- "id": "conv1",
- "content": "User asked about Python",
- "timestamp": "2024-01-01T10:00:00",
- "entities": [{"id": "e1", "text": "Python", "type": "PROGRAMMING_LANGUAGE"}]
- },
- {
- "id": "conv2",
- "content": "User asked about machine learning",
- "timestamp": "2024-01-01T11:00:00",
- "entities": [{"id": "e2", "text": "Machine Learning", "type": "CONCEPT"}]
- }
-]
-
-# Build graph from conversations
-graph = builder.build_from_conversations(
- conversations,
- link_entities=True,
- extract_intents=True
-)
-
-# Store conversations in memory
-for conv in conversations:
- memory.store(
- conv["content"],
- metadata={
- "type": "conversation",
- "conversation_id": conv["id"],
- "timestamp": conv["timestamp"]
- },
- entities=conv.get("entities", [])
- )
-
-# Retrieve conversation history
-history = memory.get_conversation_history(conversation_id="conv1")
-```
-
-### Entity Web Construction
-
-```python
-from semantica.context import EntityLinker
-
-linker = EntityLinker(
- knowledge_graph=kg,
- similarity_threshold=0.8
-)
-
-# Link multiple entities
-entities = [
- {"id": "e1", "text": "Python", "type": "PROGRAMMING_LANGUAGE"},
- {"id": "e2", "text": "Machine Learning", "type": "CONCEPT"},
- {"id": "e3", "text": "TensorFlow", "type": "FRAMEWORK"},
- {"id": "e4", "text": "PyTorch", "type": "FRAMEWORK"},
-]
-
-# Link entities
-linked = linker.link("", entities=entities)
-
-# Create explicit links
-linker.link_entities("e1", "e2", "used_for", confidence=0.9)
-linker.link_entities("e3", "e2", "implements", confidence=0.95)
-linker.link_entities("e4", "e2", "implements", confidence=0.95)
-linker.link_entities("e3", "e4", "related_to", confidence=0.8)
-
-# Build entity web
-web = linker.build_entity_web()
-
-print(f"Entity Web Statistics:")
-print(f" Total entities: {web['statistics']['total_entities']}")
-print(f" Total links: {web['statistics']['total_links']}")
-
-for entity_id, info in web['entities'].items():
- print(f" {entity_id}: {info['uri']} ({info['links']} links)")
+# Retrieve context
+results = retrieve_context("Python programming", vector_store=vs, method="hybrid")
```
-
diff --git a/semantica/context/entity_linker.py b/semantica/context/entity_linker.py
index e5865224..369b8fa6 100644
--- a/semantica/context/entity_linker.py
+++ b/semantica/context/entity_linker.py
@@ -58,7 +58,7 @@ License: MIT
import hashlib
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional, Set, Tuple
+from typing import Any, Dict, List, Optional, Set, Tuple, Union
from urllib.parse import quote
from ..utils.exceptions import ProcessingError, ValidationError
diff --git a/semantica/context/methods.py b/semantica/context/methods.py
index 401a4681..6f864c42 100644
--- a/semantica/context/methods.py
+++ b/semantica/context/methods.py
@@ -99,7 +99,7 @@ from typing import Any, Callable, Dict, List, Optional, Union
from ..utils.exceptions import ConfigurationError, ProcessingError
from ..utils.logging import get_logger
from .agent_memory import AgentMemory, MemoryItem
-from .context_graph import ContextEdge, ContextGraphBuilder, ContextNode
+from .context_graph import ContextEdge, ContextGraph, ContextNode
from .context_retriever import ContextRetriever, RetrievedContext
from .entity_linker import EntityLink, EntityLinker, LinkedEntity
from .registry import method_registry
@@ -127,7 +127,7 @@ def build_context_graph(
- "entities_relationships": Build from entities and relationships
- "conversations": Build from conversations
- "hybrid": Hybrid construction combining multiple sources
- **kwargs: Additional options passed to ContextGraphBuilder
+ **kwargs: Additional options passed to ContextGraph
Returns:
Context graph dictionary containing:
@@ -153,7 +153,8 @@ def build_context_graph(
)
try:
- builder = ContextGraphBuilder(**kwargs)
+ # Use ContextGraph as the builder
+ builder = ContextGraph(**kwargs)
if method == "entities_relationships":
if not entities or not relationships:
diff --git a/semantica/core/config_manager.py b/semantica/core/config_manager.py
index 8ed70287..07b5fe1c 100644
--- a/semantica/core/config_manager.py
+++ b/semantica/core/config_manager.py
@@ -54,7 +54,7 @@ License: MIT
import json
import os
from pathlib import Path
-from typing import Any, Dict, Optional, Union
+from typing import Any, Dict, List, Optional, Union
import yaml
diff --git a/semantica/pipeline/pipeline_validator.py b/semantica/pipeline/pipeline_validator.py
index 42c7ba5e..09ed7940 100644
--- a/semantica/pipeline/pipeline_validator.py
+++ b/semantica/pipeline/pipeline_validator.py
@@ -28,12 +28,14 @@ License: MIT
from collections import defaultdict, deque
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional, Union
+from typing import Any, Dict, List, Optional, Union, TYPE_CHECKING
from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
-from .pipeline_builder import Pipeline, PipelineBuilder, PipelineStep
+
+if TYPE_CHECKING:
+ from .pipeline_builder import Pipeline, PipelineBuilder, PipelineStep
@dataclass
@@ -74,7 +76,7 @@ class PipelineValidator:
self.progress_tracker = get_progress_tracker()
def validate_pipeline(
- self, pipeline: Union[Pipeline, PipelineBuilder], **options
+ self, pipeline: Union["Pipeline", "PipelineBuilder"], **options
) -> ValidationResult:
"""
Validate entire pipeline.
@@ -86,6 +88,8 @@ class PipelineValidator:
Returns:
Validation result
"""
+ from .pipeline_builder import Pipeline, PipelineBuilder
+
tracking_id = self.progress_tracker.start_tracking(
module="pipeline",
submodule="PipelineValidator",
@@ -158,7 +162,7 @@ class PipelineValidator:
)
raise
- def _validate_structure(self, pipeline: PipelineBuilder) -> Dict[str, Any]:
+ def _validate_structure(self, pipeline: "PipelineBuilder") -> Dict[str, Any]:
"""Validate pipeline structure."""
errors = []
warnings = []
@@ -186,7 +190,7 @@ class PipelineValidator:
return {"errors": errors, "warnings": warnings}
- def validate_step(self, step: PipelineStep, **constraints) -> ValidationResult:
+ def validate_step(self, step: "PipelineStep", **constraints) -> ValidationResult:
"""
Validate individual pipeline step.
@@ -219,7 +223,7 @@ class PipelineValidator:
)
def check_dependencies(
- self, pipeline: Union[Pipeline, PipelineBuilder]
+ self, pipeline: Union["Pipeline", "PipelineBuilder"]
) -> Dict[str, Any]:
"""
Check pipeline dependencies.
@@ -292,7 +296,7 @@ class PipelineValidator:
raise
def _detect_circular_dependencies(
- self, steps: List[PipelineStep]
+ self, steps: List["PipelineStep"]
) -> List[List[str]]:
"""Detect circular dependencies using DFS."""
step_map = {step.name: step for step in steps}
@@ -327,7 +331,7 @@ class PipelineValidator:
return cycles
- def _find_reachable_steps(self, steps: List[PipelineStep]) -> set:
+ def _find_reachable_steps(self, steps: List["PipelineStep"]) -> set:
"""Find reachable steps from entry points."""
step_map = {step.name: step for step in steps}
reachable = set()
@@ -352,7 +356,7 @@ class PipelineValidator:
return reachable
- def validate_performance(self, pipeline: Pipeline, **options) -> Dict[str, Any]:
+ def validate_performance(self, pipeline: "Pipeline", **options) -> Dict[str, Any]:
"""
Validate pipeline performance.
diff --git a/tests/verify_context_sync.py b/tests/verify_context_sync.py
new file mode 100644
index 00000000..ff0b4b05
--- /dev/null
+++ b/tests/verify_context_sync.py
@@ -0,0 +1,184 @@
+import sys
+import os
+from typing import List, Dict, Any, Optional
+from dataclasses import dataclass, field
+
+# Add project root to path
+sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
+
+from semantica.context import AgentContext, ContextGraph
+
+@dataclass
+class VectorSearchResult:
+ id: str
+ content: str
+ score: float
+ metadata: Dict[str, Any]
+
+class MockVectorStore:
+ def __init__(self):
+ self.items: Dict[str, Any] = {}
+
+ def add(self, items: List[Any]) -> List[str]:
+ ids = []
+ for item in items:
+ # Simple ID generation if not present
+ if not item.memory_id:
+ item.memory_id = f"mem_{len(self.items)}"
+ self.items[item.memory_id] = item
+ ids.append(item.memory_id)
+ print(f"MockVectorStore: Added {len(ids)} items")
+ return ids
+
+ def search(
+ self,
+ query: str,
+ limit: int = 10,
+ filters: Optional[Dict[str, Any]] = None
+ ) -> List[VectorSearchResult]:
+ print(f"MockVectorStore: Searching for '{query}'")
+ results = []
+ # Simple keyword match simulation
+ query_terms = query.lower().split()
+ for item in self.items.values():
+ if any(term in item.content.lower() for term in query_terms):
+ results.append(VectorSearchResult(
+ id=item.memory_id,
+ content=item.content,
+ score=0.8,
+ metadata=item.metadata
+ ))
+ return results[:limit]
+
+ def delete(self, ids: List[str]) -> bool:
+ count = 0
+ for mid in ids:
+ if mid in self.items:
+ del self.items[mid]
+ count += 1
+ return count > 0
+
+def test_synchronous_context():
+ print("--- Testing Synchronous Context Module ---")
+
+ # 1. Initialize Components
+ vs = MockVectorStore()
+ kg = ContextGraph()
+
+ context = AgentContext(vector_store=vs, knowledge_graph=kg)
+ print("AgentContext initialized successfully")
+
+ # 2. Store Memory
+ print("\n--- Testing Store ---")
+ mem_id = context.store(
+ "Python is a popular programming language.",
+ conversation_id="test_conv",
+ extract_entities=True
+ )
+ print(f"Stored memory with ID: {mem_id}")
+
+ # 3. Store Documents (with graph update)
+ print("\n--- Testing Document Store with Graph ---")
+ docs = [
+ {
+ "content": "Machine learning uses Python heavily.",
+ "entities": [
+ {"text": "Machine learning", "type": "CONCEPT"},
+ {"text": "Python", "type": "TOOL"}
+ ],
+ "relationships": [
+ {"source": "Machine learning", "target": "Python", "type": "uses"}
+ ]
+ },
+ {
+ "content": "TensorFlow is a Python library for ML.",
+ "entities": [
+ {"text": "TensorFlow", "type": "TOOL"},
+ {"text": "Python", "type": "TOOL"},
+ {"text": "ML", "type": "CONCEPT"}
+ ],
+ "relationships": [
+ {"source": "TensorFlow", "target": "Python", "type": "based_on"}
+ ]
+ }
+ ]
+ stats = context.store(
+ docs,
+ extract_entities=True,
+ link_entities=True
+ )
+ print(f"Stored documents stats: {stats}")
+
+ # 4. Verify Graph
+ print("\n--- Verifying Graph ---")
+ graph_stats = kg.stats()
+ print(f"Graph stats: {graph_stats}")
+ if graph_stats["node_count"] > 0:
+ print("SUCCESS: Graph nodes created")
+ else:
+ print("WARNING: No graph nodes created (expected if entity extraction is mocked/empty)")
+
+ # 5. Retrieve
+ print("\n--- Testing Retrieval ---")
+ results = context.retrieve("Python", max_results=5)
+ print(f"Retrieved {len(results)} results")
+ for r in results:
+ print(f"- {r['content']} (Score: {r['score']})")
+
+ # 6. Test Short-Term Memory
+ print("\n--- Testing Short-Term Memory (Hierarchical) ---")
+ st_id = context.store(
+ "This is a fleeting thought.",
+ skip_vector=True
+ )
+ print(f"Stored short-term only memory: {st_id}")
+
+ # Verify it's not in vector store (mock check)
+ is_in_vector = any("fleeting" in item.content for item in vs.items.values())
+ print(f"Is in vector store: {is_in_vector} (Expected: False)")
+
+ # Retrieve it (should come from short-term buffer)
+ st_results = context.retrieve("fleeting thought")
+ print(f"Retrieved {len(st_results)} results for short-term query")
+ for r in st_results:
+ source_note = f" [Source: {r.get('source', 'unknown')}]" if 'source' in r else ""
+ print(f"- {r['content']} (Score: {r['score']}){source_note}")
+
+ # 7. Test Token Management
+ print("\n--- Testing Token Management ---")
+ # Initialize a new memory with small token limit
+ from semantica.context import AgentMemory
+
+ # Create isolated memory instance for testing
+ token_memory = AgentMemory(
+ vector_store=vs,
+ token_limit=10, # Small limit (~40 chars)
+ short_term_limit=5 # Count limit
+ )
+
+ token_memory.store("First small item", skip_vector=True) # ~16 chars = 4 tokens
+ token_memory.store("Second small item", skip_vector=True) # ~17 chars = 4 tokens
+ # Total ~8 tokens. Limit 10. Should fit.
+ print(f"Items after 2 small: {len(token_memory.short_term_memory)}")
+
+ token_memory.store("Third small item", skip_vector=True) # ~16 chars = 4 tokens
+ # Total ~12 tokens. Limit 10. Should prune oldest ("First small item").
+ print(f"Items after 3rd small: {len(token_memory.short_term_memory)}")
+ remaining = [m.content for m in token_memory.short_term_memory]
+ print(f"Remaining items: {remaining}")
+
+ if len(token_memory.short_term_memory) == 2 and remaining[0] == "Second small item":
+ print("SUCCESS: Token pruning worked")
+ else:
+ print(f"FAILURE: Token pruning failed. Items: {len(token_memory.short_term_memory)}")
+
+ print("\n--- Test Complete ---")
+
+if __name__ == "__main__":
+ try:
+ test_synchronous_context()
+ except Exception as e:
+ print(f"\nERROR: Test failed with exception: {e}")
+ import traceback
+ traceback.print_exc()
+ sys.exit(1)