### Development Setup and Testing Source: https://github.com/harishsg993010/hawkinsdb/blob/main/README.md Provides commands for cloning the HawkinsDB repository, installing development dependencies, and running tests. This setup is for developers contributing to the project. ```bash git clone https://github.com/your-username/hawkinsdb.git cd hawkinsdb pip install -e ".[dev]" pytest tests/ ``` -------------------------------- ### Install HawkinsDB Source: https://github.com/harishsg993010/hawkinsdb/blob/main/README.md Installs the HawkinsDB package. Basic installation includes core features, while `[all]` installs all available features. Specific features like ConceptNet tools can also be installed separately. ```bash pip install hawkinsdb pip install hawkinsdb[all] pip install hawkinsdb[conceptnet] ``` -------------------------------- ### Quick Start: Initialize and Store Data Source: https://github.com/harishsg993010/hawkinsdb/blob/main/README.md Demonstrates initializing HawkinsDB and an LLMInterface, then storing entity data with properties and relationships. This example shows how to add structured knowledge to the memory layer. ```python from hawkinsdb import HawkinsDB, LLMInterface db = HawkinsDB() llm = LLMInterface(db) db.add_entity({ "column": "Semantic", "name": "Coffee Cup", "properties": { "type": "Container", "material": "Ceramic", "capacity": "350ml" }, "relationships": { "used_for": ["Drinking Coffee", "Hot Beverages"], "found_in": ["Kitchen", "Coffee Shop"] } }) response = llm.query("What can you tell me about the coffee cup?") print(response) ``` -------------------------------- ### Relationship Discovery: IsA Relationships Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Example of discovering 'IsA' relationships for an entity. A 'Laptop' entity is added, and then `enrich_relationships` is used to find and add its 'IsA' connections. ```python # Example of IsA relationship discovery computer_data = { "name": "Laptop", "column": "Semantic", "properties": { "type": "Device", "manufacturer": "Generic" } } db.add_entity(computer_data) enricher.enrich_relationships(db, "Laptop", relationship_types=["IsA"]) ``` -------------------------------- ### Initialize LLM Interface Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/llm_interface_guide.md Demonstrates how to initialize the LLMInterface with a HawkinsDB instance, with options for auto-enrichment and custom configuration like confidence thresholds and validation. ```python from hawkinsdb import HawkinsDB, LLMInterface # Initialize database and LLM interface with auto-enrichment db = HawkinsDB() llm = LLMInterface(db, auto_enrich=True) # Or initialize without auto-enrichment for more control llm_manual = LLMInterface(db, auto_enrich=False) # Configure additional settings (optional) llm = LLMInterface( db, auto_enrich=True, confidence_threshold=0.7, # Minimum confidence for accepting properties max_enrichment_depth=2, # Maximum depth for ConceptNet enrichment validate_properties=True # Enable strict property validation ) ``` -------------------------------- ### Enriching a Technical Concept (Laptop) Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Example of adding and enriching a technical concept, 'Laptop', with its properties like type and category. ```python # Add and enrich a technical concept # computer_data = { # "name": "Laptop", # "column": "Semantic", # "properties": { # "type": "Computer", # "category": "Device" # } # } # db.add_entity(computer_data) # enricher.enrich_entity(db, "Laptop", "Computer") ``` -------------------------------- ### Confidence Scoring Example Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/llm_interface_guide.md Shows how to retrieve and inspect confidence scores associated with properties of entities, which is useful for understanding the certainty of the inferred data. ```python # Query with metadata to see confidence scores response = llm.query_entity( "Speed_of_Light", include_metadata=True ) # Check confidence scores for properties for prop, value in response["data"]["Semantic"]["properties"].items(): print(f"{prop}: {value[0]['confidence']}") ``` -------------------------------- ### Input Formatting Best Practices Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/llm_interface_guide.md Illustrates the difference between good and bad input formatting for natural language descriptions when adding entities, emphasizing clarity and specificity. ```python # Good: Clear, specific descriptions result = llm.add_from_text(""" A MacBook Pro is a high-end laptop computer made by Apple. It features: - Retina display - M1 or M2 processor - Up to 32GB RAM Location: Office desk """) # Bad: Vague or ambiguous descriptions result = llm.add_from_text("It's a computer that does stuff") ``` -------------------------------- ### Property Validation Example Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/llm_interface_guide.md Demonstrates how the LLM Interface automatically validates properties during entity creation, ensuring correct types and formats based on inferred or provided schemas. ```python # The LLM interface automatically validates properties result = llm.add_from_text(""" The speed of light is approximately 299,792,458 meters per second. It is a fundamental physical constant represented by 'c'. """) # Properties are validated and properly typed print(result["entity_data"]["properties"]) ``` -------------------------------- ### Install HawkinsDB using pip Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/README.md Installs the HawkinsDB package using pip, the Python package installer. This command downloads and installs the latest version of HawkinsDB and its dependencies. ```bash pip install hawkinsdb ``` -------------------------------- ### Custom Entity Processing Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/llm_interface_guide.md Provides an example of subclassing the LLMInterface to implement custom logic for processing properties, allowing for extended or modified data handling. ```python from hawkinsdb.llm_interface import LLMInterface class CustomLLMInterface(LLMInterface): def _process_properties(self, properties): """Custom property processing""" processed = super()._process_properties(properties) # Add custom processing logic return processed ``` -------------------------------- ### Query Formulation Best Practices Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/llm_interface_guide.md Highlights best practices for formulating natural language queries, contrasting specific and focused questions with vague or compound ones for better results. ```python # Good: Specific, focused questions response = llm.query("What is the processor type in the MacBook Pro?") # Bad: Vague or compound questions response = llm.query("Tell me about computers and what they do") ``` -------------------------------- ### Enriching an Abstract Concept (Happiness) Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Example of adding and enriching an abstract concept, 'Happiness', with its properties like type and category. ```python # Add and enrich an abstract concept # concept_data = { # "name": "Happiness", # "column": "Semantic", # "properties": { # "type": "Emotion", # "category": "Feeling" # } # } # db.add_entity(concept_data) # enricher.enrich_entity(db, "Happiness", "Emotion") ``` -------------------------------- ### Building a Question-Answering System Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/llm_interface_guide.md Provides a function to build a simple question-answering system. It takes a list of questions, queries the LLM for each question using `llm.query`, and prints the question and the corresponding answer if successful, or an error message otherwise. ```python # Build a simple QA system def answer_questions(questions): for question in questions: response = llm.query(question) if response["success"]: print(f"Q: {question}") print(f"A: {response['response']}") else: print(f"Could not answer: {question}") # Example usage questions = [ "What programming languages are in the database?", "What is Python used for?", "Compare JavaScript and Java" ] answer_questions(questions) ``` -------------------------------- ### Batch Enrichment of Entities Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Provides an example of enriching multiple related entities in a batch process. This is an efficient way to update data for a list of similar entities. ```python # Enrich multiple related entities # Assuming 'enricher' is an instance of ConceptNetEnricher # and 'db' is the database connection # entities = ["Dog", "Cat", "Hamster"] # entity_type = "Pet" # for entity in entities: # enricher.enrich_entity(db, entity, entity_type) ``` -------------------------------- ### Context-Aware Enrichment Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Illustrates enabling context-aware enrichment by specifying a domain. This helps in retrieving more relevant information for entities within a particular field. ```python # Context-aware enrichment enricher = ConceptNetEnricher( context_aware=True, domain="technology" ) enricher.enrich_entity(db, "Smartphone", "Device") ``` -------------------------------- ### Enriching a Natural Concept (Oak Tree) Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Example of adding and enriching a natural concept, 'Oak_Tree', with its properties like type and category. ```python # Add and enrich a natural concept # tree_data = { # "name": "Oak_Tree", # "column": "Semantic", # "properties": { # "type": "Tree", # "category": "Plant" # } # } # db.add_entity(tree_data) # enricher.enrich_entity(db, "Oak_Tree", "Tree") ``` -------------------------------- ### Automated System Documentation Generation Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/llm_interface_guide.md Details a function for generating automated documentation from a system description. It first adds the description to the system and then queries for key aspects like components, features, and requirements, returning them in a structured dictionary. ```python # Generate structured documentation from text def document_system(description): # Add system description result = llm.add_from_text(description) if not result["success"]: return False # Query for important aspects components = llm.query("What are the main components?") features = llm.query("What are the key features?") requirements = llm.query("What are the system requirements?") return { "components": components["response"], "features": features["response"], "requirements": requirements["response"] } ``` -------------------------------- ### Knowledge Base Population with Multiple Entities Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/llm_interface_guide.md Illustrates how to populate a knowledge base by adding multiple related entities from a list of descriptions. It iterates through each description, adds it to the system using `llm.add_from_text`, and prints the name of the added entity. ```python # Add multiple related entities descriptions = [ "Python is a high-level programming language known for its readability", "JavaScript is a programming language used primarily for web development", "Java is a widely-used object-oriented programming language" ] for desc in descriptions: result = llm.add_from_text(desc) if result["success"]: print(f"Added programming language: {result['entity_name']}") ``` -------------------------------- ### Direct Entity Enrichment with ConceptNet Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Demonstrates how to initialize HawkinsDB and ConceptNetEnricher, add a basic entity, and then enrich it using ConceptNet. It also shows how to query the enriched entity to view its properties and relationships. ```python from hawkinsdb import HawkinsDB, ConceptNetEnricher # Initialize db = HawkinsDB() enricher = ConceptNetEnricher() # Add basic entity entity_data = { "name": "Dog", "column": "Semantic", "properties": { "type": "Animal", "category": "Pet" } } db.add_entity(entity_data) # Enrich the entity enriched_result = enricher.enrich_entity(db, "Dog", "Animal") print(f"Enrichment status: {enriched_result}") # Query enriched entity enriched_dog = db.query_frames("Dog") print("Enriched properties:", enriched_dog["Semantic"].properties) print("Enriched relationships:", enriched_dog["Semantic"].relationships) ``` -------------------------------- ### LLMInterface API Reference Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/llm_interface_guide.md Provides an overview of the `LLMInterface` methods, including `add_entity`, `add_from_text`, `query`, and `query_entity`. It details the purpose of each method, its parameters, and expected return types, serving as a reference for developers interacting with the LLM. ```apidoc LLMInterface: add_entity(entity_json: Union[str, Dict]) -> Dict[str, Any]: Add entity from structured data add_from_text(text: str) -> Dict[str, Any]: Add entity from natural language text query(question: str) -> Dict[str, Any]: Answer questions about entities query_entity(name: str, include_metadata: bool = False) -> Dict[str, Any]: Query specific entity details ``` -------------------------------- ### Add Entities from Text Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/llm_interface_guide.md Shows how to add new entities to the database using natural language descriptions. The system automatically processes the text, infers properties, and can enrich the data. ```python # Add entity using natural language result = llm.add_from_text(""" A Tesla Model 3 is an electric car manufactured by Tesla. It has autopilot capabilities, a glass roof, and typically comes in various colors including red, white, and black. """) if result["success"]: print(f"Added entity: {result['entity_name']}") print(f"Enriched: {result['enriched']}") ``` -------------------------------- ### Query with Natural Language Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/llm_interface_guide.md Illustrates how to query the database using natural language questions. It covers general questions about entities and retrieving specific entity details with metadata. ```python # Ask questions about stored entities response = llm.query("What features does the Tesla Model 3 have?") print(f"Answer: {response['response']}") # Query specific entity details details = llm.query_entity("Tesla_Model_3", include_metadata=True) print(f"Entity details: {details}") ``` -------------------------------- ### Enrichment with Multiple Sources Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Shows how to configure the ConceptNetEnricher to validate data from multiple sources and require a minimum number of sources for enrichment. This enhances data reliability. ```python # Enrichment with multiple sources enricher = ConceptNetEnricher( validate_sources=True, min_sources=2 ) enricher.enrich_entity(db, "Computer", "Device") ``` -------------------------------- ### Property Inference: Physical Characteristics Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Example of enriching an entity with its physical attributes using ConceptNet. It adds a 'Car' entity and then uses `enrich_properties` to add physical characteristics. ```python # Example of physical characteristics enrichment car_data = { "name": "Car", "column": "Semantic", "properties": {"type": "Vehicle"} } db.add_entity(car_data) enricher.enrich_properties(db, "Car", ["physical_attributes"]) ``` -------------------------------- ### Property Inference: Typical Locations Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Illustrates location-based enrichment. A 'Hammer' entity is added, and then `enrich_properties` is called to discover and add its typical locations. ```python # Location-based enrichment tool_data = { "name": "Hammer", "column": "Semantic", "properties": {"type": "Tool"} } db.add_entity(tool_data) enricher.enrich_properties(db, "Hammer", ["locations"]) ``` -------------------------------- ### Relationship Discovery: UsedFor Relationships Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Illustrates discovering utility ('UsedFor') relationships for an entity. A 'Screwdriver' entity is added, and then `enrich_relationships` is used to find and add its 'UsedFor' connections. ```python # Discovering utility relationships tool_data = { "name": "Screwdriver", "column": "Semantic", "properties": {"type": "Tool"} } db.add_entity(tool_data) enricher.enrich_relationships(db, "Screwdriver", relationship_types=["UsedFor"]) ``` -------------------------------- ### Selective Property Enrichment Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Demonstrates enriching only specific properties of an entity, such as 'parts', 'capabilities', and 'location'. This is useful for targeted data augmentation. ```python # Enrich specific properties # Assuming 'enricher' is an instance of ConceptNetEnricher # and 'db' is the database connection # enricher.enrich_properties( # db, # entity_name="Car", # properties=["parts", "capabilities", "location"] # ) ``` -------------------------------- ### Automatic Entity Enrichment via LLM Interface Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Shows how to initialize LLMInterface with auto-enrichment enabled and add an entity from text. It then verifies the enrichment by querying the entity and printing its enhanced properties and relationships. ```python from hawkinsdb import HawkinsDB, LLMInterface # Initialize with auto-enrichment db = HawkinsDB() llm = LLMInterface(db, auto_enrich=True) # Add entity with automatic enrichment result = llm.add_from_text( "A golden retriever is a friendly dog breed known for its golden coat" ) # Verify enrichment if result["success"]: entity_name = result["entity_name"] enriched_data = db.query_frames(entity_name) # Print enriched properties semantic_frame = enriched_data.get("Semantic") if semantic_frame: print("Enriched properties:", semantic_frame.properties) print("Added relationships:", semantic_frame.relationships) ``` -------------------------------- ### Error Handling during Enrichment Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Shows a robust try-except block for handling potential errors during the entity enrichment process and verifying the enrichment results. ```python try: # Assuming 'enricher' is an instance of ConceptNetEnricher # and 'db' is the database connection # enriched = enricher.enrich_entity(db, entity_name, entity_type) # if enriched: # print("Successfully enriched entity") # # Verify enrichment # result = db.query_frames(entity_name) # if result: # semantic_frame = result.get("Semantic") # if semantic_frame: # print("Enriched properties:", semantic_frame.properties) # print("Enriched relationships:", semantic_frame.relationships) # else: # print("No enrichment data found") # except Exception as e: # print(f"Error during enrichment: {str(e)}") ``` -------------------------------- ### Relationship Discovery: HasA Relationships Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Demonstrates discovering part-whole ('HasA') relationships for an entity. A 'Car' entity is added, and then `enrich_relationships` is used to find and add its 'HasA' connections. ```python # Discovering part-whole relationships car_data = { "name": "Car", "column": "Semantic", "properties": {"type": "Vehicle"} } db.add_entity(car_data) enricher.enrich_relationships(db, "Car", relationship_types=["HasA"]) ``` -------------------------------- ### Error Handling for Database Operations Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/sqlite_backend.md Provides an example of how to implement error handling for database operations in HawkinsDB, catching specific ValueErrors and general exceptions. ```python try: result = db.add_entity(entity_data) except ValueError as e: print(f"Invalid data: {str(e)}") except Exception as e: print(f"Storage error: {str(e)}") ``` -------------------------------- ### Relationship Discovery: CapableOf Relationships Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Shows how to find capability ('CapableOf') relationships for an entity. A 'Robot' entity is added, and then `enrich_relationships` is used to discover and add its 'CapableOf' connections. ```python # Finding capability relationships robot_data = { "name": "Robot", "column": "Semantic", "properties": {"type": "Machine"} } db.add_entity(robot_data) enricher.enrich_relationships(db, "Robot", relationship_types=["CapableOf"]) ``` -------------------------------- ### Property Inference: Common Behaviors Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Demonstrates enriching an entity with behavioral information. A 'Cat' entity is added, and then `enrich_properties` is used to add its common behaviors. ```python # Enriching with behavior information animal_data = { "name": "Cat", "column": "Semantic", "properties": {"type": "Pet"} } db.add_entity(animal_data) enricher.enrich_properties(db, "Cat", ["behaviors"]) ``` -------------------------------- ### Property Inference: Related Concepts Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Shows how to enrich an entity by discovering related concepts using ConceptNet. An 'Apple' entity is added, and then `enrich_properties` is used to find and add related concepts. ```python # Concept relationship enrichment fruit_data = { "name": "Apple", "column": "Semantic", "properties": {"type": "Fruit"} } db.add_entity(fruit_data) enricher.enrich_properties(db, "Apple", ["related_concepts"]) ``` -------------------------------- ### Define Semantic Memory Data Structure Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/README.md Defines the structure for semantic memory data, including properties and relationships. This example represents knowledge about 'Photosynthesis'. ```python semantic_data = { "name": "Photosynthesis", "column": "Semantic", "properties": { "type": "biological_process", "location": "plant_cells", "components": ["chlorophyll", "sunlight", "water", "carbon_dioxide"], "products": ["glucose", "oxygen"] }, "relationships": { "occurs_in": ["plants", "algae"], "requires": ["light_energy", "chloroplasts"], "produces": ["chemical_energy", "organic_compounds"] } } ``` -------------------------------- ### Custom Confidence-Based Filtering Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/conceptnet_guide.md Demonstrates how to create a custom enricher that filters ConceptNet relations based on a minimum confidence threshold. This allows for more control over the quality of enriched data. ```python from hawkinsdb import ConceptNetEnricher class CustomEnricher(ConceptNetEnricher): def __init__(self): super().__init__() self.min_confidence = 0.7 # Set minimum confidence threshold def filter_relations(self, relations): """Custom filtering of ConceptNet relations""" return [r for r in relations if r.weight >= self.min_confidence] ``` -------------------------------- ### Define Episodic Memory Data Structure Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/README.md Defines the structure for episodic memory data, including timestamp, duration, location, and outcome. This example represents a memory of a 'first_python_project'. ```python episodic_data = { "name": "first_python_project", "column": "Episodic", "properties": { "timestamp": time.time(), "duration": "2 hours", "location": "home_office", "outcome": "successful" }, "relationships": { "involves": ["Python_Language"], "followed_by": ["code_review"] } } ``` -------------------------------- ### Error Handling for LLM Operations Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/llm_interface_guide.md Demonstrates how to handle potential errors during LLM operations, specifically when adding text and checking the success status of the operation. It includes checks for enrichment and prints informative messages for both success and failure scenarios. ```python try: result = llm.add_from_text(text_description) if result["success"]: print(f"Added: {result['entity_name']}") if result["enriched"]: print("Entity was enriched with ConceptNet data") else: print(f"Error: {result['message']}") except Exception as e: print(f"Error processing text: {str(e)}") ``` -------------------------------- ### Configure SQLite Storage Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/sqlite_backend.md Demonstrates how to initialize HawkinsDB and configure it to use SQLite as the storage backend, including setting a custom storage path. ```python from hawkinsdb import HawkinsDB # Initialize database db = HawkinsDB() # Enable SQLite storage db.config.set_storage_backend('sqlite') # Optionally configure SQLite path (default: ./hawkins_memory.db) db.config.set_storage_path('path/to/your/database.db') ``` -------------------------------- ### Initialize LLM Interface with Auto-Enrichment and Query Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/README.md Initializes the LLMInterface with auto-enrichment enabled and demonstrates converting natural language text into structured data and querying the database using natural language. ```python from hawkinsdb import HawkinsDB, LLMInterface # Initialize db = HawkinsDB() llm = LLMInterface( db, auto_enrich=True, confidence_threshold=0.7, max_enrichment_depth=2 ) # Convert natural language to structured data result = llm.add_from_text(""" The respiratory system is responsible for taking in oxygen and releasing carbon dioxide. Key organs include the lungs, trachea, and diaphragm. """) print(f"Added entity: {result['entity_name']}") # Complex querying with context response = llm.query( "What are the main components of the respiratory system?", ) print(f"Response: {response}") ``` -------------------------------- ### Initialize HawkinsDB with SQLite and LLM Interface Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/README.md Initializes HawkinsDB with SQLite storage and creates an LLMInterface for natural language interaction. This sets up the database connection and the language model interface. ```python from hawkinsdb import HawkinsDB , LLMInterface # Initialize with SQLite storage db = HawkinsDB(storage_type="sqlite", db_path="memory.db") llm = LLMInterface(db) ``` -------------------------------- ### Configure HawkinsDB with Custom SQLite Path and Error Handling Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/README.md Demonstrates initializing HawkinsDB with a custom SQLite database path and includes basic operations with error handling. It shows how to add and query entities, and how to handle potential storage errors. ```python # Initialize with custom SQLite path db = HawkinsDB( storage_type="sqlite", db_path="custom_path/memory.db" ) # Basic operations try: # Add entity result = db.add_entity(entity_data) # Query data frames = db.query_frames("entity_name") # Cleanup db.cleanup() # Close connections except Exception as e: print(f"Storage error: {str(e)}") ``` -------------------------------- ### Cleanup HawkinsDB Connections Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/sqlite_backend.md Illustrates the proper way to close database connections and free resources managed by HawkinsDB. ```python db.cleanup() ``` -------------------------------- ### Query Data from HawkinsDB Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/sqlite_backend.md Illustrates how to retrieve data from HawkinsDB, including fetching frames for a specific entity and listing all available entities. ```python # Get all frames for an entity frames = db.query_frames("Tesla Model 3") # List all entities entities = db.list_entities() ``` -------------------------------- ### Execute Custom SQLite Queries Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/sqlite_backend.md Shows how to execute custom SQL queries directly against the SQLite backend using the get_storage_backend interface. ```python from hawkinsdb.storage import get_storage_backend storage = get_storage_backend('sqlite') storage.execute_query("SELECT * FROM entities WHERE name LIKE ?", ("%Tesla%",)) ``` -------------------------------- ### Bulk Add Entities Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/sqlite_backend.md Demonstrates how to efficiently add multiple entities to HawkinsDB by iterating through a list of entity data. ```python entities = [ {"name": "Entity1", "properties": {...}}, {"name": "Entity2", "properties": {...}} ] for entity in entities: db.add_entity(entity) ``` -------------------------------- ### Query and List Entities in HawkinsDB Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/README.md Shows how to query a specific entity and list all entities stored in HawkinsDB. `query_frames` retrieves information about a specific entity, while `list_entities` returns a list of all entities in the database. ```python # Query specific entity cat_info = db.query_frames("cat") # List all entities entities = db.list_entities() ``` -------------------------------- ### Integrate ConceptNet for Knowledge Enrichment Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/README.md Demonstrates integrating ConceptNet to enrich entities in HawkinsDB. It initializes the ConceptNetEnricher, adds an entity, and then enriches it using ConceptNet. ```python from hawkinsdb import ConceptNetEnricher # Initialize db = HawkinsDB() enricher = ConceptNetEnricher() # Add and enrich entity entity_data = { "name": "Dog", "column": "Semantic", "properties": { "type": "Animal", "category": "Pet" } } db.add_entity(entity_data) enriched_result = enricher.enrich_entity(db, "Dog", "Animal") ``` -------------------------------- ### Add Entity to HawkinsDB Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/sqlite_backend.md Shows how to add a new entity with its properties and relationships to the HawkinsDB using the add_entity method. ```python entity_data = { "name": "Tesla Model 3", "properties": { "color": "red", "year": 2023 }, "relationships": { "located_in": ["garage"] } } result = db.add_entity(entity_data) ``` -------------------------------- ### Error Handling with ValidationError Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/README.md Illustrates how to handle potential `ValidationError` exceptions when adding entities to the database, along with general exception handling for other errors. It shows how to check the success status of an add operation and print relevant messages. ```python from hawkinsdb import ValidationError try: # Add entity with validation result = db.add_entity({ "name": "Test", "column": "Semantic", "properties": { "age": "42" # Will be converted to integer } }) if result["success"]: print(f"Added: {result['entity_name']}") else: print(f"Error: {result['message']}") except ValidationError as e: print(f"Validation error: {str(e)}") except Exception as e: print(f"General error: {str(e)}") ``` -------------------------------- ### Add Semantic and Episodic Memories to HawkinsDB Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/README.md Demonstrates adding semantic and episodic memories to HawkinsDB. Semantic memory stores conceptual knowledge, while episodic memory stores event-based information with timestamps. ```python # Add semantic memory semantic_memory = { "name": "cat", "column": "Semantic", "properties": { "type": "animal", "size": "medium", "characteristics": ["furry", "agile", "carnivorous"] }, "relationships": { "habitat": ["homes", "outdoors"], "behavior": ["hunting", "sleeping", "grooming"] } } result = db.add_entity(semantic_memory) response = llm.query( "Explain the behaviours of cat", ) # Add episodic memory import time episodic_memory = { "name": "cat_observation", "column": "Episodic", "properties": { "timestamp": time.time(), "action": "Observed cat behavior", "location": "Garden", "details": "Cat was chasing a butterfly" }, "relationships": { "relates_to": ["cat"], "observed_by": ["human"] } } result = db.add_entity(episodic_memory) ``` -------------------------------- ### Custom Entity Enrichment Source: https://github.com/harishsg993010/hawkinsdb/blob/main/docs/README.md Demonstrates how to create and use a custom enricher by extending the ConceptNetEnricher class. It filters relations based on a minimum confidence score and applies this custom logic to enrich an entity. ```python class CustomEnricher(ConceptNetEnricher): def __init__(self): super().__init__() self.min_confidence = 0.7 def filter_relations(self, relations): return [r for r in relations if r.weight >= self.min_confidence] # Use custom enricher custom_enricher = CustomEnricher() custom_enricher.enrich_entity(db, "Dog", "Animal") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.