### Start Docker Services Source: https://context7.com/mallahyari/keplai/llms.txt Commands to initialize the environment and launch the containerized stack. ```bash echo "OPENAI_API_KEY=sk-your-key" > .env docker compose up --build ``` -------------------------------- ### Install KeplAI via pip Source: https://github.com/mallahyari/keplai/blob/main/README.md Commands to clone the repository and install the package with various dependency sets. ```bash # Clone the repository git clone https://github.com/mallahyari/keplai.git cd keplai # Install with all extras pip install -e ".[all,dev]" ``` ```bash pip install -e "." # Core SDK only pip install -e ".[api]" # SDK + REST API pip install -e ".[ai]" # SDK + AI features pip install -e ".[all]" # Everything ``` -------------------------------- ### Run KeplAI with Docker Compose Source: https://github.com/mallahyari/keplai/blob/main/README.md Initialize the environment and start the full stack services. ```bash # Create a .env file with your API key echo "OPENAI_API_KEY=sk-your-key-here" > .env # Start all services docker compose up --build ``` -------------------------------- ### Run KeplAI API and Frontend Locally Source: https://github.com/mallahyari/keplai/blob/main/README.md Commands to start the API server and the React-based frontend for development. ```bash # Create .env echo "OPENAI_API_KEY=sk-your-key-here" > .env # Run the API keplai serve --reload # or uvicorn api.main:app --reload ``` ```bash cd frontend npm install npm run dev ``` -------------------------------- ### Initialize KeplAI SDK Source: https://context7.com/mallahyari/keplai/llms.txt Starts a new graph by provisioning Fuseki via Docker or connects to an existing Fuseki instance. Includes checks for engine health and endpoint details. ```python from keplai import KeplAI # Start a new graph (provisions Fuseki via Docker automatically) kg = KeplAI.start(engine="docker", reasoner="OWL") # Or connect to an existing Fuseki instance kg = KeplAI.connect( endpoint="http://localhost:3030", dataset="keplai" ) # Check engine health is_healthy = kg._engine.is_healthy() print(f"Fuseki endpoint: {kg._engine.endpoint}") print(f"SPARQL URL: {kg._engine.sparql_url}") print(f"Update URL: {kg._engine.update_url}") # Shutdown when done (data persists via Docker volume) kg.stop() ``` -------------------------------- ### React: Frontend API Client Layer Source: https://github.com/mallahyari/keplai/blob/main/docs/plans/2026-03-15-graphai-implementation-plan.md A basic example of an API client layer for the React frontend using `axios`. It sets up a base URL and provides typed methods for interacting with the backend API. ```javascript import axios from 'axios'; const apiClient = axios.create({ baseURL: '/api', headers: { 'Content-Type': 'application/json', }, }); export const getTriples = async (params) => { const response = await apiClient.get('/graph/triples', { params }); return response.data; }; export const addTriple = async (triple) => { const response = await apiClient.post('/graph/triples', triple); return response.data; }; export const deleteTriple = async (triple) => { const response = await apiClient.delete('/graph/triples', { data: triple }); return response.data; }; export const getStatus = async () => { const response = await apiClient.get('/graph/status'); return response.data; }; export const getAllTriples = async () => { const response = await apiClient.get('/graph/triples/all'); return response.data; }; ``` -------------------------------- ### GET /api/entities Source: https://context7.com/mallahyari/keplai/llms.txt Lists all known entities in the knowledge graph. ```APIDOC ## GET /api/entities ### Description Lists all known entities in the knowledge graph. ### Method GET ### Endpoint /api/entities ### Response #### Success Response (200) - **name** (string) - The name of the entity. ``` -------------------------------- ### GET /api/ontology/properties Source: https://github.com/mallahyari/keplai/blob/main/docs/plans/2026-03-15-graphai-implementation-plan.md Lists all defined properties with their domain and range. ```APIDOC ## GET /api/ontology/properties ### Description Lists all defined properties with domain and range. ### Method GET ### Endpoint /api/ontology/properties ``` -------------------------------- ### GET /api/entities Source: https://github.com/mallahyari/keplai/blob/main/docs/plans/2026-03-15-graphai-implementation-plan.md Lists all known entities with their canonical URIs. ```APIDOC ## GET /api/entities ### Description Retrieves a list of all known entities with their canonical URIs. ### Method GET ### Endpoint /api/entities ``` -------------------------------- ### Query Triples with Filters via REST API Source: https://context7.com/mallahyari/keplai/llms.txt Query triples from the graph using filters. This example filters by subject. ```bash # Query triples with filters curl "http://localhost:8000/api/graph/triples?subject=Alice" ``` -------------------------------- ### Python SDK: JenaEngine Docker Management Source: https://github.com/mallahyari/keplai/blob/main/docs/plans/2026-03-15-graphai-implementation-plan.md Manages the lifecycle of a Jena Fuseki Docker container, including pulling the image, starting, stopping, and health checks. Configurable via environment variables or constructor arguments. ```python class JenaEngine: def __init__(self, image="stain/jena-fuseki", port=3030, dataset="tdb2", container_name="fuseki"): self.image = image self.port = port self.dataset = dataset self.container_name = container_name self.client = docker.from_env() self.container = None def start(self, reasoner="OWL"): # ... (implementation details for starting container) pass def stop(self): # ... (implementation details for stopping container) pass def health_check(self): # ... (implementation details for health check) pass ``` -------------------------------- ### Handle KeplAI Errors in Python Source: https://context7.com/mallahyari/keplai/llms.txt Use try-except blocks to catch specific KeplAI exceptions during operations. This example covers engine startup, data extraction, querying, ontology loading, conflict resolution, and disambiguation. ```python from keplai import \ KeplAI, \ KeplAIError, \ EngineError, \ ExtractionError, \ QueryError, \ DisambiguationError, \ OntologyImportError, \ OntologyConflictError, \ OntologyNotFoundError import asyncio async def error_handling_example(): try: kg = KeplAI.start() except EngineError as e: print(f"Failed to start Fuseki: {e}") return try: # Extraction errors (LLM failures) await kg.extract_and_store("some text", mode="strict") except ExtractionError as e: print(f"Extraction failed: {e}") try: # Query errors (invalid SPARQL, write attempts) await kg.ask("some question") except QueryError as e: print(f"Query failed: {e}") try: # Import errors (invalid file, network issues) kg.ontology.load_rdf("nonexistent.ttl") except OntologyImportError as e: print(f"Import failed: {e}") try: # Conflict when property matches multiple ontologies kg.add("Subject", "ambiguous_property", "Object") except OntologyConflictError as e: print(f"Ontology conflict: {e}") try: # Vector store failures await kg.disambiguator.get_similar("entity") except DisambiguationError as e: print(f"Disambiguation failed: {e}") kg.stop() asyncio.run(error_handling_example()) ``` -------------------------------- ### Add React-Specific ESLint Rules Source: https://github.com/mallahyari/keplai/blob/main/frontend/README.md Integrate eslint-plugin-react-x and eslint-plugin-react-dom for enhanced React and React DOM linting. This requires installing these plugins. ```javascript // eslint.config.js import reactX from 'eslint-plugin-react-x' import reactDom from 'eslint-plugin-react-dom' export default defineConfig([ globalIgnores(['dist']), { files: ['**/*.{ts,tsx}'], extends: [ // Other configs... // Enable lint rules for React reactX.configs['recommended-typescript'], // Enable lint rules for React DOM reactDom.configs.recommended, ], languageOptions: { parserOptions: { project: ['./tsconfig.node.json', './tsconfig.app.json'], tsconfigRootDir: import.meta.dirname, }, // other options... }, }, ]) ``` -------------------------------- ### Get All Triples via REST API Source: https://context7.com/mallahyari/keplai/llms.txt Retrieves all triples currently stored in the graph. ```bash # Get all triples curl http://localhost:8000/api/graph/triples/all ``` -------------------------------- ### Get Full Ontology Schema via REST API Source: https://context7.com/mallahyari/keplai/llms.txt Fetches the complete schema of the ontology, including all defined classes and properties. ```bash # Get full schema curl http://localhost:8000/api/ontology/schema ``` -------------------------------- ### Natural Language Query using REST API Source: https://github.com/mallahyari/keplai/blob/main/README.md Example of querying the knowledge graph using natural language via the REST API with cURL. The request includes the question in JSON format. ```bash # Ask a question curl -X POST http://localhost:8000/api/query/ask \ -H "Content-Type: application/json" \ -d '{"question": "Who does Alice know?"}' ``` -------------------------------- ### Entity Disambiguation with KeplAI Source: https://context7.com/mallahyari/keplai/llms.txt Example of using KeplAI for entity disambiguation. It involves adding entities, finding similar entities using vector similarity, retrieving all known entities, and resolving entity names to canonical forms. ```python import asyncio from keplai import KeplAI async def disambiguate_example(): kg = KeplAI.start() # Add some entities (they get registered in the vector store) await kg.extract_and_store("Mehdi Allahyari founded BrandPulse.", mode="open") # Find similar entities similar = await kg.disambiguator.get_similar("Mehdi", top_k=5) for match in similar: print(f"{match['name']} (score: {match['score']:.3f})") # Output might show: # MehdiAllahyari (score: 0.85) # Get all known entities entities = kg.disambiguator.get_all_entities() for e in entities: print(f"Entity: {e['name']}") # Resolve an entity name (used internally during extraction) canonical, score, matched = await kg.disambiguator.resolve("M. Allahyari") print(f"Resolved '{canonical}' with score {score}, matched: {matched}") kg.stop() asyncio.run(disambiguate_example()) ``` -------------------------------- ### Extract Triples from Text using REST API Source: https://github.com/mallahyari/keplai/blob/main/README.md Example of using the REST API to extract triples from provided text. The request is a POST to the extraction endpoint, including the text and the desired extraction mode. ```bash # Extract triples from text curl -X POST http://localhost:8000/api/extract \ -H "Content-Type: application/json" \ -d '{"text": "Albert Einstein was born in Germany.", "mode": "open"}' ``` -------------------------------- ### Zero-Config Startup with KeplAI Source: https://github.com/mallahyari/keplai/blob/main/docs/plans/2026-03-15-graphai-implementation-plan.md Initiates KeplAI with zero configuration, automatically spinning up a Fuseki Docker container and enabling OWL reasoning. ```python graph = KeplAI.start(engine="docker", reasoner="OWL") ``` -------------------------------- ### GraphAI Initialization and Schema Definition Source: https://github.com/mallahyari/keplai/blob/main/prd.md Demonstrates the zero-config startup of GraphAI, including spinning up a Fuseki Docker container and defining a schema using Pythonic methods. ```python from graphai import GraphAI, Entity # 1. Zero-config startup (Spins up Fuseki Docker) graph = GraphAI.start(engine="docker", reasoner="OWL") # 2. Schema definition (Pythonic) graph.ontology.define_class("Company") graph.ontology.define_class("Person") graph.ontology.define_property("founded", domain="Person", range="Company") ``` -------------------------------- ### GET /api/ontology/classes Source: https://github.com/mallahyari/keplai/blob/main/docs/plans/2026-03-15-graphai-implementation-plan.md Retrieves a list of all defined OWL classes. ```APIDOC ## GET /api/ontology/classes ### Description Lists all defined OWL classes. ### Method GET ### Endpoint /api/ontology/classes ``` -------------------------------- ### GET /api/ontology/schema Source: https://github.com/mallahyari/keplai/blob/main/docs/plans/2026-03-15-graphai-implementation-plan.md Retrieves the full ontology schema as a structured dictionary. ```APIDOC ## GET /api/ontology/schema ### Description Returns the full ontology as a structured dictionary. ### Method GET ### Endpoint /api/ontology/schema ``` -------------------------------- ### GET /api/entities/{name}/similar Source: https://context7.com/mallahyari/keplai/llms.txt Finds entities similar to the specified entity. ```APIDOC ## GET /api/entities/{name}/similar ### Description Finds entities similar to the specified entity. ### Method GET ### Endpoint /api/entities/{name}/similar ### Parameters #### Path Parameters - **name** (string) - Required - The name of the entity to find similarities for. ### Response #### Success Response (200) - **name** (string) - The name of the similar entity. - **score** (float) - The similarity score. ``` -------------------------------- ### Configure KeplAI Environment Variables Source: https://context7.com/mallahyari/keplai/llms.txt Define settings for LLM models, Fuseki database, and namespaces using a .env file. ```bash OPENAI_API_KEY=sk-your-key-here OPENAI_MODEL=gpt-4o EMBEDDING_MODEL=text-embedding-3-small # Fuseki settings (prefixed with KEPLAI_) KEPLAI_FUSEKI_IMAGE=stain/jena-fuseki KEPLAI_FUSEKI_PORT=3030 KEPLAI_FUSEKI_DATASET=keplai KEPLAI_FUSEKI_ADMIN_PASSWORD=keplai-admin # Namespaces KEPLAI_ENTITY_NAMESPACE=http://keplai.io/entity/ KEPLAI_ONTOLOGY_NAMESPACE=http://keplai.io/ontology/ # Reasoner: OWL, RDFS, or NONE KEPLAI_REASONER=OWL # Disambiguation threshold (0.0-1.0) KEPLAI_DISAMBIGUATION_THRESHOLD=0.90 # Qdrant path (None = in-memory) KEPLAI_QDRANT_PATH=/data/qdrant # Provenance database path (None = disabled) KEPLAI_PROVENANCE_PATH=/data/provenance.db ``` -------------------------------- ### Initialize KeplAI Programmatically Source: https://context7.com/mallahyari/keplai/llms.txt Override default configuration settings during runtime using the Python SDK. ```python from keplai import KeplAI # Override settings programmatically kg = KeplAI.start( reasoner="RDFS", fuseki_port=3031, entity_namespace="http://myapp.com/entity/", disambiguation_threshold=0.85, ) kg.stop() ``` -------------------------------- ### Perform Basic Graph Operations Source: https://github.com/mallahyari/keplai/blob/main/README.md SDK methods for initializing a graph, adding, querying, and deleting RDF triples. ```python from keplai import KeplAI # Start a new graph (provisions Fuseki via Docker) kg = KeplAI.start() # Or connect to an existing Fuseki instance # kg = KeplAI.connect("http://localhost:3030", dataset="keplai") # Add triples kg.add("Mehdi", "founded", "BrandPulse") kg.add("Mehdi", "role", "CEO") kg.add("BrandPulse", "industry", "AI") # Query triples results = kg.find(subject="Mehdi") # [{"s": "http://keplai.io/entity/Mehdi", "p": "...", "o": "..."}] # Delete a triple kg.delete("Mehdi", "role", "CEO") # Get all triples all_triples = kg.get_all_triples() # Shutdown (data persists in Docker volume) kg.stop() ``` -------------------------------- ### Deploy Stack with Docker Compose Source: https://context7.com/mallahyari/keplai/llms.txt Orchestrate the Fuseki database, API, and frontend services using a single configuration file. ```yaml version: '3.8' services: fuseki: image: stain/jena-fuseki environment: - FUSEKI_DATASET_1=keplai - ADMIN_PASSWORD=keplai-admin volumes: - fuseki-data:/fuseki ports: - "3030:3030" api: build: . environment: - OPENAI_API_KEY=${OPENAI_API_KEY} - KEPLAI_FUSEKI_PORT=3030 ports: - "8000:8000" depends_on: - fuseki frontend: build: ./frontend ports: - "5173:80" depends_on: - api volumes: fuseki-data: ``` -------------------------------- ### GET /api/entities/{name}/context Source: https://context7.com/mallahyari/keplai/llms.txt Retrieves the context of an entity, including related triples and similar entities. ```APIDOC ## GET /api/entities/{name}/context ### Description Retrieves the context of an entity, including related triples and similar entities. ### Method GET ### Endpoint /api/entities/{name}/context ### Parameters #### Path Parameters - **name** (string) - Required - The name of the entity. ### Response #### Success Response (200) - **entity** (string) - The entity name. - **triples_as_subject** (array) - Triples where this entity is the subject. - **triples_as_object** (array) - Triples where this entity is the object. - **entity_type** (string) - The type of the entity. - **similar_entities** (array) - List of similar entities. ``` -------------------------------- ### Apply Ontology Proposal Source: https://github.com/mallahyari/keplai/blob/main/docs/plans/next-features.md Bulk-creates classes and properties based on a provided ontology proposal dictionary. ```python graph.ontology.apply_proposal(proposal) ``` -------------------------------- ### Import Ontologies from Files Source: https://context7.com/mallahyari/keplai/llms.txt Load RDF-based ontologies from local files. The system automatically detects formats like Turtle, RDF/XML, N-Triples, and JSON-LD. ```python from keplai import KeplAI kg = KeplAI.start() # Import from Turtle file result = kg.ontology.load_rdf( "my_ontology.ttl", format="auto", # Detects from extension: .ttl, .rdf, .owl, .nt, .jsonld name="My Custom Ontology", batch_size=1000 ) print(f"Ontology ID: {result['ontology_id']}") print(f"Graph URI: {result['graph_uri']}") print(f"Triples loaded: {result['triples_loaded']}") print(f"Classes found: {len(result['classes'])}") print(f"Properties found: {len(result['properties'])}") # Supported file formats: # .ttl, .turtle -> Turtle # .rdf, .xml, .owl -> RDF/XML # .nt, .ntriples -> N-Triples # .jsonld, .json -> JSON-LD kg.stop() ``` -------------------------------- ### Execute SPARQL Query Source: https://context7.com/mallahyari/keplai/llms.txt Demonstrates executing a SPARQL query. Note that INSERT/DELETE/DROP queries are rejected, and only read-only queries are allowed. ```python try: kg.nlq.execute_sparql("INSERT DATA { 'value' }") except Exception as e: print(f"Error: {e}") # QueryError: Only read-only SPARQL queries are allowed ``` -------------------------------- ### Manage Ontologies Source: https://github.com/mallahyari/keplai/blob/main/README.md Methods for defining schema classes and properties, and importing ontologies from files or URLs. ```python # Define schema kg.ontology.define_class("Person") kg.ontology.define_class("Company") kg.ontology.define_property("founded", domain="Person", range="Company") # Import from file result = kg.ontology.load_rdf("ontology.ttl", name="My Ontology") print(f"Loaded {result['triples_loaded']} triples") print(f"Ontology ID: {result['ontology_id']}") # Import from URL result = kg.ontology.load_url("http://xmlns.com/foaf/0.1/", name="FOAF") # View schema schema = kg.ontology.get_schema() print(schema["classes"]) # [{"uri": "...", "name": "Person"}, ...] print(schema["properties"]) # [{"uri": "...", "name": "founded", ...}] ``` -------------------------------- ### Get Provenance for a Triple via REST API Source: https://context7.com/mallahyari/keplai/llms.txt Retrieves provenance information for a specific triple, including details about its creation method and timestamp. ```bash # Get provenance for a triple curl "http://localhost:8000/api/graph/triples/provenance?subject=http://keplai.io/entity/Alice&predicate=http://keplai.io/ontology/knows&obj=http://keplai.io/entity/Bob" ``` -------------------------------- ### Project directory structure Source: https://github.com/mallahyari/keplai/blob/main/README.md Visual representation of the KeplAI repository layout, highlighting core SDK, API, and frontend components. ```text keplai/ ├── src/keplai/ # Core SDK │ ├── __init__.py # Public API exports │ ├── graph.py # KeplAI main class (entry point) │ ├── engine.py # JenaEngine (Docker/Fuseki lifecycle) │ ├── ontology.py # OntologyManager (schema + import) │ ├── extractor.py # AIExtractor (LLM triple extraction) │ ├── nlq.py # NLQueryEngine (NL-to-SPARQL) │ ├── disambiguator.py # EntityDisambiguator (vector matching) │ ├── provenance.py # ProvenanceStore (triple provenance tracking) │ ├── config.py # KeplAISettings (Pydantic config) │ ├── exceptions.py # Exception hierarchy │ ├── cli.py # CLI entry point │ └── vectorstore/ # Vector store abstraction │ ├── base.py │ └── qdrant.py ├── api/ # REST API (FastAPI) │ ├── main.py # App factory + lifespan │ ├── schemas.py # Pydantic request/response models │ ├── dependencies.py # Dependency injection │ └── routers/ │ ├── graph.py # /api/graph endpoints │ ├── ontology.py # /api/ontology endpoints │ ├── extraction.py # /api/extract endpoints │ └── query.py # /api/query endpoints ├── frontend/ # Web UI (React + TypeScript) │ ├── src/ │ │ ├── api/client.ts # Typed API client │ │ ├── types/graph.ts # TypeScript interfaces │ │ ├── pages/ # Page components │ │ └── components/ # Shared UI components (shadcn) │ ├── package.json │ └── Dockerfile ├── tests/ │ ├── unit/ # Mock-based unit tests │ └── integration/ # Docker-dependent tests ├── docker-compose.yml # Full-stack deployment ├── Dockerfile # API server image ├── pyproject.toml # Python project config └── .env # Environment variables ``` -------------------------------- ### Get Graph Statistics via REST API Source: https://context7.com/mallahyari/keplai/llms.txt Retrieve statistics about the graph, including triple count, entity count, ontology count, class count, and property count. ```bash # Get graph statistics curl http://localhost:8000/api/graph/stats ``` -------------------------------- ### Open Extraction Mode Source: https://github.com/mallahyari/keplai/blob/main/prd.md Demonstrates the 'open' extraction mode where the AI can invent the schema based on the provided text. ```python # 1. Open Extraction (AI invents the schema) graph.extract_and_store("The James Webb Telescope discovered K2-18b.", mode="open") ``` -------------------------------- ### Natural Language Query and Graph Shutdown Source: https://github.com/mallahyari/keplai/blob/main/prd.md Illustrates how to query the graph using natural language and how to properly shut down the GraphAI instance, persisting the data. ```python # 5. Natural Language Query results = graph.ask("What companies did Mehdi found?") print(results) #[{'entity': 'BrandPulse', 'type': 'Company'}] # 6. Shut down and persist graph.stop() ``` -------------------------------- ### Load Ontology File Source: https://github.com/mallahyari/keplai/blob/main/docs/plans/next-features.md Parses and imports an ontology file from a local path or URL into the graph store. ```python graph.ontology.load_file(path_or_url, format="auto") ``` ```python graph.ontology.load_url(url) ``` -------------------------------- ### List All Classes via REST API Source: https://context7.com/mallahyari/keplai/llms.txt Retrieves a list of all classes defined in the ontology. ```bash # List all classes curl http://localhost:8000/api/ontology/classes ``` -------------------------------- ### Execute Natural Language and SPARQL Queries Source: https://context7.com/mallahyari/keplai/llms.txt Perform semantic queries or execute raw SPARQL commands against the knowledge graph. ```bash curl -X POST http://localhost:8000/api/query/ask \ -H "Content-Type: application/json" \ -d '{"question": "Who founded BrandPulse?"}' ``` ```bash curl -X POST http://localhost:8000/api/query/ask/explain \ -H "Content-Type: application/json" \ -d '{"question": "What companies are in the AI industry?"}' ``` ```bash curl -X POST http://localhost:8000/api/query/sparql \ -H "Content-Type: application/json" \ -d '{"sparql": "SELECT ?s ?p ?o WHERE { GRAPH ?g { ?s ?p ?o } } LIMIT 10"}' ``` -------------------------------- ### POST /api/query/ask/explain Source: https://context7.com/mallahyari/keplai/llms.txt Executes a natural language question and provides an explanation for the result. ```APIDOC ## POST /api/query/ask/explain ### Description Executes a natural language question and provides an explanation for the result. ### Method POST ### Endpoint /api/query/ask/explain ### Request Body - **question** (string) - Required - The natural language question. ### Request Example { "question": "What companies are in the AI industry?" } ### Response #### Success Response (200) - **results** (array) - The query results. - **sparql** (string) - The generated SPARQL query. - **explanation** (string) - The explanation for the result. ``` -------------------------------- ### Upload Ontology File via REST API Source: https://context7.com/mallahyari/keplai/llms.txt Uploads an ontology file (e.g., TTL format) to the system. Requires the file to be sent as form data. ```bash # Upload an ontology file curl -X POST http://localhost:8000/api/ontology/upload \ -F "file=@my_ontology.ttl" \ -F "name=My Ontology" ``` -------------------------------- ### Run project tests Source: https://github.com/mallahyari/keplai/blob/main/README.md Commands to execute unit and integration tests using pytest, including coverage reporting. ```bash # Run unit tests pytest tests/unit/ -v # Run integration tests (requires Docker) pytest tests/integration/ -v -m integration # Run all tests pytest -v # Run with coverage pytest --cov=keplai tests/ ``` -------------------------------- ### Add a Triple using REST API Source: https://github.com/mallahyari/keplai/blob/main/README.md Example of adding a triple to the knowledge graph via the REST API using a cURL command. Requires specifying the endpoint, method, content type, and the triple data in JSON format. ```bash # Add a triple curl -X POST http://localhost:8000/api/graph/triples \ -H "Content-Type: application/json" \ -d '{"subject": "Alice", "predicate": "knows", "object": "Bob"}' ``` -------------------------------- ### Query Entity Information Source: https://context7.com/mallahyari/keplai/llms.txt Retrieve lists of entities, find similar matches, or fetch full context for a specific entity. ```bash curl http://localhost:8000/api/entities ``` ```bash curl http://localhost:8000/api/entities/Einstein/similar ``` ```bash curl http://localhost:8000/api/entities/AlbertEinstein/context ``` -------------------------------- ### Add a Triple using SDK Source: https://github.com/mallahyari/keplai/blob/main/README.md Demonstrates adding a simple triple to the knowledge graph using the SDK. The system automatically resolves URIs and types entities based on the domain and range defined in the ontology. ```python kg.add("Mehdi", "owns", "Easter") # Resolves to cat:owns, auto-types from domain/range ``` -------------------------------- ### Connect to Existing Fuseki Instance Source: https://github.com/mallahyari/keplai/blob/main/docs/plans/2026-03-15-graphai-implementation-plan.md Use this method to connect to an already running Fuseki instance. It detects existing containers and reattaches instead of creating new ones. ```python KeplAI.connect(endpoint="http://localhost:3030") ``` -------------------------------- ### List All Properties via REST API Source: https://context7.com/mallahyari/keplai/llms.txt Retrieves a list of all properties defined in the ontology, including their names, domains, and ranges. ```bash # List all properties curl http://localhost:8000/api/ontology/properties ``` -------------------------------- ### Upload Ontology File using REST API Source: https://github.com/mallahyari/keplai/blob/main/README.md Demonstrates uploading an ontology file (e.g., TTL format) to the Keplai API using cURL. This involves a POST request to the ontology upload endpoint, specifying the file as form data. ```bash # Upload an ontology file curl -X POST http://localhost:8000/api/ontology/upload \ -F "file=@ontology.ttl" ``` -------------------------------- ### Import Ontologies from URLs Source: https://context7.com/mallahyari/keplai/llms.txt Fetch remote ontologies directly from URLs to integrate standard vocabularies like FOAF or Schema.org. ```python from keplai import KeplAI kg = KeplAI.start() # Import FOAF ontology foaf_result = kg.ontology.load_url( "http://xmlns.com/foaf/0.1/", name="FOAF" ) print(f"FOAF loaded: {foaf_result['triples_loaded']} triples") # Import Schema.org (note: large ontology) # schema_result = kg.ontology.load_url( # "https://schema.org/version/latest/schemaorg-current-https.ttl", # name="Schema.org" # ) kg.stop() ``` -------------------------------- ### Natural Language Queries with SDK Source: https://github.com/mallahyari/keplai/blob/main/README.md Enables querying the knowledge graph using natural language questions. Supports retrieving generated SPARQL queries, results, and human-readable explanations. Also allows direct execution of raw SPARQL queries. ```python import asyncio # Ask a question in plain English result = asyncio.run(kg.ask("What companies did Mehdi found?")) print(result["sparql"]) print(result["results"]) # Ask with explanation result = asyncio.run(kg.ask_with_explanation("Who works at BrandPulse?")) print(result["explanation"]) # Execute raw SPARQL (read-only enforced) result = kg.nlq.execute_sparql("SELECT ?s ?o WHERE { ?s ?p ?o } LIMIT 10") ``` -------------------------------- ### Python SDK: KeplAI Main Class Source: https://github.com/mallahyari/keplai/blob/main/docs/plans/2026-03-15-graphai-implementation-plan.md The core KeplAI class for interacting with the graph database. Supports starting/stopping the engine, adding, finding, deleting, and retrieving triples. Handles namespace management and URI construction. ```python from rdflib import URIRef, Literal, Namespace class KeplAI: def __init__(self, engine, base_entity_uri="http://keplaai.io/entity/", base_ontology_uri="http://keplaai.io/ontology/"): self.engine = engine self.entity_ns = Namespace(base_entity_uri) self.ontology_ns = Namespace(base_ontology_uri) @classmethod def start(cls, engine_type="docker", reasoner="OWL"): if engine_type == "docker": engine = JenaEngine() engine.start(reasoner=reasoner) return cls(engine) else: raise ValueError("Unsupported engine type") def stop(self): self.engine.stop() def _to_uri(self, value): if isinstance(value, URIRef): return value return self.entity_ns[value] def _to_literal(self, value): if isinstance(value, (str, int, float)): return Literal(value) return value def add(self, subject, predicate, object): subject_uri = self._to_uri(subject) object_val = self._to_literal(object) # ... (SPARQL UPDATE implementation) pass def find(self, subject=None, predicate=None, object=None): # ... (SPARQL SELECT implementation) pass def delete(self, subject, predicate, object): # ... (SPARQL UPDATE implementation) pass def get_all_triples(self): # ... (SPARQL SELECT implementation) pass ``` -------------------------------- ### Perform Natural Language Queries Source: https://context7.com/mallahyari/keplai/llms.txt Ask questions in plain English to generate and execute SPARQL queries against the knowledge graph. ```python import asyncio from keplai import KeplAI async def nlq_example(): kg = KeplAI.start() # Add sample data kg.add("Mehdi", "founded", "BrandPulse") kg.add("Alice", "worksAt", "BrandPulse") kg.add("BrandPulse", "industry", "AI") # Ask a natural language question result = await kg.ask("What companies did Mehdi found?") print(f"Generated SPARQL:\n{result['sparql']}") print(f"\nResults:") for row in result['results']: print(f" {row}") # Output: # Generated SPARQL: # PREFIX entity: # PREFIX ontology: # SELECT ?company WHERE { # GRAPH ?g { entity:Mehdi ontology:founded ?company } # } # # Results: # {'company': 'http://keplai.io/entity/BrandPulse'} kg.stop() asyncio.run(nlq_example()) ``` -------------------------------- ### Handle Multi-Ontology Support Source: https://github.com/mallahyari/keplai/blob/main/README.md Operations for managing multiple ontologies, including listing, schema retrieval, and deletion. ```python # Import multiple ontologies (each gets its own named graph) cat_onto = kg.ontology.load_rdf("cat_ontology.ttl", name="Cat Ontology") foaf = kg.ontology.load_url("http://xmlns.com/foaf/0.1/", name="FOAF") # List all imported ontologies ontologies = kg.ontology.list_ontologies() for ont in ontologies: print(f"{ont['name']} - {ont['classes_count']} classes, {ont['properties_count']} props") # View schema for a specific ontology schema = kg.ontology.get_schema(graph_uri=cat_onto["graph_uri"]) # Delete an ontology kg.ontology.delete_ontology(cat_onto["ontology_id"], cat_onto["graph_uri"]) # URI resolution works across all ontologies automatically ``` -------------------------------- ### Import Ontology from URL via REST API Source: https://context7.com/mallahyari/keplai/llms.txt Imports an ontology from a given URL. The URL and an optional name for the ontology should be provided in the JSON request body. ```bash # Import ontology from URL curl -X POST http://localhost:8000/api/ontology/import-url \ -H "Content-Type: application/json" \ -d '{"url": "http://xmlns.com/foaf/0.1/", "name": "FOAF"}' ``` -------------------------------- ### Preview Extraction Results Source: https://context7.com/mallahyari/keplai/llms.txt Preview potential triples and entity candidates without persisting them to the knowledge graph. ```python import asyncio from keplai import KeplAI async def preview_example(): kg = KeplAI.start() # Preview extraction (no storage) text = "Alice knows Bob and works at Acme Corporation." preview = await kg.extract_preview(text, mode="open") for t in preview: print(f"Triple: {t['subject']} --{t['predicate']}--> {t['object']}") print(f" Subject candidates: {t['subject_candidates']}") print(f" Object candidates: {t['object_candidates']}") # Output shows potential entity matches from vector store kg.stop() asyncio.run(preview_example()) ``` -------------------------------- ### POST /api/ontology/propose Source: https://github.com/mallahyari/keplai/blob/main/docs/plans/2026-03-15-graphai-implementation-plan.md Proposes an ontology schema based on provided text. ```APIDOC ## POST /api/ontology/propose ### Description Analyzes text to propose classes and properties for the ontology. ### Method POST ### Endpoint /api/ontology/propose ### Request Body - **text** (string) - Required - The text to analyze for schema proposal. ### Response #### Success Response (200) - **classes** (array) - Proposed classes. - **properties** (array) - Proposed properties. ``` -------------------------------- ### Query with Natural Language Explanation Source: https://context7.com/mallahyari/keplai/llms.txt Retrieve query results accompanied by a human-readable explanation of the findings. ```python import asyncio from keplai import KeplAI async def explain_example(): kg = KeplAI.start() # Add sample data kg.add("Mehdi", "founded", "BrandPulse") kg.add("Mehdi", "role", "CEO") # Ask with explanation result = await kg.ask_with_explanation("What is Mehdi's role?") print(f"SPARQL: {result['sparql']}") print(f"Results: {result['results']}") print(f"Explanation: {result['explanation']}") # Output includes a natural language explanation like: # "The query found that Mehdi has the role of CEO based on the asserted # triple in the knowledge graph." kg.stop() asyncio.run(explain_example()) ``` -------------------------------- ### Manual Graph Addition and AI Extraction Source: https://github.com/mallahyari/keplai/blob/main/prd.md Shows how to manually add data to the graph and then use AI to extract and store information from unstructured text, including auto-disambiguation. ```python # 3. Manual Graph addition graph.add("Mehdi", "founded", "BrandPulse") # 4. AI-Powered Extraction with Auto-Disambiguation text = "Mehdi established a new SaaS startup called BrandPulse Analytics in 2023." # (Under the hood: Disambiguator realizes "BrandPulse Analytics" is "BrandPulse") graph.extract_and_store(text) ``` -------------------------------- ### POST /api/extract/preview Source: https://context7.com/mallahyari/keplai/llms.txt Previews extraction results without storing them in the knowledge graph. ```APIDOC ## POST /api/extract/preview ### Description Previews extraction results without storing them in the knowledge graph. ### Method POST ### Endpoint /api/extract/preview ### Request Body - **text** (string) - Required - The input text to process. - **mode** (string) - Required - The extraction mode (e.g., "open"). ### Request Example { "text": "Alice knows Bob.", "mode": "open" } ### Response #### Success Response (200) - **subject** (string) - The extracted subject. - **predicate** (string) - The extracted predicate. - **object** (string) - The extracted object. - **subject_candidates** (array) - List of subject candidates. - **object_candidates** (array) - List of object candidates. ``` -------------------------------- ### Strict Extraction Mode with Predefined Schema Source: https://github.com/mallahyari/keplai/blob/main/prd.md Illustrates the 'strict' extraction mode where the AI is constrained to use a predefined schema, mapping natural language terms to the defined properties. ```python # 3. Strict Extraction (AI is forced to use your exact schema) graph.ontology.define_class("Person") graph.ontology.define_class("Company") graph.ontology.define_property("founded", domain="Person", range="Company") text = "Mehdi started a SaaS startup called BrandPulse." # The LLM is forced to map "started" to "founded" because of the strict JSON schema. graph.extract_and_store(text, mode="strict") ``` -------------------------------- ### Extract and Preview Triples via REST API Source: https://context7.com/mallahyari/keplai/llms.txt Use these endpoints to extract triples from text and store them or preview the results without persistence. ```bash curl -X POST http://localhost:8000/api/extract \ -H "Content-Type: application/json" \ -d '{"text": "Albert Einstein was born in Germany and developed relativity.", "mode": "open"}' ``` ```bash curl -X POST http://localhost:8000/api/extract/preview \ -H "Content-Type: application/json" \ -d '{"text": "Alice knows Bob.", "mode": "open"}' ``` -------------------------------- ### Execute Raw SPARQL Queries Source: https://context7.com/mallahyari/keplai/llms.txt Run custom SPARQL SELECT queries directly against the graph. Queries are restricted to read-only operations. ```python from keplai import KeplAI kg = KeplAI.start() # Add sample data kg.add("Mehdi", "founded", "BrandPulse") kg.add("Alice", "worksAt", "BrandPulse") # Execute raw SPARQL (read-only enforced) sparql = """ PREFIX entity: PREFIX ontology: SELECT ?person ?predicate ?object WHERE { GRAPH ?g { ?person ?predicate ?object . FILTER(STRSTARTS(STR(?person), STR(entity:))) } } LIMIT 10 """ results = kg.nlq.execute_sparql(sparql) for row in results: print(row) ``` -------------------------------- ### POST /api/query/ask Source: https://github.com/mallahyari/keplai/blob/main/docs/plans/2026-03-15-graphai-implementation-plan.md Executes a natural language query against the knowledge graph. ```APIDOC ## POST /api/query/ask ### Description Processes a natural language question and returns results along with the generated SPARQL query. ### Method POST ### Endpoint /api/query/ask ### Request Body - **question** (string) - Required - The natural language question to ask. ### Response #### Success Response (200) - **results** (object) - The query results. - **sparql** (string) - The generated SPARQL query. ``` -------------------------------- ### Manage Multiple Ontologies Source: https://context7.com/mallahyari/keplai/llms.txt Handle multiple named graphs, list imported ontologies, and perform cross-namespace URI resolution. ```python from keplai import KeplAI kg = KeplAI.start() # Import multiple ontologies cat_onto = kg.ontology.load_rdf("cat_ontology.ttl", name="Cat Ontology") foaf = kg.ontology.load_url("http://xmlns.com/foaf/0.1/", name="FOAF") # List all imported ontologies ontologies = kg.ontology.list_ontologies() for ont in ontologies: print(f"{ont['name']}: {ont['classes_count']} classes, {ont['properties_count']} props") print(f" ID: {ont['id']}") print(f" Graph: {ont['graph_uri']}") print(f" Imported: {ont['import_date']}") # Get schema for a specific ontology schema = kg.ontology.get_schema(graph_uri=cat_onto["graph_uri"]) # Delete an ontology (removes graph and metadata) kg.ontology.delete_ontology( ontology_id=cat_onto["ontology_id"], graph_uri=cat_onto["graph_uri"] ) # URI resolution works across all ontologies automatically # If "owns" is defined in cat_ontology, it resolves to cat:owns kg.add("Mehdi", "owns", "Easter") # Auto-resolves predicate URI kg.stop() ``` -------------------------------- ### Hybrid Drafting with Ontology Proposal Source: https://github.com/mallahyari/keplai/blob/main/prd.md Shows the 'hybrid drafting' mode where the AI analyzes text and proposes a schema (classes and properties) for the developer to review and approve. ```python # 2. Hybrid Drafting (AI proposes a schema for you to review) proposed_schema = graph.analyze_and_propose_ontology("Mehdi started BrandPulse in 2023. Sarah put $50k into the business.") print(proposed_schema) # Output: { classes: ['Person', 'Company'], properties:['founded', 'invested_in'] } ``` -------------------------------- ### Schema Definition using Pythonic Syntax Source: https://github.com/mallahyari/keplai/blob/main/docs/plans/2026-03-15-graphai-implementation-plan.md Defines classes and properties for the ontology using a Pythonic interface. This allows for programmatic schema creation. ```python graph.ontology.define_class("Company") graph.ontology.define_class("Person") graph.ontology.define_property("founded", domain="Person", range="Company") ``` -------------------------------- ### POST /api/ontology/upload Source: https://github.com/mallahyari/keplai/blob/main/README.md Uploads an RDF file to define or update the ontology. ```APIDOC ## POST /api/ontology/upload ### Description Uploads an RDF file to define or update the ontology. ### Method POST ### Endpoint /api/ontology/upload ### Request Body - **file** (file) - Required - The RDF file to upload (multipart/form-data) ``` -------------------------------- ### Define Ontology Properties in KeplAI Source: https://context7.com/mallahyari/keplai/llms.txt Create object and datatype properties with domain and range constraints. Use these to define relationships between classes and link entities to literals. ```python from keplai import KeplAI kg = KeplAI.start() # Define classes first kg.ontology.define_class("Person") kg.ontology.define_class("Company") # Define object property (links entities) kg.ontology.define_property("founded", domain="Person", range="Company") kg.ontology.define_property("worksAt", domain="Person", range="Company") # Define datatype property (links to literals) # Supported datatypes: string, integer, int, float, double, boolean, date, datetime kg.ontology.define_property("name", domain="Person", range="string") kg.ontology.define_property("age", domain="Person", range="integer") kg.ontology.define_property("birthDate", domain="Person", range="date") # List all properties properties = kg.ontology.get_properties() for prop in properties: print(f"{prop['name']}: {prop['domain']} -> {prop['range']}") # Output: # founded: Person -> Company # worksAt: Person -> Company # name: Person -> string # Get full schema schema = kg.ontology.get_schema() print(f"Classes: {len(schema['classes'])}, Properties: {len(schema['properties'])}") # Remove a property kg.ontology.remove_property("age") kg.stop() ``` -------------------------------- ### Define Ontology Classes Source: https://context7.com/mallahyari/keplai/llms.txt Manages OWL classes programmatically using the `OntologyManager`. Allows defining, listing, and removing classes. Classes are stored with proper RDF typing and labels. ```python from keplai import KeplAI kg = KeplAI.start() # Define classes kg.ontology.define_class("Person") kg.ontology.define_class("Company") kg.ontology.define_class("Product") # List all classes classes = kg.ontology.get_classes() for cls in classes: print(f"Class: {cls['name']} ({cls['uri']})") # Output: # Class: Person (http://keplai.io/ontology/Person) # Class: Company (http://keplai.io/ontology/Company) # Class: Product (http://keplai.io/ontology/Product) # Remove a class kg.ontology.remove_class("Product") kg.stop() ```