Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(context): Add comprehensive memory and context management methods

KaifAhmad137d75f260e4c
diff --git a/cookbook/introduction/19_Context_Module.ipynb b/cookbook/introduction/19_Context_Module.ipynb
new file mode 100644
index 00000000..e06175a2
--- /dev/null
+++ b/cookbook/introduction/19_Context_Module.ipynb
@@ -0,0 +1,1872 @@
+{
+ "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"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/docs/reference/context.md b/docs/reference/context.md
index 10d2a163..c2bd98a8 100644
--- a/docs/reference/context.md
+++ b/docs/reference/context.md
@@ -83,6 +83,63 @@
## 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.
@@ -91,9 +148,12 @@ Builds and manages the context graph.
| Method | Description | Algorithm |
|--------|-------------|-----------|
-| `build_from_entities(entities)` | Build graph from entities | Node creation |
-| `add_conversation(conv)` | Add conversation data | Intent/Entity extraction |
-| `get_subgraph(node_id)` | Get local context | BFS Traversal |
+| `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:**
@@ -105,6 +165,14 @@ 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
@@ -115,9 +183,13 @@ Manages persistent agent memory.
| Method | Description | Algorithm |
|--------|-------------|-----------|
-| `store(text, metadata)` | Store memory item | Embedding + Vector Store |
-| `retrieve(query)` | Retrieve relevant memories | Vector Similarity |
-| `prune(days)` | Remove old memories | Time-based filtering |
+| `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:**
@@ -125,8 +197,14 @@ Manages persistent agent memory.
from semantica.context import AgentMemory
memory = AgentMemory(vector_store=vs, knowledge_graph=kg)
-memory.store("User prefers Python over Java", metadata={"type": "preference"})
-relevant = memory.retrieve("What language does the user like?")
+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
@@ -137,9 +215,26 @@ Links entities across different contexts.
| Method | Description | Algorithm |
|--------|-------------|-----------|
-| `link_entities(entities)` | Link list of entities | Similarity matching |
-| `generate_uri(entity)` | Create unique ID | Hashing |
-| `find_links(entity)` | Find related entities | Graph lookup |
+| `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
@@ -149,25 +244,143 @@ Orchestrates hybrid retrieval.
| Method | Description | Algorithm |
|--------|-------------|-----------|
-| `retrieve(query)` | Get full context | Hybrid (Vector+Graph) |
-| `retrieve_from_graph(query)` | Graph-only retrieval | Traversal |
-| `retrieve_from_memory(query)` | Memory-only retrieval | Vector search |
-
----
+| `retrieve(query, max_results, use_graph_expansion, min_relevance_score, **options)` | Retrieve relevant context for query | Hybrid (Vector+Graph+Memory) |
-## Convenience Functions
+**Example:**
```python
-from semantica.context import build_context
+from semantica.context import ContextRetriever
-# Build context and memory in one go
-context = build_context(
- entities=entities,
- relationships=relationships,
- vector_store=vs,
+retriever = ContextRetriever(
+ memory_store=memory,
knowledge_graph=kg,
- store_initial_memories=True
+ 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)}")
+```
+
+---
+
+## 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
+
+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")
+
+# Load from config file
+context_config = config.ContextConfig(config_file="context_config.yaml")
+all_configs = context_config.get_all()
```
---
@@ -177,9 +390,9 @@ context = build_context(
### Environment Variables
```bash
-export CONTEXT_RETENTION_DAYS=30
-export CONTEXT_MAX_HOPS=2
-export CONTEXT_EMBEDDING_MODEL=all-MiniLM-L6-v2
+export CONTEXT_RETENTION_POLICY=30_days
+export CONTEXT_MAX_MEMORY_SIZE=5000
+export CONTEXT_SIMILARITY_THRESHOLD=0.8
```
### YAML Configuration
@@ -248,8 +461,8 @@ def chat(user_input):
```python
memory = AgentMemory(
- retention_days=7,
- similarity_threshold=0.8
+ retention_policy="7_days",
+ max_memory_size=1000
)
```
diff --git a/semantica/context/__init__.py b/semantica/context/__init__.py
index 49aefacd..5c3e8bc8 100644
--- a/semantica/context/__init__.py
+++ b/semantica/context/__init__.py
@@ -42,6 +42,7 @@ Entity Linking:
- Entity Web Construction: Graph-based entity connection web
Key Features:
+ - High-level interface (AgentContext) for easy use
- Context graph construction from entities, relationships, and conversations
- Agent memory management with RAG integration
- Entity linking across sources with URI assignment
@@ -51,8 +52,11 @@ Key Features:
- Graph-based context traversal and querying
- Method registry for custom context methods
- Configuration management with environment variables and config files
+ - Boolean flags for common options (user-friendly)
+ - Auto-detection of content types and retrieval strategies
Main Classes:
+ - AgentContext: High-level interface for agent context management (store, retrieve, forget, conversation)
- ContextGraphBuilder: Builds context graphs from various sources
- ContextNode: Context graph node data structure
- ContextEdge: Context graph edge data structure
@@ -63,51 +67,48 @@ Main Classes:
- LinkedEntity: Linked entity with context
- ContextRetriever: Retrieves relevant context from multiple sources
- RetrievedContext: Retrieved context item data structure
- - MethodRegistry: Registry for custom context methods
- - ContextConfig: Configuration manager for context module
+ - MethodRegistry: Registry for custom context methods (accessed via registry submodule)
+ - ContextConfig: Configuration manager for context module (accessed via config submodule)
-Convenience Functions:
- - build_context: Build context graph and manage memory in one call
+Submodules:
+ - methods: Context engineering methods (build_context_graph, store_memory, retrieve_context, etc.)
+ - registry: Method registry for custom methods (method_registry, MethodRegistry)
+ - config: Configuration management (context_config, ContextConfig)
Example Usage:
- >>> from semantica.context import build_context, ContextGraphBuilder, AgentMemory
- >>> # Using convenience function
- >>> result = build_context(
- ... entities=entities,
- ... relationships=relationships,
- ... vector_store=vs,
- ... knowledge_graph=kg
- ... )
- >>> # Using classes directly
+ >>> # High-level interface (recommended for most users)
+ >>> from semantica.context import AgentContext
+ >>> context = AgentContext(vector_store=vs, knowledge_graph=kg)
+ >>> memory_id = context.store("User asked about Python", conversation_id="conv1")
+ >>> results = context.retrieve("Python programming")
+ >>> stats = context.store(["Doc 1", "Doc 2"], extract_entities=True)
+
+ >>> # Low-level classes (for advanced use cases)
+ >>> from semantica.context import ContextGraphBuilder, AgentMemory, methods
>>> builder = ContextGraphBuilder()
>>> graph = builder.build_from_entities_and_relationships(entities, relationships)
>>> memory = AgentMemory(vector_store=vs, knowledge_graph=kg)
>>> memory_id = memory.store("User asked about Python", metadata={"type": "conversation"})
>>> results = memory.retrieve("Python", max_results=5)
+ >>> # Using methods submodule
+ >>> graph = methods.build_context_graph(entities, relationships, method="entities_relationships")
Author: Semantica Contributors
License: MIT
"""
-from pathlib import Path
-from typing import Any, Dict, List, Optional, Union
-
+from .agent_context import AgentContext
from .agent_memory import AgentMemory, MemoryItem
-from .config import ContextConfig, context_config
from .context_graph import ContextEdge, ContextGraphBuilder, ContextNode
from .context_retriever import ContextRetriever, RetrievedContext
from .entity_linker import EntityLink, EntityLinker, LinkedEntity
-from .methods import (
- build_context_graph,
- get_context_method,
- link_entities,
- list_available_methods,
- retrieve_context,
- store_memory,
-)
-from .registry import MethodRegistry, method_registry
+from . import methods
+from . import registry
+from . import config
__all__ = [
+ # High-level interface
+ "AgentContext",
# Main classes
"ContextGraphBuilder",
"ContextNode",
@@ -119,112 +120,8 @@ __all__ = [
"MemoryItem",
"ContextRetriever",
"RetrievedContext",
- # Registry
- "MethodRegistry",
- "method_registry",
- # Methods
- "build_context_graph",
- "store_memory",
- "retrieve_context",
- "link_entities",
- "get_context_method",
- "list_available_methods",
- # Config
- "ContextConfig",
- "context_config",
- # Convenience
- "build_context",
+ # Submodules
+ "methods",
+ "registry",
+ "config",
]
-
-
-def build_context(
- entities: Optional[List[Dict[str, Any]]] = None,
- relationships: Optional[List[Dict[str, Any]]] = None,
- conversations: Optional[List[Union[str, Dict[str, Any]]]] = None,
- vector_store: Optional[Any] = None,
- knowledge_graph: Optional[Any] = None,
- graph_method: str = "entities_relationships",
- store_initial_memories: bool = False,
- **options,
-) -> Dict[str, Any]:
- """
- Build context graph and optionally manage memory (convenience function).
-
- This is a user-friendly wrapper that builds context graphs and optionally
- stores initial memories in one call.
-
- Args:
- entities: List of entity dictionaries
- relationships: List of relationship dictionaries
- conversations: List of conversation files or dictionaries
- vector_store: Vector store instance for memory
- knowledge_graph: Knowledge graph instance
- graph_method: Graph construction method (default: "entities_relationships")
- store_initial_memories: Whether to store initial memories from entities
- **options: Additional options passed to builders
-
- Returns:
- Dictionary containing:
- - graph: Context graph dictionary
- - memory_ids: List of stored memory IDs (if store_initial_memories=True)
- - statistics: Graph and memory statistics
-
- Examples:
- >>> from semantica.context import build_context
- >>> entities = [{"id": "e1", "text": "Python", "type": "PROGRAMMING_LANGUAGE"}]
- >>> relationships = [{"source_id": "e1", "target_id": "e2", "type": "related_to"}]
- >>> result = build_context(
- ... entities=entities,
- ... relationships=relationships,
- ... vector_store=vs,
- ... knowledge_graph=kg
- ... )
- >>> print(f"Graph has {result['graph']['statistics']['node_count']} nodes")
- """
- from ..utils.logging import get_logger
-
- logger = get_logger("context")
-
- # Build context graph
- graph = build_context_graph(
- entities=entities,
- relationships=relationships,
- conversations=conversations,
- method=graph_method,
- **options,
- )
-
- memory_ids = []
-
- # Optionally store initial memories
- if store_initial_memories and vector_store:
- memory = AgentMemory(
- vector_store=vector_store, knowledge_graph=knowledge_graph, **options
- )
-
- # Store entity-based memories
- if entities:
- for entity in entities[:10]: # Limit to first 10
- entity_text = (
- entity.get("text") or entity.get("label") or entity.get("name", "")
- )
- if entity_text:
- memory_id = memory.store(
- f"Entity: {entity_text}",
- metadata={
- "type": "entity",
- "entity_id": entity.get("id"),
- "entity_type": entity.get("type"),
- },
- entities=[entity] if entity.get("id") else None,
- )
- memory_ids.append(memory_id)
-
- return {
- "graph": graph,
- "memory_ids": memory_ids,
- "statistics": {
- "graph": graph.get("statistics", {}),
- "memories_stored": len(memory_ids),
- },
- }
diff --git a/semantica/context/agent_context.py b/semantica/context/agent_context.py
new file mode 100644
index 00000000..5f42a86d
--- /dev/null
+++ b/semantica/context/agent_context.py
@@ -0,0 +1,1277 @@
+"""
+High-Level Agent Context Interface
+
+This module provides a simplified, generic high-level interface for agent context management,
+RAG, and GraphRAG. It uses generic method names (store, retrieve, forget, conversation) that
+auto-detect content types and retrieval strategies, with boolean flags for common options.
+
+Key Features:
+ - Generic methods: store(), retrieve(), forget(), conversation()
+ - Auto-detection: Memory vs documents, RAG vs GraphRAG
+ - Boolean flags: Simple True/False parameters for common options
+ - User-friendly: Easy to use interface for agentic systems
+
+Example Usage:
+ >>> from semantica.context import AgentContext
+ >>> context = AgentContext(vector_store=vs, knowledge_graph=kg)
+ >>> memory_id = context.store("User likes Python", conversation_id="conv1")
+ >>> results = context.retrieve("Python programming")
+ >>> stats = context.store(["Doc 1", "Doc 2"], extract_entities=True)
+"""
+
+from datetime import datetime
+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_retriever import ContextRetriever, RetrievedContext
+from .entity_linker import EntityLinker
+
+
+class 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. Uses boolean flags for common options.
+
+ Attributes:
+ vector_store: Vector store instance
+ 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)
+
+ Main Methods:
+ - store(): Store memory or documents (auto-detects type)
+ - retrieve(): Retrieve context (auto-detects RAG vs GraphRAG)
+ - forget(): Delete memories
+ - conversation(): Get conversation history
+ - get_memory(): Get specific memory by ID
+ - stats(): Get memory statistics
+ - link(): Link entities in text
+ - build_graph(): Build context graph manually
+
+ Example:
+ >>> context = AgentContext(vector_store=vs, knowledge_graph=kg)
+ >>> memory_id = context.store("User likes Python", conversation_id="conv1")
+ >>> results = context.retrieve("Python programming")
+ >>> stats = context.stats()
+ >>> memory = context.get_memory(memory_id)
+ """
+
+ def __init__(
+ self,
+ vector_store,
+ knowledge_graph=None,
+ retention_days: Optional[int] = 30,
+ max_memories: int = 10000,
+ use_graph_expansion: bool = True,
+ max_expansion_hops: int = 2,
+ hybrid_alpha: float = 0.5,
+ **kwargs
+ ):
+ """
+ Initialize AgentContext.
+
+ Args:
+ vector_store: Vector store instance (required)
+ knowledge_graph: Knowledge graph instance (optional, enables GraphRAG)
+ retention_days: Days to keep memories (default: 30, None=unlimited)
+ max_memories: Maximum number of memories (default: 10000)
+ use_graph_expansion: Enable graph expansion for retrieval (default: True)
+ max_expansion_hops: Maximum hops for graph expansion (default: 2)
+ hybrid_alpha: Balance between vector (0) and graph (1) retrieval (default: 0.5)
+ **kwargs: Additional options passed to underlying components
+
+ Raises:
+ ValueError: If vector_store is not provided
+ """
+ self.logger = get_logger("agent_context")
+
+ if vector_store is None:
+ raise ValueError(
+ "vector_store is required for AgentContext. "
+ "Please provide a vector store instance. "
+ "Example: AgentContext(vector_store=your_vector_store)"
+ )
+
+ self.vector_store = vector_store
+ self.knowledge_graph = knowledge_graph
+
+ # Initialize AgentMemory
+ retention_policy = f"{retention_days}_days" if retention_days else "unlimited"
+ memory_config = {
+ "vector_store": vector_store,
+ "knowledge_graph": knowledge_graph,
+ "retention_policy": retention_policy,
+ "max_memory_size": max_memories,
+ **kwargs
+ }
+ self._memory = AgentMemory(**memory_config)
+
+ # Initialize ContextRetriever if knowledge_graph available
+ if knowledge_graph:
+ retriever_config = {
+ "memory_store": self._memory,
+ "knowledge_graph": knowledge_graph,
+ "vector_store": vector_store,
+ "use_graph_expansion": use_graph_expansion,
+ "max_expansion_hops": max_expansion_hops,
+ "hybrid_alpha": hybrid_alpha,
+ **kwargs
+ }
+ self._retriever = ContextRetriever(**retriever_config)
+ else:
+ self._retriever = None
+
+ # Initialize ContextGraphBuilder if knowledge_graph available
+ if knowledge_graph:
+ self._graph_builder = ContextGraphBuilder()
+ else:
+ self._graph_builder = None
+
+ # Store config
+ self.config = {
+ "retention_days": retention_days,
+ "max_memories": max_memories,
+ "use_graph_expansion": use_graph_expansion,
+ "max_expansion_hops": max_expansion_hops,
+ "hybrid_alpha": hybrid_alpha,
+ }
+
+ @property
+ def memory(self) -> AgentMemory:
+ """Access underlying AgentMemory instance."""
+ return self._memory
+
+ @property
+ def retriever(self) -> Optional[ContextRetriever]:
+ """Access underlying ContextRetriever instance."""
+ return self._retriever
+
+ @property
+ def graph_builder(self) -> Optional[ContextGraphBuilder]:
+ """Access underlying ContextGraphBuilder instance."""
+ return self._graph_builder
+
+ def store(
+ self,
+ content: Union[str, List[str], List[Dict[str, Any]]],
+ metadata: Optional[Dict[str, Any]] = None,
+ conversation_id: Optional[str] = None,
+ user_id: Optional[str] = None,
+ entities: Optional[List[Dict[str, Any]]] = None,
+ relationships: Optional[List[Dict[str, Any]]] = None,
+ extract_entities: bool = True,
+ extract_relationships: bool = True,
+ link_entities: bool = True,
+ auto_extract: bool = False,
+ **kwargs
+ ) -> Union[str, Dict[str, Any]]:
+ """
+ Store content (memory or documents).
+
+ Auto-detects content type:
+ - Single string -> Memory item
+ - List of strings/dicts -> Documents (builds graph if knowledge_graph available)
+
+ Args:
+ content: Content to store:
+ - str: Single memory item
+ - List[str]: Multiple documents
+ - List[Dict]: Documents with metadata
+ metadata: Additional metadata dict
+ conversation_id: Conversation ID (for memories)
+ user_id: User ID (for memories)
+ entities: Pre-extracted entities (optional)
+ relationships: Pre-extracted relationships (optional)
+ extract_entities: Extract entities from documents (default: True)
+ extract_relationships: Extract relationships (default: True)
+ link_entities: Link entities across documents (default: True)
+ auto_extract: Auto-extract entities/relationships if not provided (default: False)
+ **kwargs: Additional options passed to storage methods
+
+ Returns:
+ - str: Memory ID (for single memory)
+ - Dict: Statistics (for documents) with keys: stored_count, graph_nodes, graph_edges
+
+ Example:
+ >>> # Store memory
+ >>> memory_id = context.store("User likes Python", conversation_id="conv1")
+
+ >>> # Store documents
+ >>> stats = context.store(["Doc 1", "Doc 2"], extract_entities=True)
+ """
+ # Auto-detect content type
+ if isinstance(content, str):
+ # Single memory item
+ memory_metadata = metadata or {}
+ if conversation_id:
+ memory_metadata["conversation_id"] = conversation_id
+ if user_id:
+ memory_metadata["user_id"] = user_id
+
+ return self._memory.store(
+ content,
+ metadata=memory_metadata,
+ entities=entities,
+ relationships=relationships,
+ **kwargs
+ )
+
+ elif isinstance(content, list):
+ # Documents - normalize to list of dicts
+ documents = self._normalize_documents(content)
+
+ # Add entities/relationships to documents if provided
+ if entities or relationships:
+ for doc in documents:
+ if entities and "entities" not in doc:
+ doc["entities"] = entities
+ if relationships and "relationships" not in doc:
+ doc["relationships"] = relationships
+
+ # Store each document in vector store
+ stored_ids = []
+ for doc in documents:
+ doc_metadata = {**(metadata or {}), **doc.get("metadata", {})}
+ doc_entities = doc.get("entities")
+ doc_relationships = doc.get("relationships")
+
+ doc_id = self._memory.store(
+ doc["content"],
+ metadata=doc_metadata,
+ entities=doc_entities,
+ relationships=doc_relationships,
+ **kwargs
+ )
+ stored_ids.append(doc_id)
+
+ # Build graph if knowledge_graph available and flags set
+ graph_stats = {}
+ if self.knowledge_graph and (extract_entities or extract_relationships or auto_extract):
+ graph_stats = self._build_graph_from_documents(
+ documents,
+ extract_entities=extract_entities or auto_extract,
+ extract_relationships=extract_relationships or auto_extract,
+ link_entities=link_entities
+ )
+
+ return {
+ "stored_count": len(stored_ids),
+ "memory_ids": stored_ids,
+ "graph_nodes": graph_stats.get("node_count", 0),
+ "graph_edges": graph_stats.get("edge_count", 0),
+ }
+
+ else:
+ raise ValueError(
+ f"Unsupported content type: {type(content)}. "
+ "Expected str (single memory) or list (multiple documents). "
+ f"Received: {type(content).__name__}"
+ )
+
+ def retrieve(
+ self,
+ query: str,
+ max_results: int = 5,
+ use_graph: Optional[bool] = None,
+ min_score: float = 0.0,
+ conversation_id: Optional[str] = None,
+ user_id: Optional[str] = None,
+ include_entities: bool = True,
+ include_relationships: bool = False,
+ expand_graph: bool = True,
+ deduplicate: bool = True,
+ **kwargs
+ ) -> List[Dict[str, Any]]:
+ """
+ Retrieve relevant context.
+
+ Auto-detects best strategy:
+ - If knowledge_graph available -> GraphRAG (hybrid retrieval)
+ - Otherwise -> Simple RAG (vector only)
+
+ Args:
+ query: Search query
+ max_results: Maximum results (default: 5)
+ use_graph: Force graph usage (None=auto-detect, True=force, False=vector only)
+ min_score: Minimum relevance score (default: 0.0)
+ conversation_id: Filter by conversation ID
+ user_id: Filter by user ID
+ include_entities: Include related entities in results (default: True)
+ include_relationships: Include relationships in results (default: False)
+ expand_graph: Use graph expansion (default: True)
+ deduplicate: Deduplicate results (default: True)
+ **kwargs: Additional filters (type, date_range, etc.)
+
+ Returns:
+ List of context dicts with keys: content, score, source, metadata, related_entities
+
+ Example:
+ >>> # Auto-detects RAG vs GraphRAG
+ >>> results = context.retrieve("Python programming")
+
+ >>> # Force vector-only retrieval
+ >>> results = context.retrieve("Python", use_graph=False)
+ """
+ # Auto-detect strategy
+ if use_graph is None:
+ use_graph = (self.knowledge_graph is not None and self._retriever is not None)
+
+ # Apply filters if provided
+ if conversation_id:
+ kwargs["conversation_id"] = conversation_id
+ if user_id:
+ kwargs["user_id"] = user_id
+
+ if use_graph and self._retriever:
+ # GraphRAG: Use ContextRetriever (hybrid retrieval)
+ results = self._retriever.retrieve(
+ query,
+ max_results=max_results,
+ use_graph_expansion=expand_graph,
+ min_relevance_score=min_score,
+ **kwargs
+ )
+ # Convert RetrievedContext to dicts
+ return [self._context_to_dict(r, include_entities, include_relationships) for r in results]
+ else:
+ # Simple RAG: Use AgentMemory (vector + memory)
+ results = self._memory.retrieve(
+ query,
+ max_results=max_results,
+ min_score=min_score,
+ **kwargs
+ )
+ # Convert to dicts
+ return [self._memory_to_dict(r) for r in results]
+
+ def forget(
+ self,
+ memory_id: Optional[str] = None,
+ conversation_id: Optional[str] = None,
+ user_id: Optional[str] = None,
+ days_old: Optional[int] = None,
+ **filters
+ ) -> int:
+ """
+ Delete memories.
+
+ Args:
+ memory_id: Delete specific memory by ID
+ conversation_id: Delete all memories in conversation
+ user_id: Delete all memories for user
+ days_old: Delete memories older than N days
+ **filters: Additional filters (type, date_range, etc.)
+
+ Returns:
+ Number of memories deleted
+
+ Example:
+ >>> context.forget(memory_id="mem123")
+ >>> context.forget(conversation_id="conv1")
+ >>> context.forget(days_old=90)
+ """
+ if memory_id:
+ self._memory.delete_memory(memory_id)
+ return 1
+
+ # Build filters dict
+ filter_dict = {}
+ if conversation_id:
+ filter_dict["conversation_id"] = conversation_id
+ if user_id:
+ filter_dict["user_id"] = user_id
+ if days_old:
+ from datetime import datetime, timedelta
+ filter_dict["start_date"] = (datetime.now() - timedelta(days=days_old)).isoformat()
+ filter_dict.update(filters)
+
+ return self._memory.clear_memory(**filter_dict)
+
+ def conversation(
+ self,
+ conversation_id: str,
+ max_items: int = 100,
+ reverse: bool = False,
+ include_metadata: bool = True,
+ **kwargs
+ ) -> List[Dict[str, Any]]:
+ """
+ Get conversation history.
+
+ Args:
+ conversation_id: Conversation ID
+ max_items: Maximum items to return (default: 100)
+ reverse: Return in reverse chronological order (default: False)
+ include_metadata: Include full metadata (default: True)
+ **kwargs: Additional options
+
+ Returns:
+ List of memory dicts in conversation
+
+ Example:
+ >>> history = context.conversation("conv1")
+ >>> history = context.conversation("conv1", reverse=True, include_metadata=False)
+ """
+ history = self._memory.get_conversation_history(
+ conversation_id=conversation_id,
+ max_items=max_items
+ )
+
+ # Convert to dicts
+ result = []
+ for item in history:
+ item_dict = {
+ "id": item.get("id"),
+ "content": item.get("content"),
+ "timestamp": item.get("timestamp"),
+ }
+ if include_metadata:
+ item_dict["metadata"] = item.get("metadata", {})
+ result.append(item_dict)
+
+ if reverse:
+ result.reverse()
+
+ return result
+
+ def _normalize_documents(self, content: List[Union[str, Dict[str, Any]]]) -> List[Dict[str, Any]]:
+ """Normalize documents to list of dicts."""
+ documents = []
+ for i, doc in enumerate(content):
+ if isinstance(doc, str):
+ documents.append({
+ "content": doc,
+ "id": f"doc_{i}",
+ "metadata": {}
+ })
+ elif isinstance(doc, dict):
+ if "content" not in doc:
+ raise ValueError(f"Document dict must have 'content' key: {doc}")
+ documents.append({
+ "content": doc["content"],
+ "id": doc.get("id", f"doc_{i}"),
+ "metadata": doc.get("metadata", {})
+ })
+ else:
+ raise ValueError(f"Unsupported document type: {type(doc)}")
+ return documents
+
+ def _build_graph_from_documents(
+ self,
+ documents: List[Dict[str, Any]],
+ extract_entities: bool = True,
+ extract_relationships: bool = True,
+ link_entities: bool = True
+ ) -> Dict[str, Any]:
+ """Build graph from documents."""
+ if not self._graph_builder:
+ return {"node_count": 0, "edge_count": 0}
+
+ try:
+ # Convert documents to conversations format
+ conversations = []
+ for doc in documents:
+ conv = {
+ "id": doc.get("id", "unknown"),
+ "content": doc["content"],
+ "entities": doc.get("entities", []),
+ "relationships": doc.get("relationships", [])
+ }
+ conversations.append(conv)
+
+ # Build graph from conversations
+ graph = self._graph_builder.build_from_conversations(
+ conversations,
+ link_entities=link_entities,
+ extract_intents=False,
+ extract_sentiments=False
+ )
+
+ return {
+ "node_count": graph.get("statistics", {}).get("node_count", 0),
+ "edge_count": graph.get("statistics", {}).get("edge_count", 0),
+ }
+ except Exception as e:
+ self.logger.warning(f"Failed to build graph from documents: {e}")
+ return {"node_count": 0, "edge_count": 0}
+
+ def _context_to_dict(
+ self,
+ context: RetrievedContext,
+ include_entities: bool = True,
+ include_relationships: bool = False
+ ) -> Dict[str, Any]:
+ """Convert RetrievedContext to dict."""
+ result = {
+ "content": context.content,
+ "score": context.score,
+ "source": context.source,
+ "metadata": context.metadata,
+ }
+
+ if include_entities:
+ result["related_entities"] = context.related_entities
+
+ if include_relationships:
+ result["related_relationships"] = context.related_relationships
+
+ return result
+
+ def _memory_to_dict(self, memory: Dict[str, Any]) -> Dict[str, Any]:
+ """Convert memory result to dict."""
+ return {
+ "content": memory.get("content", ""),
+ "score": memory.get("score", 0.0),
+ "source": "memory",
+ "metadata": memory.get("metadata", {}),
+ "related_entities": [],
+ "related_relationships": [],
+ }
+
+ def get_memory(self, memory_id: str) -> Optional[Dict[str, Any]]:
+ """
+ Get a specific memory by ID.
+
+ Args:
+ memory_id: Memory ID
+
+ Returns:
+ Memory dict or None if not found
+
+ Example:
+ >>> memory = context.get_memory("mem123")
+ """
+ memory_item = self._memory.get_memory(memory_id)
+ if memory_item:
+ return {
+ "id": memory_item.get("id"),
+ "content": memory_item.get("content"),
+ "timestamp": memory_item.get("timestamp"),
+ "metadata": memory_item.get("metadata", {}),
+ }
+ return None
+
+ def stats(self) -> Dict[str, Any]:
+ """
+ Get statistics about stored memories.
+
+ Returns:
+ Dict with statistics: total_items, items_by_type, etc.
+
+ Example:
+ >>> stats = context.stats()
+ >>> print(f"Total memories: {stats['total_items']}")
+ """
+ return self._memory.get_statistics()
+
+ def link(
+ self,
+ text: str,
+ entities: Optional[List[Dict[str, Any]]] = None,
+ similarity_threshold: float = 0.8,
+ **kwargs
+ ) -> List[Dict[str, Any]]:
+ """
+ Link entities in text (if knowledge_graph available).
+
+ Args:
+ text: Text containing entities
+ entities: List of entities to link
+ similarity_threshold: Similarity threshold for linking (default: 0.8)
+ **kwargs: Additional options
+
+ Returns:
+ List of linked entity dicts
+
+ Raises:
+ ValueError: If knowledge_graph not available
+
+ Example:
+ >>> linked = context.link("Python is used for ML", entities=[...])
+ """
+ if not self.knowledge_graph:
+ raise ValueError(
+ "knowledge_graph is required for entity linking. "
+ "Please initialize AgentContext with a knowledge_graph parameter. "
+ "Example: AgentContext(vector_store=vs, knowledge_graph=kg)"
+ )
+
+ from .entity_linker import EntityLinker
+
+ linker = EntityLinker(
+ knowledge_graph=self.knowledge_graph,
+ similarity_threshold=similarity_threshold,
+ **kwargs
+ )
+
+ linked_entities = linker.link(text, entities=entities or [])
+
+ return [
+ {
+ "entity_id": e.entity_id,
+ "uri": e.uri,
+ "text": e.text,
+ "type": e.type,
+ "linked_count": len(e.linked_entities),
+ "confidence": e.confidence,
+ }
+ for e in linked_entities
+ ]
+
+ def build_graph(
+ self,
+ entities: Optional[List[Dict[str, Any]]] = None,
+ relationships: Optional[List[Dict[str, Any]]] = None,
+ conversations: Optional[List[Dict[str, Any]]] = None,
+ link_entities: bool = True,
+ **kwargs
+ ) -> Dict[str, Any]:
+ """
+ Build context graph from entities, relationships, or conversations.
+
+ Args:
+ entities: List of entities
+ relationships: List of relationships
+ conversations: List of conversations
+ link_entities: Link entities (default: True)
+ **kwargs: Additional options
+
+ Returns:
+ Graph statistics dict
+
+ Raises:
+ ValueError: If knowledge_graph not available
+
+ Example:
+ >>> graph = context.build_graph(entities=entities, relationships=relationships)
+ """
+ if not self._graph_builder:
+ raise ValueError(
+ "knowledge_graph is required for graph building. "
+ "Please initialize AgentContext with a knowledge_graph parameter. "
+ "Example: AgentContext(vector_store=vs, knowledge_graph=kg)"
+ )
+
+ if entities and relationships:
+ graph = self._graph_builder.build_from_entities_and_relationships(
+ entities, relationships, **kwargs
+ )
+ elif conversations:
+ graph = self._graph_builder.build_from_conversations(
+ conversations,
+ link_entities=link_entities,
+ **kwargs
+ )
+ else:
+ raise ValueError(
+ "Must provide either (entities and relationships) or conversations. "
+ f"Received: entities={entities is not None}, "
+ f"relationships={relationships is not None}, "
+ f"conversations={conversations is not None}"
+ )
+
+ return graph.get("statistics", {})
+
+ # Memory Management Methods
+ def exists(self, memory_id: str) -> bool:
+ """
+ Check if memory exists.
+
+ Args:
+ memory_id: Memory ID to check
+
+ Returns:
+ True if memory exists, False otherwise
+
+ Example:
+ >>> if context.exists("mem123"):
+ ... print("Memory exists")
+ """
+ return self._memory.get_memory(memory_id) is not None
+
+ def count(self, **filters) -> int:
+ """
+ Get total memory count with optional filters.
+
+ Args:
+ **filters: Optional filters (conversation_id, user_id, type, etc.)
+
+ Returns:
+ Total count of memories matching filters
+
+ Example:
+ >>> total = context.count()
+ >>> conv_count = context.count(conversation_id="conv1")
+ """
+ stats = self._memory.get_statistics()
+ if not filters:
+ return stats.get("total_items", 0)
+
+ # Filter memories
+ count = 0
+ for memory_id in self._memory.memory_items:
+ memory_item = self._memory.memory_items[memory_id]
+ if self._memory._matches_filters(memory_item, filters):
+ count += 1
+ return count
+
+ def get(self, memory_id: str) -> Optional[Dict[str, Any]]:
+ """
+ Get memory by ID (alias for get_memory).
+
+ Args:
+ memory_id: Memory ID
+
+ Returns:
+ Memory dict or None if not found
+
+ Example:
+ >>> memory = context.get("mem123")
+ """
+ return self.get_memory(memory_id)
+
+ def update(
+ self,
+ memory_id: str,
+ content: Optional[str] = None,
+ metadata: Optional[Dict[str, Any]] = None,
+ **kwargs
+ ) -> bool:
+ """
+ Update existing memory.
+
+ Args:
+ memory_id: Memory ID to update
+ content: New content (optional)
+ metadata: New metadata (optional, merged with existing)
+ **kwargs: Additional fields to update
+
+ Returns:
+ True if updated successfully, False if not found
+
+ Example:
+ >>> context.update("mem123", content="Updated content")
+ >>> context.update("mem123", metadata={"new_key": "value"})
+ """
+ memory_item = self._memory.get_memory(memory_id)
+ if not memory_item:
+ return False
+
+ # Get current values
+ current_content = content if content is not None else memory_item.get("content", "")
+ current_metadata = memory_item.get("metadata", {})
+ if metadata:
+ current_metadata.update(metadata)
+
+ # Delete old and create new
+ self._memory.delete_memory(memory_id)
+ new_id = self._memory.store(
+ current_content,
+ metadata=current_metadata,
+ entities=memory_item.get("entities", []),
+ relationships=memory_item.get("relationships", []),
+ **kwargs
+ )
+
+ return new_id is not None
+
+ def delete(self, memory_id: str) -> bool:
+ """
+ Delete memory by ID (alias for forget with memory_id).
+
+ Args:
+ memory_id: Memory ID to delete
+
+ Returns:
+ True if deleted, False if not found
+
+ Example:
+ >>> context.delete("mem123")
+ """
+ if self.exists(memory_id):
+ self._memory.delete_memory(memory_id)
+ return True
+ return False
+
+ def clear(self, **filters) -> int:
+ """
+ Clear memories with filters (alias for forget).
+
+ Args:
+ **filters: Filter criteria (conversation_id, user_id, days_old, etc.)
+
+ Returns:
+ Number of memories deleted
+
+ Example:
+ >>> deleted = context.clear(conversation_id="conv1")
+ >>> deleted = context.clear(days_old=90)
+ """
+ return self.forget(**filters)
+
+ def list(
+ self,
+ conversation_id: Optional[str] = None,
+ user_id: Optional[str] = None,
+ limit: int = 100,
+ offset: int = 0,
+ **filters
+ ) -> List[Dict[str, Any]]:
+ """
+ List memories with pagination.
+
+ Args:
+ conversation_id: Filter by conversation ID
+ user_id: Filter by user ID
+ limit: Maximum items to return (default: 100)
+ offset: Number of items to skip (default: 0)
+ **filters: Additional filters
+
+ Returns:
+ List of memory dicts
+
+ Example:
+ >>> memories = context.list(conversation_id="conv1", limit=50)
+ >>> memories = context.list(user_id="user123", limit=20, offset=10)
+ """
+ all_filters = {**filters}
+ if conversation_id:
+ all_filters["conversation_id"] = conversation_id
+ if user_id:
+ all_filters["user_id"] = user_id
+
+ results = []
+ for memory_id in list(self._memory.memory_items.keys())[offset:offset + limit]:
+ memory_item = self._memory.memory_items[memory_id]
+ if not all_filters or self._memory._matches_filters(memory_item, all_filters):
+ mem_dict = self._memory.get_memory(memory_id)
+ if mem_dict:
+ results.append(mem_dict)
+
+ return results
+
+ def batch_store(self, items: List[Union[str, Dict[str, Any]]]) -> List[str]:
+ """
+ Store multiple items at once.
+
+ Args:
+ items: List of items to store (strings or dicts with content)
+
+ Returns:
+ List of memory IDs
+
+ Example:
+ >>> ids = context.batch_store(["Item 1", "Item 2", "Item 3"])
+ """
+ memory_ids = []
+ for item in items:
+ if isinstance(item, str):
+ memory_id = self.store(item)
+ memory_ids.append(memory_id)
+ elif isinstance(item, dict):
+ content = item.get("content", "")
+ if content:
+ memory_id = self.store(
+ content,
+ metadata=item.get("metadata"),
+ conversation_id=item.get("conversation_id"),
+ user_id=item.get("user_id"),
+ **{k: v for k, v in item.items() if k not in ["content", "metadata", "conversation_id", "user_id"]}
+ )
+ memory_ids.append(memory_id)
+ return memory_ids
+
+ def batch_delete(self, memory_ids: List[str]) -> int:
+ """
+ Delete multiple memories.
+
+ Args:
+ memory_ids: List of memory IDs to delete
+
+ Returns:
+ Number of memories deleted
+
+ Example:
+ >>> deleted = context.batch_delete(["mem1", "mem2", "mem3"])
+ """
+ deleted = 0
+ for memory_id in memory_ids:
+ if self.delete(memory_id):
+ deleted += 1
+ return deleted
+
+ def batch_update(self, updates: List[Dict[str, Any]]) -> int:
+ """
+ Update multiple memories.
+
+ Args:
+ updates: List of update dicts with 'memory_id' and fields to update
+
+ Returns:
+ Number of memories updated
+
+ Example:
+ >>> updated = context.batch_update([
+ ... {"memory_id": "mem1", "content": "New content"},
+ ... {"memory_id": "mem2", "metadata": {"key": "value"}}
+ ... ])
+ """
+ updated = 0
+ for update in updates:
+ memory_id = update.get("memory_id")
+ if memory_id and self.update(memory_id, **{k: v for k, v in update.items() if k != "memory_id"}):
+ updated += 1
+ return updated
+
+ # Search and Retrieval Methods
+ def search(self, query: str, **filters) -> List[Dict[str, Any]]:
+ """
+ Simple search with filters (alias for retrieve).
+
+ Args:
+ query: Search query
+ **filters: Additional filters (max_results, min_score, conversation_id, etc.)
+
+ Returns:
+ List of context dicts
+
+ Example:
+ >>> results = context.search("Python", max_results=10)
+ >>> results = context.search("Python", conversation_id="conv1")
+ """
+ return self.retrieve(query, **filters)
+
+ def find_similar(self, content: str, limit: int = 5, **kwargs) -> List[Dict[str, Any]]:
+ """
+ Find similar content.
+
+ Args:
+ content: Content to find similar items for
+ limit: Maximum results (default: 5)
+ **kwargs: Additional options
+
+ Returns:
+ List of similar content dicts
+
+ Example:
+ >>> similar = context.find_similar("Python programming", limit=5)
+ """
+ return self.retrieve(content, max_results=limit, **kwargs)
+
+ def get_context(self, query: str, max_results: int = 5, **kwargs) -> List[Dict[str, Any]]:
+ """
+ Get context for query.
+
+ Args:
+ query: Query string
+ max_results: Maximum results (default: 5)
+ **kwargs: Additional options
+
+ Returns:
+ List of context dicts
+
+ Example:
+ >>> context_data = context.get_context("Python", max_results=10)
+ """
+ return self.retrieve(query, max_results=max_results, **kwargs)
+
+ def expand_query(self, query: str, max_hops: int = 2, **kwargs) -> List[Dict[str, Any]]:
+ """
+ Expand query with graph context.
+
+ Args:
+ query: Query string
+ max_hops: Maximum graph expansion hops (default: 2)
+ **kwargs: Additional options
+
+ Returns:
+ List of expanded context dicts
+
+ Example:
+ >>> expanded = context.expand_query("Python", max_hops=3)
+ """
+ if not self._retriever:
+ return self.retrieve(query, **kwargs)
+
+ return self.retrieve(
+ query,
+ expand_graph=True,
+ max_expansion_hops=max_hops,
+ **kwargs
+ )
+
+ # Conversation Methods
+ def get_conversation(self, conversation_id: str, limit: int = 100, **kwargs) -> List[Dict[str, Any]]:
+ """
+ Get conversation (alias for conversation).
+
+ Args:
+ conversation_id: Conversation ID
+ limit: Maximum items (default: 100)
+ **kwargs: Additional options
+
+ Returns:
+ List of conversation memory dicts
+
+ Example:
+ >>> conv = context.get_conversation("conv1", limit=50)
+ """
+ return self.conversation(conversation_id, max_items=limit, **kwargs)
+
+ def list_conversations(self, user_id: Optional[str] = None, limit: int = 50) -> List[str]:
+ """
+ List all conversations.
+
+ Args:
+ user_id: Filter by user ID (optional)
+ limit: Maximum conversations to return (default: 50)
+
+ Returns:
+ List of conversation IDs
+
+ Example:
+ >>> conversations = context.list_conversations()
+ >>> user_convs = context.list_conversations(user_id="user123")
+ """
+ conversation_ids = set()
+ for memory_id, memory_item in self._memory.memory_items.items():
+ conv_id = memory_item.metadata.get("conversation_id")
+ if conv_id:
+ if user_id is None or memory_item.metadata.get("user_id") == user_id:
+ conversation_ids.add(conv_id)
+
+ return list(conversation_ids)[:limit]
+
+ def delete_conversation(self, conversation_id: str) -> int:
+ """
+ Delete entire conversation.
+
+ Args:
+ conversation_id: Conversation ID to delete
+
+ Returns:
+ Number of memories deleted
+
+ Example:
+ >>> deleted = context.delete_conversation("conv1")
+ """
+ return self.forget(conversation_id=conversation_id)
+
+ def conversation_summary(self, conversation_id: str) -> Dict[str, Any]:
+ """
+ Get conversation summary.
+
+ Args:
+ conversation_id: Conversation ID
+
+ Returns:
+ Summary dict with count, first_message, last_message, etc.
+
+ Example:
+ >>> summary = context.conversation_summary("conv1")
+ """
+ history = self.conversation(conversation_id, max_items=1000)
+
+ if not history:
+ return {
+ "conversation_id": conversation_id,
+ "message_count": 0,
+ "first_message": None,
+ "last_message": None,
+ }
+
+ return {
+ "conversation_id": conversation_id,
+ "message_count": len(history),
+ "first_message": history[0] if history else None,
+ "last_message": history[-1] if history else None,
+ "user_id": history[0].get("metadata", {}).get("user_id") if history else None,
+ }
+
+ # Export/Import Methods
+ def export(
+ self,
+ conversation_id: Optional[str] = None,
+ format: str = 'json',
+ **filters
+ ) -> Union[str, Dict[str, Any]]:
+ """
+ Export memories.
+
+ Args:
+ conversation_id: Export specific conversation (optional)
+ format: Export format ('json' or 'dict', default: 'json')
+ **filters: Additional filters
+
+ Returns:
+ Exported data (JSON string or dict)
+
+ Example:
+ >>> data = context.export(conversation_id="conv1")
+ >>> data = context.export(format='dict')
+ """
+ all_filters = {**filters}
+ if conversation_id:
+ all_filters["conversation_id"] = conversation_id
+
+ memories = self.list(**all_filters)
+
+ export_data = {
+ "exported_at": datetime.now().isoformat(),
+ "count": len(memories),
+ "memories": memories
+ }
+
+ if format == 'json':
+ import json
+ return json.dumps(export_data, indent=2, default=str)
+ return export_data
+
+ def import_data(self, data: Union[str, Dict[str, Any]], format: str = 'json') -> int:
+ """
+ Import memories.
+
+ Args:
+ data: Data to import (JSON string or dict)
+ format: Data format ('json' or 'dict', default: 'json')
+
+ Returns:
+ Number of memories imported
+
+ Example:
+ >>> imported = context.import_data(json_string)
+ >>> imported = context.import_data(data_dict, format='dict')
+ """
+ if format == 'json':
+ import json
+ if isinstance(data, str):
+ data = json.loads(data)
+
+ if not isinstance(data, dict):
+ raise ValueError("Invalid data format. Expected dict or JSON string.")
+
+ memories = data.get("memories", [])
+ if not memories:
+ return 0
+
+ imported = 0
+ for memory in memories:
+ try:
+ memory_id = self.store(
+ memory.get("content", ""),
+ metadata=memory.get("metadata", {}),
+ conversation_id=memory.get("metadata", {}).get("conversation_id"),
+ user_id=memory.get("metadata", {}).get("user_id"),
+ )
+ if memory_id:
+ imported += 1
+ except Exception as e:
+ self.logger.warning(f"Failed to import memory: {e}")
+
+ return imported
+
+ def backup(self, **filters) -> str:
+ """
+ Create backup (alias for export).
+
+ Args:
+ **filters: Filter criteria
+
+ Returns:
+ JSON string of backup data
+
+ Example:
+ >>> backup_data = context.backup()
+ >>> backup_data = context.backup(conversation_id="conv1")
+ """
+ return self.export(format='json', **filters)
+
+ def restore(self, data: Union[str, Dict[str, Any]], format: str = 'json') -> int:
+ """
+ Restore from backup (alias for import_data).
+
+ Args:
+ data: Backup data (JSON string or dict)
+ format: Data format ('json' or 'dict', default: 'json')
+
+ Returns:
+ Number of memories restored
+
+ Example:
+ >>> restored = context.restore(backup_data)
+ """
+ return self.import_data(data, format=format)
+
+ # Statistics and Analytics
+ def health(self) -> Dict[str, Any]:
+ """
+ Check system health.
+
+ Returns:
+ Health status dict
+
+ Example:
+ >>> health = context.health()
+ >>> print(f"Status: {health['status']}")
+ """
+ stats = self.stats()
+ total = stats.get("total_items", 0)
+
+ health_status = {
+ "status": "healthy" if total >= 0 else "error",
+ "total_memories": total,
+ "vector_store_available": self.vector_store is not None,
+ "knowledge_graph_available": self.knowledge_graph is not None,
+ "retriever_available": self._retriever is not None,
+ "graph_builder_available": self._graph_builder is not None,
+ }
+
+ return health_status
+
+ def usage_stats(self, period: str = 'day') -> Dict[str, Any]:
+ """
+ Get usage statistics.
+
+ Args:
+ period: Time period ('day', 'week', 'month', default: 'day')
+
+ Returns:
+ Usage statistics dict
+
+ Example:
+ >>> usage = context.usage_stats(period='week')
+ """
+ from datetime import datetime, timedelta
+
+ now = datetime.now()
+ if period == 'day':
+ start = now - timedelta(days=1)
+ elif period == 'week':
+ start = now - timedelta(weeks=1)
+ elif period == 'month':
+ start = now - timedelta(days=30)
+ else:
+ start = now - timedelta(days=1)
+
+ stats = self.stats()
+ total = stats.get("total_items", 0)
+
+ # Count recent memories
+ recent_count = 0
+ for memory_id, memory_item in self._memory.memory_items.items():
+ if memory_item.timestamp >= start:
+ recent_count += 1
+
+ return {
+ "period": period,
+ "total_memories": total,
+ "recent_memories": recent_count,
+ "conversations": len(self.list_conversations()),
+ }
+
diff --git a/semantica/context/agent_memory.py b/semantica/context/agent_memory.py
index f7b5c343..a7dc0887 100644
--- a/semantica/context/agent_memory.py
+++ b/semantica/context/agent_memory.py
@@ -588,3 +588,610 @@ class AgentMemory:
"max_size": self.max_memory_size,
"retention_policy": self.retention_policy,
}
+
+ # Basic Operations
+ def exists(self, memory_id: str) -> bool:
+ """
+ Check if memory exists.
+
+ Args:
+ memory_id: Memory ID to check
+
+ Returns:
+ True if exists, False otherwise
+
+ Example:
+ >>> if memory.exists("mem123"):
+ ... print("Memory exists")
+ """
+ return memory_id in self.memory_items
+
+ def count(self, **filters) -> int:
+ """
+ Get count with filters.
+
+ Args:
+ **filters: Filter criteria
+
+ Returns:
+ Count of memories matching filters
+
+ Example:
+ >>> total = memory.count()
+ >>> conv_count = memory.count(conversation_id="conv1")
+ """
+ if not filters:
+ return len(self.memory_items)
+
+ count = 0
+ for memory_id, memory_item in self.memory_items.items():
+ if self._matches_filters(memory_item, filters):
+ count += 1
+ return count
+
+ def get(self, memory_id: str) -> Optional[Dict[str, Any]]:
+ """
+ Get memory by ID.
+
+ Args:
+ memory_id: Memory ID
+
+ Returns:
+ Memory dict or None if not found
+
+ Example:
+ >>> memory = memory.get("mem123")
+ """
+ return self.get_memory(memory_id)
+
+ def update(
+ self,
+ memory_id: str,
+ content: Optional[str] = None,
+ metadata: Optional[Dict[str, Any]] = None,
+ **kwargs
+ ) -> bool:
+ """
+ Update memory.
+
+ Args:
+ memory_id: Memory ID to update
+ content: New content (optional)
+ metadata: New metadata (optional, merged with existing)
+ **kwargs: Additional fields to update
+
+ Returns:
+ True if updated, False if not found
+
+ Example:
+ >>> memory.update("mem123", content="Updated content")
+ """
+ if memory_id not in self.memory_items:
+ return False
+
+ memory_item = self.memory_items[memory_id]
+ current_content = content if content is not None else memory_item.content
+ current_metadata = memory_item.metadata.copy()
+ if metadata:
+ current_metadata.update(metadata)
+
+ # Delete old and create new
+ self.delete_memory(memory_id)
+ new_id = self.store(
+ current_content,
+ metadata=current_metadata,
+ entities=memory_item.entities,
+ relationships=memory_item.relationships,
+ **kwargs
+ )
+
+ return new_id is not None
+
+ def delete(self, memory_id: str) -> bool:
+ """
+ Delete memory (alias for delete_memory).
+
+ Args:
+ memory_id: Memory ID to delete
+
+ Returns:
+ True if deleted, False if not found
+
+ Example:
+ >>> memory.delete("mem123")
+ """
+ return self.delete_memory(memory_id)
+
+ def clear(self, **filters) -> int:
+ """
+ Clear with filters (alias for clear_memory).
+
+ Args:
+ **filters: Filter criteria
+
+ Returns:
+ Number of memories deleted
+
+ Example:
+ >>> deleted = memory.clear(conversation_id="conv1")
+ """
+ return self.clear_memory(**filters)
+
+ # Search Methods
+ def search(self, query: str, **filters) -> List[Dict[str, Any]]:
+ """
+ Simple search (alias for retrieve).
+
+ Args:
+ query: Search query
+ **filters: Additional filters
+
+ Returns:
+ List of memory dicts
+
+ Example:
+ >>> results = memory.search("Python", max_results=10)
+ """
+ return self.retrieve(query, **filters)
+
+ def find_similar(self, content: str, limit: int = 5, **kwargs) -> List[Dict[str, Any]]:
+ """
+ Find similar content.
+
+ Args:
+ content: Content to find similar items for
+ limit: Maximum results (default: 5)
+ **kwargs: Additional options
+
+ Returns:
+ List of similar memory dicts
+
+ Example:
+ >>> similar = memory.find_similar("Python programming", limit=5)
+ """
+ return self.retrieve(content, max_results=limit, **kwargs)
+
+ def find_by_entity(self, entity_id: str, limit: int = 10) -> List[Dict[str, Any]]:
+ """
+ Find by entity.
+
+ Args:
+ entity_id: Entity ID to search for
+ limit: Maximum results (default: 10)
+
+ Returns:
+ List of memory dicts containing the entity
+
+ Example:
+ >>> results = memory.find_by_entity("entity_123")
+ """
+ results = []
+ for memory_id, memory_item in self.memory_items.items():
+ for entity in memory_item.entities:
+ if entity.get("id") == entity_id:
+ mem_dict = self.get_memory(memory_id)
+ if mem_dict:
+ results.append(mem_dict)
+ break
+ if len(results) >= limit:
+ break
+ return results[:limit]
+
+ def find_by_relationship(self, relationship_type: str, limit: int = 10) -> List[Dict[str, Any]]:
+ """
+ Find by relationship.
+
+ Args:
+ relationship_type: Relationship type to search for
+ limit: Maximum results (default: 10)
+
+ Returns:
+ List of memory dicts containing the relationship
+
+ Example:
+ >>> results = memory.find_by_relationship("related_to")
+ """
+ results = []
+ for memory_id, memory_item in self.memory_items.items():
+ for relationship in memory_item.relationships:
+ if relationship.get("type") == relationship_type:
+ mem_dict = self.get_memory(memory_id)
+ if mem_dict:
+ results.append(mem_dict)
+ break
+ if len(results) >= limit:
+ break
+ return results[:limit]
+
+ # List and Filter Methods
+ def list(
+ self,
+ conversation_id: Optional[str] = None,
+ user_id: Optional[str] = None,
+ limit: int = 100,
+ offset: int = 0,
+ **filters
+ ) -> List[Dict[str, Any]]:
+ """
+ List memories.
+
+ Args:
+ conversation_id: Filter by conversation ID
+ user_id: Filter by user ID
+ limit: Maximum items (default: 100)
+ offset: Number of items to skip (default: 0)
+ **filters: Additional filters
+
+ Returns:
+ List of memory dicts
+
+ Example:
+ >>> memories = memory.list(conversation_id="conv1", limit=50)
+ """
+ all_filters = {**filters}
+ if conversation_id:
+ all_filters["conversation_id"] = conversation_id
+ if user_id:
+ all_filters["user_id"] = user_id
+
+ results = []
+ for memory_id in list(self.memory_items.keys())[offset:offset + limit]:
+ memory_item = self.memory_items[memory_id]
+ if not all_filters or self._matches_filters(memory_item, all_filters):
+ # Also check user_id and conversation_id in metadata
+ if user_id and memory_item.metadata.get("user_id") != user_id:
+ continue
+ if conversation_id and memory_item.metadata.get("conversation_id") != conversation_id:
+ continue
+
+ mem_dict = self.get_memory(memory_id)
+ if mem_dict:
+ results.append(mem_dict)
+
+ return results
+
+ def get_by_conversation(self, conversation_id: str, limit: int = 100) -> List[Dict[str, Any]]:
+ """
+ Get conversation memories.
+
+ Args:
+ conversation_id: Conversation ID
+ limit: Maximum items (default: 100)
+
+ Returns:
+ List of memory dicts in conversation
+
+ Example:
+ >>> memories = memory.get_by_conversation("conv1")
+ """
+ return self.get_conversation_history(conversation_id=conversation_id, max_items=limit)
+
+ def get_by_user(self, user_id: str, limit: int = 100) -> List[Dict[str, Any]]:
+ """
+ Get user memories.
+
+ Args:
+ user_id: User ID
+ limit: Maximum items (default: 100)
+
+ Returns:
+ List of memory dicts for user
+
+ Example:
+ >>> memories = memory.get_by_user("user123")
+ """
+ results = []
+ for memory_id, memory_item in self.memory_items.items():
+ if memory_item.metadata.get("user_id") == user_id:
+ mem_dict = self.get_memory(memory_id)
+ if mem_dict:
+ results.append(mem_dict)
+ if len(results) >= limit:
+ break
+ return results
+
+ def get_recent(self, limit: int = 10) -> List[Dict[str, Any]]:
+ """
+ Get recent memories.
+
+ Args:
+ limit: Maximum items (default: 10)
+
+ Returns:
+ List of recent memory dicts
+
+ Example:
+ >>> recent = memory.get_recent(limit=20)
+ """
+ results = []
+ sorted_items = sorted(
+ self.memory_items.items(),
+ key=lambda x: x[1].timestamp,
+ reverse=True
+ )
+ for memory_id, _ in sorted_items[:limit]:
+ mem_dict = self.get_memory(memory_id)
+ if mem_dict:
+ results.append(mem_dict)
+ return results
+
+ def get_by_date(
+ self,
+ start_date: Union[str, datetime],
+ end_date: Union[str, datetime],
+ limit: int = 100
+ ) -> List[Dict[str, Any]]:
+ """
+ Get by date range.
+
+ Args:
+ start_date: Start date (ISO string or datetime)
+ end_date: End date (ISO string or datetime)
+ limit: Maximum items (default: 100)
+
+ Returns:
+ List of memory dicts in date range
+
+ Example:
+ >>> memories = memory.get_by_date("2024-01-01", "2024-12-31")
+ """
+ if isinstance(start_date, str):
+ from dateutil.parser import parse
+ start_date = parse(start_date)
+ if isinstance(end_date, str):
+ from dateutil.parser import parse
+ end_date = parse(end_date)
+
+ results = []
+ for memory_id, memory_item in self.memory_items.items():
+ if start_date <= memory_item.timestamp <= end_date:
+ mem_dict = self.get_memory(memory_id)
+ if mem_dict:
+ results.append(mem_dict)
+ if len(results) >= limit:
+ break
+ return results
+
+ def get_by_type(self, type: str, limit: int = 100) -> List[Dict[str, Any]]:
+ """
+ Get by type.
+
+ Args:
+ type: Memory type
+ limit: Maximum items (default: 100)
+
+ Returns:
+ List of memory dicts of specified type
+
+ Example:
+ >>> memories = memory.get_by_type("conversation")
+ """
+ results = []
+ for memory_id, memory_item in self.memory_items.items():
+ if memory_item.metadata.get("type") == type:
+ mem_dict = self.get_memory(memory_id)
+ if mem_dict:
+ results.append(mem_dict)
+ if len(results) >= limit:
+ break
+ return results
+
+ # Batch Operations
+ def batch_store(self, items: List[Union[str, Dict[str, Any]]]) -> List[str]:
+ """
+ Batch store.
+
+ Args:
+ items: List of items to store
+
+ Returns:
+ List of memory IDs
+
+ Example:
+ >>> ids = memory.batch_store(["Item 1", "Item 2"])
+ """
+ memory_ids = []
+ for item in items:
+ if isinstance(item, str):
+ memory_id = self.store(item)
+ memory_ids.append(memory_id)
+ elif isinstance(item, dict):
+ content = item.get("content", "")
+ if content:
+ memory_id = self.store(
+ content,
+ metadata=item.get("metadata"),
+ **{k: v for k, v in item.items() if k not in ["content", "metadata"]}
+ )
+ memory_ids.append(memory_id)
+ return memory_ids
+
+ def batch_delete(self, memory_ids: List[str]) -> int:
+ """
+ Batch delete.
+
+ Args:
+ memory_ids: List of memory IDs to delete
+
+ Returns:
+ Number of memories deleted
+
+ Example:
+ >>> deleted = memory.batch_delete(["mem1", "mem2"])
+ """
+ deleted = 0
+ for memory_id in memory_ids:
+ if self.delete_memory(memory_id):
+ deleted += 1
+ return deleted
+
+ def batch_update(self, updates: List[Dict[str, Any]]) -> int:
+ """
+ Batch update.
+
+ Args:
+ updates: List of update dicts with 'memory_id' and fields
+
+ Returns:
+ Number of memories updated
+
+ Example:
+ >>> updated = memory.batch_update([{"memory_id": "mem1", "content": "New"}])
+ """
+ updated = 0
+ for update in updates:
+ memory_id = update.get("memory_id")
+ if memory_id and self.update(memory_id, **{k: v for k, v in update.items() if k != "memory_id"}):
+ updated += 1
+ return updated
+
+ # Export/Import
+ def export(
+ self,
+ conversation_id: Optional[str] = None,
+ format: str = 'json',
+ **filters
+ ) -> Union[str, Dict[str, Any]]:
+ """
+ Export memories.
+
+ Args:
+ conversation_id: Export specific conversation (optional)
+ format: Export format ('json' or 'dict', default: 'json')
+ **filters: Additional filters
+
+ Returns:
+ Exported data
+
+ Example:
+ >>> data = memory.export(conversation_id="conv1")
+ """
+ all_filters = {**filters}
+ if conversation_id:
+ all_filters["conversation_id"] = conversation_id
+
+ memories = []
+ for memory_id, memory_item in self.memory_items.items():
+ if not all_filters or self._matches_filters(memory_item, all_filters):
+ mem_dict = self.get_memory(memory_id)
+ if mem_dict:
+ memories.append(mem_dict)
+
+ export_data = {
+ "exported_at": datetime.now().isoformat(),
+ "count": len(memories),
+ "memories": memories
+ }
+
+ if format == 'json':
+ import json
+ return json.dumps(export_data, indent=2, default=str)
+ return export_data
+
+ def import_data(self, data: Union[str, Dict[str, Any]], format: str = 'json') -> int:
+ """
+ Import memories.
+
+ Args:
+ data: Data to import
+ format: Data format ('json' or 'dict', default: 'json')
+
+ Returns:
+ Number of memories imported
+
+ Example:
+ >>> imported = memory.import_data(json_string)
+ """
+ if format == 'json':
+ import json
+ if isinstance(data, str):
+ data = json.loads(data)
+
+ if not isinstance(data, dict):
+ raise ValueError("Invalid data format")
+
+ memories = data.get("memories", [])
+ if not memories:
+ return 0
+
+ imported = 0
+ for memory in memories:
+ try:
+ memory_id = self.store(
+ memory.get("content", ""),
+ metadata=memory.get("metadata", {}),
+ )
+ if memory_id:
+ imported += 1
+ except Exception as e:
+ self.logger.warning(f"Failed to import memory: {e}")
+
+ return imported
+
+ # Statistics
+ def stats(self, **filters) -> Dict[str, Any]:
+ """
+ Get statistics (enhance existing).
+
+ Args:
+ **filters: Optional filters
+
+ Returns:
+ Statistics dict
+
+ Example:
+ >>> stats = memory.stats()
+ >>> conv_stats = memory.stats(conversation_id="conv1")
+ """
+ base_stats = self.get_statistics()
+ if filters:
+ base_stats["filtered_count"] = self.count(**filters)
+ return base_stats
+
+ def count_by_type(self) -> Dict[str, int]:
+ """
+ Count by type.
+
+ Returns:
+ Dict mapping type to count
+
+ Example:
+ >>> counts = memory.count_by_type()
+ """
+ counts = {}
+ for memory_item in self.memory_items.values():
+ mem_type = memory_item.metadata.get("type", "unknown")
+ counts[mem_type] = counts.get(mem_type, 0) + 1
+ return counts
+
+ def count_by_user(self) -> Dict[str, int]:
+ """
+ Count by user.
+
+ Returns:
+ Dict mapping user_id to count
+
+ Example:
+ >>> counts = memory.count_by_user()
+ """
+ counts = {}
+ for memory_item in self.memory_items.values():
+ user_id = memory_item.metadata.get("user_id", "unknown")
+ counts[user_id] = counts.get(user_id, 0) + 1
+ return counts
+
+ def count_by_conversation(self) -> Dict[str, int]:
+ """
+ Count by conversation.
+
+ Returns:
+ Dict mapping conversation_id to count
+
+ Example:
+ >>> counts = memory.count_by_conversation()
+ """
+ counts = {}
+ for memory_item in self.memory_items.values():
+ conv_id = memory_item.metadata.get("conversation_id", "unknown")
+ counts[conv_id] = counts.get(conv_id, 0) + 1
+ return counts
\ No newline at end of file
diff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.py
index 142bebe6..08fd82e3 100644
--- a/semantica/context/context_graph.py
+++ b/semantica/context/context_graph.py
@@ -642,3 +642,494 @@ class ContextGraphBuilder:
)
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),
+ }
+ }
+
+ 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
diff --git a/semantica/context/context_retriever.py b/semantica/context/context_retriever.py
index 40aeef4b..e6184fc0 100644
--- a/semantica/context/context_retriever.py
+++ b/semantica/context/context_retriever.py
@@ -58,8 +58,9 @@ Author: Semantica Contributors
License: MIT
"""
+from datetime import datetime
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, Union
from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
@@ -438,3 +439,424 @@ class ContextRetriever:
current_level = next_level
return related
+
+ # Search Methods
+ def search(self, query: str, **options) -> List[RetrievedContext]:
+ """
+ Simple search (alias for retrieve).
+
+ Args:
+ query: Search query
+ **options: Additional options
+
+ Returns:
+ List of RetrievedContext objects
+
+ Example:
+ >>> results = retriever.search("Python", max_results=10)
+ """
+ return self.retrieve(query, **options)
+
+ def vector_search(self, query: str, **options) -> List[RetrievedContext]:
+ """
+ Vector-only search.
+
+ Args:
+ query: Search query
+ **options: Additional options
+
+ Returns:
+ List of RetrievedContext objects from vector store
+
+ Example:
+ >>> results = retriever.vector_search("Python")
+ """
+ # Temporarily disable graph and memory
+ original_graph = self.knowledge_graph
+ original_memory = self.memory_store
+
+ self.knowledge_graph = None
+ self.memory_store = None
+
+ try:
+ results = self.retrieve(query, use_graph_expansion=False, **options)
+ finally:
+ self.knowledge_graph = original_graph
+ self.memory_store = original_memory
+
+ return results
+
+ def graph_search(self, query: str, **options) -> List[RetrievedContext]:
+ """
+ Graph-only search.
+
+ Args:
+ query: Search query
+ **options: Additional options
+
+ Returns:
+ List of RetrievedContext objects from graph
+
+ Example:
+ >>> results = retriever.graph_search("Python")
+ """
+ if not self.knowledge_graph:
+ return []
+
+ # Temporarily disable vector and memory
+ original_vector = self.vector_store
+ original_memory = self.memory_store
+
+ self.vector_store = None
+ self.memory_store = None
+
+ try:
+ results = self.retrieve(query, use_graph_expansion=True, **options)
+ finally:
+ self.vector_store = original_vector
+ self.memory_store = original_memory
+
+ return results
+
+ def memory_search(self, query: str, **options) -> List[RetrievedContext]:
+ """
+ Memory-only search.
+
+ Args:
+ query: Search query
+ **options: Additional options
+
+ Returns:
+ List of RetrievedContext objects from memory
+
+ Example:
+ >>> results = retriever.memory_search("Python")
+ """
+ if not self.memory_store:
+ return []
+
+ # Use memory store's retrieve method
+ memory_results = self.memory_store.retrieve(query, **options)
+
+ # Convert to RetrievedContext
+ results = []
+ for mem in memory_results:
+ results.append(
+ RetrievedContext(
+ content=mem.get("content", ""),
+ score=mem.get("score", 0.0),
+ source="memory",
+ metadata=mem.get("metadata", {}),
+ )
+ )
+
+ return results
+
+ def hybrid_search(self, query: str, **options) -> List[RetrievedContext]:
+ """
+ Hybrid search (all sources).
+
+ Args:
+ query: Search query
+ **options: Additional options
+
+ Returns:
+ List of RetrievedContext objects from all sources
+
+ Example:
+ >>> results = retriever.hybrid_search("Python")
+ """
+ return self.retrieve(query, **options)
+
+ # Advanced Retrieval
+ def find_similar(self, content: str, limit: int = 5, **options) -> List[RetrievedContext]:
+ """
+ Find similar content.
+
+ Args:
+ content: Content to find similar items for
+ limit: Maximum results (default: 5)
+ **options: Additional options
+
+ Returns:
+ List of similar RetrievedContext objects
+
+ Example:
+ >>> similar = retriever.find_similar("Python programming", limit=5)
+ """
+ return self.retrieve(content, max_results=limit, **options)
+
+ def get_context(self, query: str, max_results: int = 5, **options) -> List[RetrievedContext]:
+ """
+ Get context for query.
+
+ Args:
+ query: Query string
+ max_results: Maximum results (default: 5)
+ **options: Additional options
+
+ Returns:
+ List of RetrievedContext objects
+
+ Example:
+ >>> context_data = retriever.get_context("Python", max_results=10)
+ """
+ return self.retrieve(query, max_results=max_results, **options)
+
+ def expand_query(self, query: str, max_hops: int = 2, **options) -> List[RetrievedContext]:
+ """
+ Expand query with graph.
+
+ Args:
+ query: Query string
+ max_hops: Maximum expansion hops (default: 2)
+ **options: Additional options
+
+ Returns:
+ List of expanded RetrievedContext objects
+
+ Example:
+ >>> expanded = retriever.expand_query("Python", max_hops=3)
+ """
+ return self.retrieve(
+ query,
+ use_graph_expansion=True,
+ max_hops=max_hops,
+ **options
+ )
+
+ def get_related(self, entity_id: str, max_hops: int = 2) -> List[Dict[str, Any]]:
+ """
+ Get related entities.
+
+ Args:
+ entity_id: Entity ID
+ max_hops: Maximum hops (default: 2)
+
+ Returns:
+ List of related entity dicts
+
+ Example:
+ >>> related = retriever.get_related("entity_123", max_hops=2)
+ """
+ if not self.knowledge_graph:
+ return []
+
+ return self._get_related_entities(entity_id, max_hops=max_hops)
+
+ def get_path(self, source_id: str, target_id: str, max_hops: int = 5) -> List[Dict[str, Any]]:
+ """
+ Get path between entities.
+
+ Args:
+ source_id: Source entity ID
+ target_id: Target entity ID
+ max_hops: Maximum hops (default: 5)
+
+ Returns:
+ List of path nodes/edges
+
+ Example:
+ >>> path = retriever.get_path("entity_1", "entity_2", max_hops=5)
+ """
+ if not self.knowledge_graph:
+ return []
+
+ # Simple BFS path finding
+ from collections import deque
+
+ 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
+ nodes = self.knowledge_graph.get("nodes", [])
+ path_info = []
+ for node_id in path:
+ for node in nodes:
+ if node.get("id") == node_id:
+ path_info.append({
+ "id": node_id,
+ "content": node.get("content", ""),
+ "type": node.get("type", ""),
+ })
+ break
+ return path_info
+
+ # Get neighbors
+ edges = self.knowledge_graph.get("edges", [])
+ for edge in edges:
+ neighbor_id = None
+ if edge.get("source") == current_id:
+ neighbor_id = edge.get("target")
+ elif edge.get("target") == current_id:
+ neighbor_id = edge.get("source")
+
+ if neighbor_id and neighbor_id not in visited:
+ visited.add(neighbor_id)
+ queue.append((neighbor_id, path + [neighbor_id]))
+
+ return []
+
+ # Filter Methods
+ def filter_by_entity(self, entity_id: str, query: str, **options) -> List[RetrievedContext]:
+ """
+ Filter by entity.
+
+ Args:
+ entity_id: Entity ID to filter by
+ query: Search query
+ **options: Additional options
+
+ Returns:
+ Filtered RetrievedContext objects
+
+ Example:
+ >>> results = retriever.filter_by_entity("entity_123", "Python")
+ """
+ results = self.retrieve(query, **options)
+ filtered = []
+ for result in results:
+ # Check if entity is in related entities
+ for entity in result.related_entities:
+ if entity.get("id") == entity_id:
+ filtered.append(result)
+ break
+ return filtered
+
+ def filter_by_type(self, type: str, query: str, **options) -> List[RetrievedContext]:
+ """
+ Filter by type.
+
+ Args:
+ type: Node/entity type to filter by
+ query: Search query
+ **options: Additional options
+
+ Returns:
+ Filtered RetrievedContext objects
+
+ Example:
+ >>> results = retriever.filter_by_type("PROGRAMMING_LANGUAGE", "Python")
+ """
+ results = self.retrieve(query, **options)
+ filtered = []
+ for result in results:
+ if result.metadata.get("node_type") == type:
+ filtered.append(result)
+ return filtered
+
+ def filter_by_date(
+ self,
+ start_date: Union[str, datetime],
+ end_date: Union[str, datetime],
+ query: str,
+ **options
+ ) -> List[RetrievedContext]:
+ """
+ Filter by date.
+
+ Args:
+ start_date: Start date
+ end_date: End date
+ query: Search query
+ **options: Additional options
+
+ Returns:
+ Filtered RetrievedContext objects
+
+ Example:
+ >>> results = retriever.filter_by_date("2024-01-01", "2024-12-31", "Python")
+ """
+ if isinstance(start_date, str):
+ from dateutil.parser import parse
+ start_date = parse(start_date)
+ if isinstance(end_date, str):
+ from dateutil.parser import parse
+ end_date = parse(end_date)
+
+ results = self.retrieve(query, **options)
+ filtered = []
+ for result in results:
+ result_date = result.metadata.get("timestamp")
+ if result_date:
+ if isinstance(result_date, str):
+ from dateutil.parser import parse
+ result_date = parse(result_date)
+ if start_date <= result_date <= end_date:
+ filtered.append(result)
+ return filtered
+
+ def filter_by_score(
+ self,
+ min_score: float,
+ query: str,
+ **options
+ ) -> List[RetrievedContext]:
+ """
+ Filter by score.
+
+ Args:
+ min_score: Minimum score threshold
+ query: Search query
+ **options: Additional options
+
+ Returns:
+ Filtered RetrievedContext objects
+
+ Example:
+ >>> results = retriever.filter_by_score(0.7, "Python")
+ """
+ results = self.retrieve(query, min_relevance_score=min_score, **options)
+ return [r for r in results if r.score >= min_score]
+
+ # Batch Operations
+ def batch_search(self, queries: List[str], **options) -> Dict[str, List[RetrievedContext]]:
+ """
+ Search multiple queries.
+
+ Args:
+ queries: List of queries
+ **options: Additional options
+
+ Returns:
+ Dict mapping query to results
+
+ Example:
+ >>> results = retriever.batch_search(["Python", "Java", "C++"])
+ """
+ results = {}
+ for query in queries:
+ results[query] = self.retrieve(query, **options)
+ return results
+
+ def batch_get_context(
+ self,
+ queries: List[str],
+ max_results: int = 5,
+ **options
+ ) -> Dict[str, List[RetrievedContext]]:
+ """
+ Get context for multiple queries.
+
+ Args:
+ queries: List of queries
+ max_results: Maximum results per query (default: 5)
+ **options: Additional options
+
+ Returns:
+ Dict mapping query to context results
+
+ Example:
+ >>> contexts = retriever.batch_get_context(["Python", "Java"], max_results=5)
+ """
+ results = {}
+ for query in queries:
+ results[query] = self.get_context(query, max_results=max_results, **options)
+ return results
\ No newline at end of file
diff --git a/semantica/context/context_usage.md b/semantica/context/context_usage.md
index 7efd0d9a..0e3d2cb3 100644
--- a/semantica/context/context_usage.md
+++ b/semantica/context/context_usage.md
@@ -4,46 +4,337 @@ This guide demonstrates how to use the context module for building context graph
## Table of Contents
-1. [Basic Usage](#basic-usage)
-2. [Context Graph Construction](#context-graph-construction)
-3. [Agent Memory Management](#agent-memory-management)
-4. [Context Retrieval](#context-retrieval)
-5. [Entity Linking](#entity-linking)
-6. [Using Methods](#using-methods)
-7. [Using Registry](#using-registry)
-8. [Configuration](#configuration)
-9. [Advanced Examples](#advanced-examples)
+1. [High-Level Interface (Quick Start)](#high-level-interface-quick-start)
+2. [Basic Usage](#basic-usage)
+3. [Context Graph Construction](#context-graph-construction)
+4. [Agent Memory Management](#agent-memory-management)
+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)
-## Basic Usage
+## 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.
-### Using the Convenience Function
+### Simple RAG
```python
-from semantica.context import build_context
+from semantica.context import AgentContext
-# Sample entities and relationships
-entities = [
- {"id": "e1", "text": "Python", "type": "PROGRAMMING_LANGUAGE"},
- {"id": "e2", "text": "Machine Learning", "type": "CONCEPT"},
-]
-relationships = [
- {"source_id": "e1", "target_id": "e2", "type": "used_for"},
+# Initialize with vector store
+context = AgentContext(vector_store=vs)
+
+# Store a memory
+memory_id = context.store("User likes Python programming", conversation_id="conv1")
+
+# Retrieve context
+results = context.retrieve("Python programming", max_results=5)
+
+for result in results:
+ print(f"Content: {result['content']}")
+ print(f"Score: {result['score']:.2f}")
+```
+
+### GraphRAG
+
+```python
+# Initialize with vector store and knowledge graph
+context = AgentContext(vector_store=vs, knowledge_graph=kg)
+
+# Store documents (auto-builds graph)
+documents = [
+ "Python is a programming language used for machine learning",
+ "TensorFlow and PyTorch are popular ML frameworks",
+ "Machine learning involves training models on data"
]
-# Build context graph and optionally store memories
-result = build_context(
+stats = context.store(
+ documents,
+ extract_entities=True, # Extract entities from documents
+ extract_relationships=True, # Extract relationships
+ link_entities=True # Link entities across documents
+)
+
+print(f"Stored {stats['stored_count']} documents")
+print(f"Built graph with {stats['graph_nodes']} nodes and {stats['graph_edges']} edges")
+
+# Retrieve with graph context (auto-detects GraphRAG)
+results = context.retrieve(
+ "Python machine learning",
+ use_graph=None, # Auto-detect (uses graph since knowledge_graph available)
+ include_entities=True, # Include related entities
+ expand_graph=True # Use graph expansion
+)
+
+for result in results:
+ print(f"Content: {result['content']}")
+ print(f"Score: {result['score']:.2f}")
+ print(f"Related entities: {len(result.get('related_entities', []))}")
+```
+
+### Agent Memory Management
+
+```python
+context = AgentContext(vector_store=vs, retention_days=30)
+
+# 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(
+ "conv1",
+ reverse=True, # Most recent first
+ include_metadata=True # Include full metadata
+)
+
+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,
- vector_store=vs, # Optional vector store
- knowledge_graph=kg, # Optional knowledge graph
- graph_method="entities_relationships",
- store_initial_memories=False
+ 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")
-print(f"Graph has {result['graph']['statistics']['node_count']} nodes")
-print(f"Graph has {result['graph']['statistics']['edge_count']} edges")
+# 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
```python
@@ -144,11 +435,42 @@ print(f"Neighbors: {neighbors}")
results = builder.query(node_type="entity", confidence=0.8)
```
+### Additional Graph Construction Methods
+
+```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()
+```
+
### Using Graph Construction Methods
```python
from semantica.context.methods import build_context_graph
-
# Build from entities and relationships
graph = build_context_graph(
entities=entities,
@@ -278,11 +600,56 @@ 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",
@@ -335,7 +702,6 @@ for result in results:
```python
from semantica.context.methods import retrieve_context
-
# Vector-based retrieval only
results = retrieve_context(
"Python programming",
@@ -396,6 +762,38 @@ for result in results:
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)
+```
+
## Entity Linking
### Basic Entity Linking
@@ -453,6 +851,11 @@ linker.link_entities(
links = linker.get_entity_links("entity_1")
for link in links:
print(f"{link.source_entity_id} --{link.link_type}--> {link.target_entity_id}")
+
+# Get entity URI
+uri = linker.get_entity_uri("entity_1")
+if uri:
+ print(f"Entity URI: {uri}")
```
### Finding Similar Entities
@@ -494,11 +897,38 @@ 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,
@@ -561,26 +991,25 @@ if custom_method:
### Registering Custom Methods
```python
-from semantica.context.registry import method_registry
-
+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
-method_registry.register("graph", "custom_builder", custom_graph_builder)
+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 = method_registry.list_all("graph")
+methods = registry.method_registry.list_all("graph")
print(f"Registered graph methods: {methods}")
# Unregister method
-method_registry.unregister("graph", "custom_builder")
+registry.method_registry.unregister("graph", "custom_builder")
```
## Configuration
@@ -588,26 +1017,26 @@ method_registry.unregister("graph", "custom_builder")
### Using Configuration
```python
-from semantica.context.config import context_config
+from semantica.context import config
# Get configuration
-retention = context_config.get("retention_policy", default="unlimited")
-max_size = context_config.get("max_memory_size", default=10000)
+retention = config.context_config.get("retention_policy", default="unlimited")
+max_size = config.context_config.get("max_memory_size", default=10000)
# Set configuration
-context_config.set("retention_policy", "30_days")
-context_config.set("max_memory_size", 5000)
+config.context_config.set("retention_policy", "30_days")
+config.context_config.set("max_memory_size", 5000)
# Method-specific configuration
-context_config.set_method_config("graph", {
+config.context_config.set_method_config("graph", {
"extract_entities": True,
"extract_relationships": True
})
-method_config = context_config.get_method_config("graph")
+method_config = config.context_config.get_method_config("graph")
# Get all configurations
-all_configs = context_config.get_all()
+all_configs = config.context_config.get_all()
```
### Environment Variables
@@ -637,10 +1066,10 @@ context_methods:
```
```python
-from semantica.context.config import ContextConfig
+from semantica.context import config
# Load from config file
-config = ContextConfig(config_file="context_config.yaml")
+context_config = config.ContextConfig(config_file="context_config.yaml")
```
## Advanced Examples
@@ -649,23 +1078,15 @@ config = ContextConfig(config_file="context_config.yaml")
```python
from semantica.context import (
- build_context,
AgentMemory,
ContextRetriever,
- EntityLinker
+ EntityLinker,
+ ContextGraphBuilder
)
# Step 1: Build context graph
-result = build_context(
- entities=entities,
- relationships=relationships,
- vector_store=vs,
- knowledge_graph=kg,
- store_initial_memories=True
-)
-
-graph = result['graph']
-memory_ids = result['memory_ids']
+builder = ContextGraphBuilder()
+graph = builder.build_from_entities_and_relationships(entities, relationships)
# Step 2: Initialize memory
memory = AgentMemory(vector_store=vs, knowledge_graph=kg)
diff --git a/semantica/context/entity_linker.py b/semantica/context/entity_linker.py
index 7ba50c43..e5865224 100644
--- a/semantica/context/entity_linker.py
+++ b/semantica/context/entity_linker.py
@@ -522,3 +522,343 @@ class EntityLinker:
)
return web
+
+ # Linking Methods
+ def link_text(self, text: str, entities: Optional[List[EntityDict]] = None) -> List[LinkedEntity]:
+ """
+ Link entities in text.
+
+ Args:
+ text: Text containing entities
+ entities: List of entities to link (optional)
+
+ Returns:
+ List of LinkedEntity objects
+
+ Example:
+ >>> linked = linker.link_text("Python is used for ML", entities=[...])
+ """
+ return self.link(text, entities=entities or [])
+
+ def link_batch(self, entities: List[EntityDict]) -> List[LinkedEntity]:
+ """
+ Link multiple entities.
+
+ Args:
+ entities: List of entities to link
+
+ Returns:
+ List of LinkedEntity objects
+
+ Example:
+ >>> linked = linker.link_batch(entities)
+ """
+ linked_results = []
+ for entity in entities:
+ uri = self.assign_uri(
+ entity.get("id", ""),
+ entity.get("text"),
+ entity.get("type")
+ )
+
+ # Find similar entities
+ similar = self.find_similar_entities(
+ entity.get("text", ""),
+ entity.get("type", ""),
+ threshold=self.similarity_threshold
+ )
+
+ linked_entities = []
+ for similar_id, similarity in similar:
+ linked_entities.append(
+ EntityLink(
+ source_entity_id=entity.get("id", ""),
+ target_entity_id=similar_id,
+ link_type="similar_to",
+ confidence=similarity
+ )
+ )
+
+ linked_results.append(
+ LinkedEntity(
+ entity_id=entity.get("id", ""),
+ uri=uri,
+ text=entity.get("text", ""),
+ type=entity.get("type", ""),
+ linked_entities=linked_entities,
+ confidence=1.0
+ )
+ )
+
+ return linked_results
+
+ # Search Methods
+ def find_similar(self, entity: Union[str, EntityDict], threshold: float = 0.8) -> List[Tuple[str, float]]:
+ """
+ Find similar entities.
+
+ Args:
+ entity: Entity text or EntityDict
+ threshold: Similarity threshold (default: 0.8)
+
+ Returns:
+ List of (entity_id, similarity) tuples
+
+ Example:
+ >>> similar = linker.find_similar("Python", threshold=0.8)
+ """
+ if isinstance(entity, dict):
+ text = entity.get("text", "")
+ entity_type = entity.get("type", "")
+ else:
+ text = entity
+ entity_type = ""
+
+ return self.find_similar_entities(text, entity_type, threshold=threshold)
+
+ def find_by_text(self, text: str, threshold: float = 0.8) -> List[Dict[str, Any]]:
+ """
+ Find by text.
+
+ Args:
+ text: Text to search for
+ threshold: Similarity threshold (default: 0.8)
+
+ Returns:
+ List of matching entity dicts
+
+ Example:
+ >>> entities = linker.find_by_text("Python", threshold=0.8)
+ """
+ results = []
+ for entity_id, uri in self.entity_registry.items():
+ # Get entity text from knowledge graph or registry
+ if self.knowledge_graph:
+ nodes = self.knowledge_graph.get("nodes", [])
+ for node in nodes:
+ if node.get("id") == entity_id:
+ similarity = self._calculate_similarity(text, node.get("content", ""))
+ if similarity >= threshold:
+ results.append({
+ "entity_id": entity_id,
+ "uri": uri,
+ "text": node.get("content", ""),
+ "type": node.get("type", ""),
+ "similarity": similarity,
+ })
+ break
+ return sorted(results, key=lambda x: x.get("similarity", 0), reverse=True)
+
+ def find_by_type(self, type: str, limit: int = 10) -> List[Dict[str, Any]]:
+ """
+ Find by type.
+
+ Args:
+ type: Entity type
+ limit: Maximum results (default: 10)
+
+ Returns:
+ List of entity dicts of specified type
+
+ Example:
+ >>> entities = linker.find_by_type("PROGRAMMING_LANGUAGE", limit=10)
+ """
+ results = []
+ if self.knowledge_graph:
+ nodes = self.knowledge_graph.get("nodes", [])
+ for node in nodes:
+ if node.get("type") == type:
+ entity_id = node.get("id", "")
+ uri = self.entity_registry.get(entity_id, "")
+ results.append({
+ "entity_id": entity_id,
+ "uri": uri,
+ "text": node.get("content", ""),
+ "type": type,
+ })
+ if len(results) >= limit:
+ break
+ return results
+
+ def find_related(self, entity_id: str, max_hops: int = 2) -> List[Dict[str, Any]]:
+ """
+ Find related entities.
+
+ Args:
+ entity_id: Entity ID
+ max_hops: Maximum hops (default: 2)
+
+ Returns:
+ List of related entity dicts
+
+ Example:
+ >>> related = linker.find_related("entity_123", max_hops=2)
+ """
+ related = []
+ visited = {entity_id}
+ current_level = {entity_id}
+
+ for hop in range(max_hops):
+ next_level = set()
+ for current_id in current_level:
+ links = self.entity_links.get(current_id, [])
+ for link in links:
+ target_id = link.target_entity_id
+ if target_id not in visited:
+ visited.add(target_id)
+ next_level.add(target_id)
+
+ # Get entity info
+ uri = self.entity_registry.get(target_id, "")
+ if self.knowledge_graph:
+ nodes = self.knowledge_graph.get("nodes", [])
+ for node in nodes:
+ if node.get("id") == target_id:
+ related.append({
+ "entity_id": target_id,
+ "uri": uri,
+ "text": node.get("content", ""),
+ "type": node.get("type", ""),
+ "link_type": link.link_type,
+ "confidence": link.confidence,
+ "hop": hop + 1,
+ })
+ break
+
+ current_level = next_level
+
+ return related
+
+ # URI Methods
+ def get_uri(self, entity_id: str) -> Optional[str]:
+ """
+ Get URI for entity.
+
+ Args:
+ entity_id: Entity ID
+
+ Returns:
+ URI or None if not found
+
+ Example:
+ >>> uri = linker.get_uri("entity_123")
+ """
+ return self.entity_registry.get(entity_id)
+
+ def get_all_uris(self) -> Dict[str, str]:
+ """
+ Get all URIs.
+
+ Returns:
+ Dict mapping entity_id to URI
+
+ Example:
+ >>> uris = linker.get_all_uris()
+ """
+ return self.entity_registry.copy()
+
+ def resolve_uri(self, uri: str) -> Optional[Dict[str, Any]]:
+ """
+ Resolve URI to entity.
+
+ Args:
+ uri: URI to resolve
+
+ Returns:
+ Entity dict or None if not found
+
+ Example:
+ >>> entity = linker.resolve_uri("https://semantica.dev/entity/python")
+ """
+ # Find entity_id by URI
+ for entity_id, entity_uri in self.entity_registry.items():
+ if entity_uri == uri:
+ # Get entity info
+ if self.knowledge_graph:
+ nodes = self.knowledge_graph.get("nodes", [])
+ for node in nodes:
+ if node.get("id") == entity_id:
+ return {
+ "entity_id": entity_id,
+ "uri": uri,
+ "text": node.get("content", ""),
+ "type": node.get("type", ""),
+ }
+ return {
+ "entity_id": entity_id,
+ "uri": uri,
+ }
+ return None
+
+ # Statistics
+ def link_count(self, entity_id: str) -> int:
+ """
+ Get link count for entity.
+
+ Args:
+ entity_id: Entity ID
+
+ Returns:
+ Number of links for entity
+
+ Example:
+ >>> count = linker.link_count("entity_123")
+ """
+ return len(self.entity_links.get(entity_id, []))
+
+ def stats(self) -> Dict[str, Any]:
+ """
+ Get statistics.
+
+ Returns:
+ Statistics dict
+
+ Example:
+ >>> stats = linker.stats()
+ """
+ web = self.build_entity_web()
+ return {
+ "total_entities": web["statistics"]["total_entities"],
+ "total_links": web["statistics"]["total_links"],
+ "average_links_per_entity": (
+ web["statistics"]["total_links"] / web["statistics"]["total_entities"]
+ if web["statistics"]["total_entities"] > 0 else 0
+ ),
+ }
+
+ def most_linked(self, limit: int = 10) -> List[Dict[str, Any]]:
+ """
+ Get most linked entities.
+
+ Args:
+ limit: Maximum results (default: 10)
+
+ Returns:
+ List of entity dicts sorted by link count
+
+ Example:
+ >>> top = linker.most_linked(limit=10)
+ """
+ entity_link_counts = []
+ for entity_id, links in self.entity_links.items():
+ uri = self.entity_registry.get(entity_id, "")
+ entity_link_counts.append({
+ "entity_id": entity_id,
+ "uri": uri,
+ "link_count": len(links),
+ })
+
+ # Sort by link count
+ entity_link_counts.sort(key=lambda x: x["link_count"], reverse=True)
+
+ # Add entity text if available
+ if self.knowledge_graph:
+ nodes = self.knowledge_graph.get("nodes", [])
+ node_map = {node.get("id"): node for node in nodes}
+ for item in entity_link_counts:
+ node = node_map.get(item["entity_id"])
+ if node:
+ item["text"] = node.get("content", "")
+ item["type"] = node.get("type", "")
+
+ return entity_link_counts[:limit]
\ No newline at end of file
diff --git a/semantica/context/methods.py b/semantica/context/methods.py
index 34f3e069..401a4681 100644
--- a/semantica/context/methods.py
+++ b/semantica/context/methods.py
@@ -190,8 +190,8 @@ def build_context_graph(
raise ProcessingError(f"Unknown graph construction method: {method}")
except Exception as e:
- logger.error(f"Failed to build context graph: {e}")
- raise
+ logger.error(f"Failed to build context graph: {e}", exc_info=True)
+ raise ProcessingError(f"Context graph construction failed: {e}") from e
def store_memory(
@@ -255,8 +255,8 @@ def store_memory(
)
except Exception as e:
- logger.error(f"Failed to store memory: {e}")
- raise
+ logger.error(f"Failed to store memory: {e}", exc_info=True)
+ raise ProcessingError(f"Memory storage failed: {e}") from e
def retrieve_context(
@@ -333,8 +333,8 @@ def retrieve_context(
return retriever.retrieve(query, max_results=max_results, **kwargs)
except Exception as e:
- logger.error(f"Failed to retrieve context: {e}")
- raise
+ logger.error(f"Failed to retrieve context: {e}", exc_info=True)
+ raise ProcessingError(f"Context retrieval failed: {e}") from e
def link_entities(
@@ -413,8 +413,8 @@ def link_entities(
)
except Exception as e:
- logger.error(f"Failed to link entities: {e}")
- raise
+ logger.error(f"Failed to link entities: {e}", exc_info=True)
+ raise ProcessingError(f"Entity linking failed: {e}") from e
def get_context_method(task: str, name: str) -> Optional[Callable]: