# SAG

> Self-hosted knowledge base built on event-entity indexing and SQL-driven retrieval

- Category: Retrieval & Knowledge (RAG) / RAG Frameworks & Platforms
- Language: Python
- Licence: MIT
- Repository: https://github.com/Zleap-AI/SAG
- Website: https://zleap.com
- Canonical page: https://ai-tldr.dev/tools/zleap-sag/
- Updated: 2026-09-23

## In short

SAG is an open-source knowledge base application from Zleap, built on a retrieval architecture of the same name (SQL-Retrieval Augmented Generation with Query-Time Dynamic Hyperedges). You upload documents once; SAG parses them to Markdown, splits them into chunks, embeds them, extracts events and entities, and keeps every retrieval result linked to the original text. It sits in the RAG Frameworks & Platforms category of the Retrieval & Knowledge (RAG) tools and is open-source, written in Python and licensed MIT.

## Overview

SAG is an open-source knowledge base application from Zleap, built on a retrieval architecture of the same name (SQL-Retrieval Augmented Generation with Query-Time Dynamic Hyperedges). You upload documents once; SAG parses them to Markdown, splits them into chunks, embeds them, extracts events and entities, and keeps every retrieval result linked to the original text. From there you can search across sources, inspect the event-entity graph, ask an agent questions that come back with clickable citations, or expose the same knowledge to other applications.

The retrieval design is the project's own. Each chunk becomes one semantically complete event plus several lightweight entities, stored in relational tables alongside vector and full-text indexes. At query time SAG finds seed entities and events, uses SQL joins over shared entities to expand into a local candidate set, and builds only the hyperedges relevant to that query, so there is no global graph to construct or rebuild and new documents are added incrementally. The output is always the original evidence chunks. The project reports, in its arXiv paper, an average Recall@5 of 90.07% and F1 of 72.96% across HotpotQA, 2WikiMultiHopQA and MuSiQue, with reproduction scripts in a separate SAG-Benchmark repository.

The app is local-first and single-user by default: it runs on SQLite and LanceDB with no external database, and can move to PostgreSQL/pgvector, MySQL, OceanBase or Elasticsearch backends. It is split into three independently usable layers: a Next.js web UI (also packaged as a desktop app for macOS on Apple Silicon and Windows x64), a FastAPI backend with REST/OpenAPI, an OpenAI-compatible chat endpoint and an MCP server, and the zleap-sag Python engine on PyPI that you can embed in your own service.

## What it does

- Background ingestion of Markdown, text, PDF and Office files: parsing via MarkItDown (or MinerU for PDFs when configured), chunking, embedding and event/entity extraction
- Global or source-scoped search in two modes: Fast (vector similarity) and Precise (entity relationships plus LLM reranking), with every result openable back to its original chunk
- A default agent that answers multi-turn questions from the sources you bind to it, streaming replies with clickable citations
- Graph and 3D views of the event-entity index, plus an Explore mode for moving through events, entities and their relationships
- Integration surfaces: a self-hosted REST/OpenAPI backend, an OpenAI-compatible Chat Completions endpoint that adds a sag.citations field, an MCP server, a Dify external knowledge base endpoint and the sag CLI for wiring MCP into Codex or Claude Code
- Pluggable storage behind one EngineConfig: SQLite + LanceDB locally, or PostgreSQL/pgvector, MySQL, OceanBase and Elasticsearch in production

## Getting started

The README offers a desktop installer on GitHub Releases, a Docker Compose self-hosted setup, and the standalone zleap-sag Python engine. The steps below follow the Docker path, then show the MCP CLI and the Python engine. The UI boots without model credentials, but indexing needs an embedding endpoint and extraction and answers need an LLM.

1. Start SAG with Docker Compose

   Requires Docker Desktop, or Docker Engine with Compose v2. When both services are healthy, the web app is at http://localhost:3000 and the API docs at http://localhost:8000/docs. The default Compose file binds to 127.0.0.1 in local (name-only) auth mode, so do not expose it to an untrusted network without switching SAG_AUTH_MODE to password.

```bash
git clone https://github.com/Zleap-AI/SAG.git
cd SAG
docker compose up -d --build
```

2. Configure models and add documents

   Enter a name to create the local identity, then use the 302.AI quick setup or open Settings → Models to configure any OpenAI-compatible LLM and embedding endpoint. Create a source, upload documents, wait until their status is Ready, then search or start a cited conversation.

3. Connect SAG to your coding agent over MCP

   The official CLI (Node.js 20.19 or later) discovers the local Docker container, checks that the MCP server responds and mounts it into Codex or Claude Code.

```bash
npm install --global @zleap-ai/sag-cli
sag mcp test
sag agent connect claude-code
sag agent status
```

4. Or embed the Python engine directly

   The zleap-sag package (Python 3.11+) runs the full ingest, extract and search lifecycle with local storage created under ./.zleap/. Point it at any OpenAI-compatible endpoint.

```python
pip install zleap-sag

# main.py
import asyncio
from zleap.sag import DataEngine, EngineConfig
from zleap.sag.config import EmbeddingConfig, LLMConfig

async def main() -> None:
    config = EngineConfig(
        llm=LLMConfig(
            api_key="sk-...",
            base_url="https://your-openai-compatible-host/v1",
            model="qwen3.6-flash",
        ),
        embedding=EmbeddingConfig(model="bge-large-en-v1.5"),
        language="en",
    )
    async with DataEngine(config) as engine:
        await engine.ingest("knowledge.md")
        await engine.extract()
        result = await engine.search(
            "Why is SAG effective for multi-hop retrieval?",
            strategy="multi",
            top_k=5,
        )
        for section in result.sections:
            print(section.get("content", "")[:200])

asyncio.run(main())
```

## When to use it

- Run a private, self-hosted knowledge base over your own documents where every answer and search hit can be traced back to the exact source chunk
- Give Claude Code, Codex or another MCP host retrieval over a document collection through SAG's MCP server and CLI
- Drop cited retrieval into an existing app by calling SAG as an OpenAI-compatible model, or use it as an external knowledge base for Dify
- Build multi-hop retrieval into your own Python service with the zleap-sag engine, starting on SQLite and LanceDB and moving to PostgreSQL/pgvector later

## Version history

- 2026-09-23 v1.8.11: Removes automatic migration of legacy knowledge-base storage: when incompatible old data is detected, SAG keeps a backup, accounts and model settings and asks the user to confirm a fresh rebuild and re-upload documents.
