zilan README

README проекта с github.com/lxcshine/zilan. Одним файлом markdown: README.md.

Zilan 知澜

Where knowledge converges into waves — bring every document to life

Minimalist aesthetics × Deep parsing × Autonomous reasoning — an intelligent knowledge hub

License Version Deployment Design Language

| English | 简体中文 |

Overview • Highlights • Architecture • Feature Overview • Getting Started • Docs • Developer Guide

💡 Zilan — Where Knowledge Converges: a Minimalist Knowledge Hub Unifying RAG, Agent Reasoning, and Auto-Wiki

📌 Overview

Zilan (知澜) is an LLM-powered knowledge management and intelligent Q&A platform with a minimalist product experience that unifies RAG quick Q&A, ReAct agent reasoning, and auto-generated Wiki knowledge distillation.

Zilan is a thorough re-imagination built on a battle-tested open-source knowledge framework, carrying product genes entirely its own:

On top of that, Zilan inherits engineering capabilities proven through large-scale production use: multi-source ingestion (Feishu / Notion / Yuque / RSS, and growing), 20+ LLM provider integrations, a dozen IM channels, website embed widgets, a 4-tier RBAC role matrix with workspace audit logs, AES-256-GCM credential encryption at rest, full-stack Langfuse observability plus a runtime task-queue governance dashboard, and a fully self-hostable modular architecture — LLMs, vector databases, and storage backends are all swappable, keeping data sovereignty entirely yours.

✨ Highlights

🎨 Minimalist Design Language · An Interface Built for Focus

Principle Details
Dark monochrome brand Brand color stays in the #333 family; interaction states shift luminance only — no flashy gradients, no saturated clashes
Large radii × light shadows A global radius system (starting at 8/10/12px); cards and chat bubbles use feather-light or no shadows
Pure solid backgrounds Pages return to solid colors (light #fafafa / dark #181818) — no textures, no decorative animations
Centered login A single vertical focal point of brand mark + form; every login-irrelevant element removed
Symmetric chat bubbles User-side dark, assistant-side light-gray symmetric rounded bubbles with inline citations and reasoning chains
Responsive Consistent desktop / tablet / mobile experience; dark mode follows the system

📄 Deep Document Parsing · Read Every PDF Properly

Capability Details
Table extraction Detects table boundaries and restores them as Markdown tables, preserving row/column semantics
Formula recognition Extracts mathematical formulas and converts them to LaTeX for fine-grained retrieval in academic and technical docs
Dual-column awareness Detects two-/multi-column layouts and restores the correct reading order
Auto routing Picks light or heavy parsing engines by file size and content profile, balancing throughput and quality
Quality scoring & retry Parse results are auto-scored; short or low-scoring content is retried with a heavier engine
Human review queue Documents that exhaust retries enter a review queue for human-in-the-loop closure

🕸️ GraphRAG-Enhanced Retrieval

Entities and relations are extracted into Neo4j at ingest time to build a knowledge graph; at query time, community summaries provide the global view while local subgraph retrieval supplies neighborhood detail — fused with BM25 / dense vector recall via RRF, markedly improving answers to multi-hop and cross-document aggregation questions.

🧠 Memory & Knowledge Distillation

Toward a more personal, context-aware knowledge assistant, Zilan is building a three-layer memory architecture:

Supporting mechanics: memory is extracted asynchronously after each session via the Asynq task queue (fact triples / to-dos / emotional feedback); injection scores each memory as score = semantic similarity × time decay × (1 + log(access count)) and loads the Top-K into the system prompt; high-value conversations (favorited or heavily followed-up) auto-distill into Wiki pages linked back to the source session.

The dedicated My Memory page makes long-term memory fully transparent and controllable:

All operations are isolated per user and available in four languages (zh-CN / en-US / ru-RU / ko-KR) — GDPR / privacy compliant by design.

🗂️ Four Structured Memory Modules (Soul / User / Memory / Agent)

Beyond a flat fact list, long-term memory is organized into four semantic modules — so the assistant not only remembers facts, but also knows who it should be, who you are, and how to work best with you:

Module What it holds What you see
Soul Read-only global persona + your style directives ("call me Zhang Gong", "answer in bullet points") Persona card + directive list; directives are auto-extracted from chat and injected into every answer
User Stable attributes about you (identity / role / preferences) Profile card with grouped sections, a completeness meter, and drill-down into the memory stream
Memory The full memory stream: all facts, to-dos, feedback, plus L2 session summaries The original category-filtered list (as above)
Agent Distilled skills — reusable know-how learned from your feedback Skill cards + a feedback wall showing which feedback has been upgraded into a skill

How it works:

Zero schema change: the modules are a code-level mapping over the existing memory_facts table, so all existing memory management (edit / delete / clear / switch) applies unchanged.

🧠 Context Management · IMA-Grade Five-Layer Intelligent Architecture

Zilan completely rethinks how conversation context is organized, moving beyond a naive sliding window to a precise token budget + five-layer context architecture, so every answer spends its budget where it matters:

Enabled globally via config/config.yaml, and customizable per tenant:

conversation:
  context_manager:
    max_tokens: 0                  # 0 = resolve the model's window automatically
    compression_strategy: "smart"  # "sliding_window" (default) or "smart" (five-layer)
    recent_message_count: 0        # 0 = use the system default recent rounds
    summarize_threshold: 0         # 0 = 3x the recent window (deep fetch for summarization)

🔐 Independent Brand · Independent Protocol

Product name, UI marks, browser titles, storage keys, JWT audience, webhook signature header, and embed SDK are unified under the Zilan namespace — a fully self-owned product identity.

📱 Interface Showcase

💬 Intelligent Q&A Conversation
Intelligent Q&A Conversation
📖 Wiki Browser
Wiki Browser
🕸️ Wiki Knowledge Graph
Wiki Knowledge Graph
🤖 Agent Mode · Tool Call Process
Agent Mode Tool Call Process
⚙️ Conversation Settings
Conversation Settings
🔭 Observability · Langfuse Tracing
Observability Langfuse Tracing

🖥️ Real Product Screenshots

💬 New Chat
New Chat
📚 Knowledge Base
Knowledge Base
📄 Documents
Documents
🤖 Agent
Agent
🧠 My Memory
My Memory

🏗️ Architecture

zilan-architecture

Fully modular pipeline from document parsing, vectorization, and retrieval to LLM inference — every component is swappable and extensible. Supports local / private cloud deployment with full data sovereignty and a zero-barrier Web UI for quick onboarding.

🧩 Feature Overview

Intelligent Conversation

Capability Details
Intelligent Reasoning ReACT progressive multi-step reasoning, autonomously orchestrating knowledge retrieval, MCP tools, and web search
Quick Q&A RAG-based Q&A over knowledge bases for fast and accurate answers
Wiki Mode Agent-driven auto-generation of structured, interlinked markdown Wiki pages from raw documents
Tool Calling Built-in tools, MCP tools (incl. OAuth2 remote services, mid-conversation OAuth), web search; @Skill / @MCP mentions to scope the agent runtime per turn
Conversation Strategy Online Prompt editing, retrieval threshold tuning, multi-turn context awareness, per-agent citation output toggle
Suggested Questions Auto-generated question suggestions and after-answer follow-ups based on knowledge base content
Temporary Attachments Session-scoped image / document uploads with async parsing for one-off Q&A, with a combined image + attachment limit
Citations & RAG Progress Inline citation popovers and a references drawer (web / KB source distinction), shared markdown rendering, and stage-by-stage RAG pipeline progress in chat
Session Management Filter and group sidebar sessions by source (Web / IM / Embed), with inline session-title rename
Memory & Personalization Three-layer memory architecture (see Highlights): async fact extraction, scored recall injection, and a dedicated My Memory page structured into four modules (Soul / User / Memory / Agent) for browsing / editing / deleting memories with a global memory switch

Knowledge Management

Capability Details
Knowledge Base Types FAQ / Document / Wiki with folder import, URL import, multi-tag management, and online entry
Deep Parsing Pipeline PDF table extraction / formula recognition / dual-column awareness / auto routing / quality-scored retry / human review queue
Per-Upload Process Config Override parser, chunking, multimodal (VLM / ASR), graph extraction, and question generation per upload batch via upload-confirm dialog or process_config API; reparse with new settings
Batch Reparse Re-queue parsing for multiple documents at once with optional per-batch process_config
Data Source Import Auto-sync from Feishu / Notion / Yuque / RSS feeds (more data sources coming soon); incremental and full sync
Document Formats PDF / Word / Txt / Markdown / HTML / EPUB / MHTML / Images / CSV / Excel / PPT / JSON
Retrieval Strategies BM25 sparse / Dense retrieval / GraphRAG (community summary + local subgraph) / parent-child chunking / HNSW-accelerated pgvector (1024-dim) / multi-dimensional indexing
Batch Selection Marquee drag-select multiple documents in the KB list for batch operations
E2E Testing Full-pipeline visualization with recall hit rate, BLEU / ROUGE metric evaluation

Integrations & Extensions

Capability Details
LLMs OpenAI / Azure OpenAI / Anthropic (Claude) / DeepSeek / Qwen (Alibaba Cloud) / Zhipu / Hunyuan / Doubao (Volcengine) / Gemini / MiniMax / NVIDIA / Novita AI / SiliconFlow / OpenRouter / Requesty / Ollama
Embeddings Ollama / BGE / GTE / Zhipu / OpenAI-compatible APIs
Vector DBs PostgreSQL (pgvector) / Elasticsearch / OpenSearch / Milvus / Weaviate / Qdrant / Apache Doris / Tencent VectorDB
Object Storage Local / Tencent COS / Volcengine TOS / MinIO / AWS S3 / Alibaba Cloud OSS / Kingsoft Cloud KS3 / Huawei Cloud OBS; multiple storage instances per workspace with per-KB binding and a default instance
IM Channels WeCom / Feishu / Lark (Feishu International) / QQBot / Slack / Telegram / DingTalk / Mattermost / WeChat / Yunzhijia
Website Embed Publish agents to any site via zilan-widget.js with domain allowlists, rate limits, and secure-mode token exchange
Web Search DuckDuckGo / Bing / Google / Tavily / Baidu / Ollama / SearXNG / Keenable / Zhipu AI
API Integration Scoped API keys (capability-level grants + per-KB restriction + throttled last-used tracking) with an API integration playground; MCP OAuth and embed sessions isolated per principal

Platform

Capability Details
Deployment Local / Docker / Kubernetes (Helm) with private and offline support
UI Web UI / RESTful API / Website Embed Widget; the Zilan minimalist design language covers the whole journey
Access Control Workspace RBAC with 4-tier role matrix (Owner / Admin / Contributor / Viewer), per-KB resource ownership, per-workspace audit log, invite-only workspaces, tenantless provisioning & gated self-service workspace creation, admin password reset (session revocation), cross-workspace superuser, scoped API keys
Security AES-256-GCM at-rest encryption for API keys and MCP / data-source credentials with graceful key rotation; gRPC TLS + Token between app and docreader; Redis TLS; SSRF-safe HTTP client (data sources, URL import, redirect chains); secret redaction in responses; sandbox isolation for agent skills
Observability Integrated Langfuse (sole tracing backend) for ReAct loops, token tracking, tool calls, and pipeline tracing; built-in Langfuse-style document parsing trace timeline with stage-by-stage progress; system-admin runtime task-queue dashboard (queue depth, per-model concurrency, failed-task inspection & manual retry)
Task Management MQ async tasks with per-stage worker-pool governance (core / post-process / enrichment / maintenance + elastic shared pool, plus an independent Wiki pool) and per-model background concurrency governors; automatic database migration on version upgrade
Model Management Centralized config, declarative built-in models via YAML, per-knowledge-base model selection, per-model thinking-mode and embedding-dimension overrides, interactive model test debugger, multi-workspace built-in model sharing, Zilan Cloud hosted models and parsing

🚀 Getting Started

🛠 Prerequisites

📦 Installation & Launch

git clone https://github.com/lxcshine/zilan.git zilan
cd zilan
cp .env.example .env   # Edit .env as needed, see comments in the file
docker compose up -d   # Start core services

For a production deployment (PostgreSQL primary/replica, Redis, Neo4j, MinIO, nginx with landing page), jump to Production Deployment.

Once started, visit http://localhost to get started.

To use a local Ollama model, run ollama serve > /dev/null 2>&1 & first.

⚙️ First-Run Configuration (.env)

.env.example is organized into commented sections (A runtime / B data & storage / C vector search / D models / E document parsing / F auth & security). Most entries can stay empty to use defaults. For a first deployment, focus on:

Section When needed Notes
B1. Database External DB only docker compose up -d ships with PostgreSQL and works out of the box; for your own DB, set DB_DRIVER / DB_HOST / DB_PORT / DB_USER / DB_PASSWORD
F1. SYSTEM_AES_KEY Change in production 32-byte static encryption key for API keys / MCP / data-source credentials. The default is for evaluation only; encrypted data is unrecoverable if the key is lost
D1 / D2. Models Before first use Configure any provider's API key via Web UI after startup, or declare built-in models via config/builtin_models.yaml (see file comments)
F2.5. Verification codes Optional Registration/login verification channels, see below
F2.6. Backup & recovery Optional Daily user-data snapshots into an independent backup store, see below

Registration / Login Verification Channels (optional, log dev mode by default)

Registration and login support phone / email dual channels with automatic format validation, human verification (slider puzzle or digit image, switch via WEKNORA_AUTH_CAPTCHA_TYPE), and passwords must contain uppercase, lowercase and digits. Unconfigured channels run in log mode — codes are written to server logs only (search auth/email:log / auth/sms:log), so the full flow works with zero configuration.

To actually send email codes (QQ Mail example):

WEKNORA_AUTH_EMAIL_PROVIDER=smtp            # log=log only (default) / smtp=real delivery
WEKNORA_AUTH_EMAIL_SMTP_PRESET=qq           # Provider preset: fills host/port/TLS automatically
[email protected] # Sender mailbox
WEKNORA_AUTH_EMAIL_SMTP_PASSWORD=<SMTP auth code> # Not the mailbox login password

Backup & Recovery (optional, off by default)

Daily automatic snapshots of every workspace's data: metadata is exported per-workspace as logical jsonl.gz streams, file-tier objects are copied into an independently configured backup store, and snapshots are pruned automatically by a simplified GFS retention policy (7 daily / 4 weekly / 6 monthly by default). Restores verify the SHA-256 manifest of every object before writing anything.

WEKNORA_BACKUP_ENABLED=true                  # master switch
WEKNORA_BACKUP_STORAGE_PROVIDER=local        # local / minio / s3
WEKNORA_BACKUP_STORAGE_LOCAL_PATH=/data/backups
# --- or an S3-compatible target (MUST be a different instance/bucket
#     than the primary storage — backing up onto the primary defeats the purpose) ---
# WEKNORA_BACKUP_STORAGE_ENDPOINT=minio.example.com:9000
# WEKNORA_BACKUP_STORAGE_ACCESS_KEY=...
# WEKNORA_BACKUP_STORAGE_SECRET_KEY=...
# WEKNORA_BACKUP_STORAGE_BUCKET=weknora-backups
WEKNORA_BACKUP_SCHEDULE="0 0 3 * * *"        # 6-field cron, daily 03:00

Once enabled, system admins get a Backup & Recovery section under Settings → System Administration with the last-success status (RPO countdown), snapshot records, per-workspace archive export, and a restore wizard (per-workspace restore into a new -restored- workspace or full-instance disaster recovery, both with a dry-run verification mode).

Restart to apply .env changes: docker compose down && docker compose up -d

🔧 Optional Services (Docker Compose Profiles)

Add --profile flags to enable additional components. Multiple profiles can be combined:

Profile Description Command
(default) Core services docker compose up -d
full All features docker compose --profile full up -d
neo4j Knowledge Graph (Neo4j) docker compose --profile neo4j up -d
minio Object Storage (MinIO) docker compose --profile minio up -d
langfuse Tracing (Langfuse) docker compose --profile langfuse up -d

Combine profiles: docker compose --profile neo4j --profile minio up -d

Stop services: docker compose down

🛠 Local Binary Build & Launch (without Docker)

If you prefer to compile and run the backend binary directly on your Linux host, follow these steps.

1. Install dependencies (SQLite C headers are required — otherwise CGO compilation fails with a missing sqlite3.h):

sudo apt-get update && sudo apt-get install -y libsqlite3-dev build-essential

2. Compile the backend binary Zilan:

CGO_ENABLED=1 go build -o Zilan ./cmd/server

To rename the binary, adjust BINARY_NAME in the Makefile, or just use make build which compiles under that name.

3. Export environment variables and launch:

set -a && source .env && set +a && ./Zilan

4. Start development infrastructure (PostgreSQL / Redis / Neo4j and other dependencies for development/debugging):

docker compose -f docker-compose.dev.yml --profile neo4j up -d

On the first dev start, if you hit a WeKnora-* container-name conflict, clear the leftover container with docker rm -f WeKnora-neo4j-dev.

🌐 Service URLs

Service URL
Landing page (production stack) http://localhost
Web UI / API (production stack) http://localhost:8080
Web UI (local dev stack) http://localhost
Langfuse Tracing http://localhost:3000

🏭 Production Deployment (Step by Step)

docker-compose.prod.yml is the production topology. The commands below take a bare Linux server to a running instance; follow them in order and substitute <your-server> with your own host name or IP address.

Component Service name Port
Landing page (static, single file) edge (nginx) 80
Web UI + API (reverse proxy, load balanced) edge → app replicas 8080
Forward proxy (private networks only) edge (nginx) 3128
PostgreSQL primary (ParadeDB: pgvector + BM25) postgres-primary internal
PostgreSQL streaming replica postgres-replica internal
Redis (streams + asynq task queue) redis internal
Neo4j (knowledge graph) neo4j internal
MinIO (shared object storage) minio internal

In-container nginx always listens on port 80; the host maps 8080 → 80. Host port 80 is reserved for the landing page, which has exactly one button that jumps to 8080.

Step 0 — Server prerequisites

Step 1 — Install Docker Engine and Compose v2

# Install (mainland China: the Aliyun mirror flag keeps the download fast)
curl -fsSL https://get.docker.com | bash -s -- --mirror Aliyun

systemctl enable --now docker

docker --version && docker compose version   # Compose v2 required

If your install only provides the legacy docker-compose binary (v2.x standalone), every command below works unchanged — just replace docker compose with docker-compose.

Step 2 — Add swap (only needed when RAM ≤ 2 GB)

fallocate -l 4G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap sw 0 0' >> /etc/fstab
free -m

Without swap the image build can be killed by the OOM killer on a 2 GB box.

Step 3 — Use a domestic registry mirror (mainland China only)

Docker Hub is usually unreachable from mainland China. Configure a working mirror before pulling anything:

cat > /etc/docker/daemon.json <<'EOF'
{
  "registry-mirrors": [
    "https://docker.1panel.live",
    "https://docker.m.daocloud.io"
  ],
  "log-driver": "json-file",
  "log-opts": { "max-size": "50m", "max-file": "3" }
}
EOF

systemctl restart docker
docker info | grep -A3 'Registry Mirrors'   # should list both mirrors

docker pull alpine:3.20                     # smoke test

Skip this step outside mainland China.

Step 4 — Get the code and build the frontend bundle

git clone https://github.com/lxcshine/zilan.git zilan
cd zilan

# The frontend image is a static nginx image built from `frontend/dist`,
# so the bundle has to exist before `docker compose build` runs.
./scripts/build_frontend_dist.sh

build_frontend_dist.sh needs Node.js 20+ and npm. If you would rather not install Node on the host, build the bundle in a container instead:

docker run --rm -v "$PWD/frontend:/app" -w /app node:20-bookworm \
  sh -c "npm ci && npm run build"

Step 5 — Create the production .env

cp .env.prod.example .env
chmod 600 .env

The template contains placeholders only — every secret must be replaced. Generate them:

# 32-hex-character random values (one per service)
for k in DB_PASSWORD REPLICATION_PASSWORD REDIS_PASSWORD NEO4J_PASSWORD MINIO_SECRET_ACCESS_KEY; do
  echo "$k=$(openssl rand -hex 16)"
done

# SYSTEM_AES_KEY must be exactly 32 characters (AES-256)
echo "SYSTEM_AES_KEY=$(openssl rand -hex 16)"
# JWT_SECRET: any long random string
echo "JWT_SECRET=$(openssl rand -hex 32)"

Then fill in .env:

Variable Required Notes
DB_PASSWORD / REPLICATION_PASSWORD ✅ PostgreSQL app user and streaming-replication user
REDIS_PASSWORD / NEO4J_PASSWORD ✅ Redis and Neo4j auth
MINIO_SECRET_ACCESS_KEY ✅ MinIO root secret (≥ 8 chars)
SYSTEM_AES_KEY ✅ Exactly 32 characters. Encrypts stored API keys and data-source credentials. Losing it makes that data unrecoverable — keep an offline copy
JWT_SECRET ✅ Session token signing key
LLM_BASE_URL / LLM_API_KEY / LLM_MODEL_NAME ✅ Chat model (any OpenAI-compatible endpoint)
VLM_BASE_URL / VLM_API_KEY / VLM_MODEL_NAME ✅ Vision model — required for scanned-PDF OCR
EMBEDDING_BASE_URL / EMBEDDING_API_KEY / EMBEDDING_MODEL_NAME / EMBEDDING_DIMENSION ✅ Retrieval embeddings. EMBEDDING_DIMENSION must match the model's real output size
DISABLE_REGISTRATION first boot Set false for the very first boot so you can create the admin account, then set true (see Step 8)
WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL first boot Email you will register; it is auto-promoted to system administrator on startup
FRONTEND_BASE_URL / APP_EXTERNAL_URL optional Public origin of your instance, e.g. http://<your-server>:8080
DB_REPLICAS optional postgres-replica:5432 enables read/write splitting — see the note below

Read/write splitting: DB_REPLICAS routes non-transactional SELECTs to the replica. Leave it empty when running the ParadeDB Community image: BM25 keyword search cannot be served from a standby (SQLSTATE 0A000) unless the binary is built with the "keyword search always hits primary" patch included in this repository. With the official image, empty is the correct value.

Step 6 — Start the stack

docker compose -f docker-compose.prod.yml up -d --build

The first build compiles Go, installs Python dependencies and pulls Neo4j/MinIO; on 2 vCPU expect 40–90 minutes. Watch progress:

docker compose -f docker-compose.prod.yml ps
docker logs -f zilan-app-1

To speed things up on a small machine, build one service at a time (services are built strictly in sequence):

COMPOSE_PARALLEL_LIMIT=1 docker compose -f docker-compose.prod.yml build app
COMPOSE_PARALLEL_LIMIT=1 docker compose -f docker-compose.prod.yml build docreader

Step 7 — Verify the deployment

# 1. Landing page on port 80 and the app on 8080
curl -s -o /dev/null -w 'landing %{http_code}\n' http://127.0.0.1/
curl -s -o /dev/null -w 'app     %{http_code}\n' http://127.0.0.1:8080/healthz

# 2. All containers healthy
docker compose -f docker-compose.prod.yml ps

# 3. Streaming replication is up
docker exec zilan-postgres-primary psql -U postgres -d zilan \
  -c "select client_addr, state, sync_state from pg_stat_replication;"

# 4. The replica really is read-only (must fail with a read-only transaction error)
docker exec zilan-postgres-replica psql -U postgres -d zilan -c "select pg_is_in_recovery();"
docker exec zilan-postgres-replica psql -U postgres -d zilan -c "create table _probe(id int);"

# 5. Startup wiring: read/write splitting, tracing, migrations
docker logs zilan-app-1 2>&1 | grep -E '\[db\]|\[reqtrace\]|migrated from'

Step 8 — Create the first system administrator

The stack ships with no default account. On the very first boot only:

# .env
DISABLE_REGISTRATION=false
[email protected]
docker compose -f docker-compose.prod.yml up -d app

# Register through the UI (http://<your-server>:8080) or the API:
curl -s -X POST http://127.0.0.1:8080/api/v1/auth/register \
  -H 'Content-Type: application/json' \
  -d '{"username":"admin","email":"[email protected]","password":"ChangeMe2026"}'

Restart the app so bootstrap promotes that account:

docker compose -f docker-compose.prod.yml restart app
docker logs zilan-app-1 2>&1 | grep -i 'promoted.*system admin'

Now close public registration:

sed -i 's/^DISABLE_REGISTRATION=.*/DISABLE_REGISTRATION=true/' .env
docker compose -f docker-compose.prod.yml up -d app

Adding a second (non-admin) user afterwards: temporarily set DISABLE_REGISTRATION=false, register, then set it back to true. Each registration creates its own workspace; to share documents, invite the user from Workspace → Members instead.

Step 9 — Landing page and ports

The landing page is already part of the stack (landing/index.html, mounted read-only into edge, served on host port 80). Only one file needs to change when you edit copy:

# edit locally, then re-upload — no container restart needed (HTML is served with no-cache)
scp landing/index.html <user>@<your-server>:/opt/zilan/landing/index.html

If host port 80 is already taken, override the mapping:

# .env
LANDING_HTTP_PORT=8081

Step 10 — Scale the API horizontally

app has no fixed container name, so it can be scaled; nginx re-resolves the service name every 10 s through Docker DNS:

docker compose -f docker-compose.prod.yml up -d --scale app=3

# requirements for multi-replica:
#   STORAGE_TYPE=minio   (an `app` replica cannot share local disk)
#   STREAM_MANAGER_TYPE=redis
#   DB_REPLICAS may stay empty; read/write splitting is orthogonal

Keep DB_MAX_OPEN_CONNS sensible: replicas × max_open must stay below PostgreSQL's max_connections.

Day-2 operations

# logs
docker compose -f docker-compose.prod.yml logs -f app
tail -f /var/lib/docker/volumes/zilan_app-logs/_data/zilan.log

# config change + restart (only the affected service)
docker compose -f docker-compose.prod.yml up -d app

# upgrade: pull new code, rebuild only what changed
git pull
./scripts/build_frontend_dist.sh
docker compose -f docker-compose.prod.yml up -d --build app docreader frontend

# database backup (requires a separate backup target — never the primary volume)
docker exec zilan-postgres-primary pg_dump -U postgres -d zilan -Fc > zilan-$(date +%F).dump

# stop everything (data lives in named volumes and survives)
docker compose -f docker-compose.prod.yml down

Never run down -v on a production host — -v deletes the volumes, including the primary database.

Troubleshooting

Symptom Cause Fix
docker pull hangs at 0 B/s Docker Hub unreachable Configure mirrors (Step 3)
Build killed, exit code 137 Out of memory while compiling Add swap (Step 2), build services one at a time
COPY /app/Zilan: not found Binary name mismatch BINARY_NAME in Makefile must equal the name in docker/Dockerfile.app
App starts but keyword search errors with SQLSTATE 0A000 Read replica serving a ParadeDB BM25 index Set DB_REPLICAS= (empty)
no procedure with the name apoc.periodic.iterate Neo4j APOC plugin missing Put apoc-<version>-core.jar into docker/neo4j/plugins/ and restart neo4j
Registration fails with idx_users_phone duplicate key Empty phone stored as '' under a unique index update users set phone = null where phone = '';
nginx: [warn] worker_connections exceed open file resource limit Low nofile in the container Harmless; raise --ulimit nofile if you need > 1024 concurrent connections

Knowledge Graph

Zilan converts documents into knowledge graphs that surface how different passages relate to each other. Once enabled, the system analyzes and builds a semantic relation network inside each document — helping users understand the content while providing structural support for indexing and retrieval, improving both relevance and breadth of search results.

See the Knowledge Graph Configuration Guide for setup details.

MCP Server

Please refer to the MCP Configuration Guide for the necessary setup.

📘 Docs

Troubleshooting FAQ: Troubleshooting FAQ

Detailed API documentation is available at: API Docs

Product plans and upcoming features: Roadmap

🧭 Developer Guide

If you need to frequently modify code, you don't need to rebuild Docker images every time! Use fast development mode:

# Start infrastructure
make dev-start

# Start backend (new terminal)
make dev-app

# Start frontend (new terminal)
make dev-frontend

Development Advantages:

Detailed Documentation: Development Environment Quick Start

🤝 Customization Guidelines

Zilan is designed for continuous in-house customization and evolution.

Process: Create branch → Commit changes → Merge to mainline

Standards: Format code with gofmt, follow Conventional Commits (feat: / fix: / docs: / test: / refactor:)

🔒 Security Notice

For production deployments, we strongly recommend:

📄 License

This project is licensed under the MIT License. You are free to use, modify, and distribute the code with proper attribution.

zilan (lxcshine/zilan)

Ищем в базе…

Что это?Zilan — платформа управления знаниями и вопросами-ответами на базе LLM, объединяющая быструю RAG-поддержку вопросов-ответов, рассуждения ReAct-агентов и автоматическую дистилляцию знаний в Wiki в одном минималистичном центре знаний.
Это хостируемое веб-приложение или библиотека для импорта в код?Это самостоятельно размещаемое модульное веб-приложение (бэкенд на Go), где провайдеры LLM, векторные базы данных и хранилища — взаимозаменяемые компоненты за браузерным интерфейсом.
Как развернуть Zilan?Проект рассчитан на локальное или частное облачное развёртывание с полным суверенитетом данных; после запуска онбординг ведёт «zero-barrier» Web UI; в комплекте идёт настройка Docker Compose.
С какими источниками данных и провайдерами LLM он работает?Он принимает данные из Feishu, Notion, Yuque и RSS-лент, интегрируется более чем с 20 провайдерами LLM и примерно дюжиной каналов мессенджеров, а для графа знаний использует Neo4j плюс pgvector для векторов памяти.
Всегда ли глубокий парсер документов справляется со сложными PDF?Не всегда — разборы с низкой оценкой автоматически повторяются более тяжёлым движком, а документы, не поддавшиеся после повторов, ставятся в очередь на ручную проверку вместо тихого сбоя.
Могу ли я видеть и удалять то, что Zilan запомнил обо мне?Да, отдельная страница My Memory позволяет каждому пользователю просматривать, редактировать и удалять каждое сохранённое воспоминание или полностью приостановить извлечение памяти; система построена с расчётом на соответствие GDPR.
Что такое поиск, дополненный GraphRAG?При приёме данных сущности и связи извлекаются в Neo4j, образуя граф знаний; во время запроса сводные данные сообществ дают глобальную картину, локальный поиск по подграфам добавляет детали окрестности, и всё это сплавляется с полнотекстовым BM25/плотным векторным поиском через RRF для лучших многошаговых ответов.
Как работает трёхслойная система памяти?L1 — рабочая память текущего разговора, L2 — векторизованное резюме недавних сессий, L3 — долговременная память (профиль, триплеты фактов, задачи), организованная в четыре модуля — Soul, User, Memory и Agent, — добавляемая в системный промпт по оценке релевантности.
Что такое режим Wiki?Агент автоматически дистиллирует ценные разговоры (добавленные в избранное или с активными продолжениями) в структурированные страницы Wiki, которые остаются связанными с исходной чат-сессией.
Какие языки поддерживает интерфейс?Управление памятью и интерфейс доступны на четырёх языках: упрощённом китайском, английском, русском и корейском.
Какие есть похожие проекты?goclaw, m_flow, WeKnora, semantica, carrel, utopia, serviette, LightRAG
Автор
lxcshine
Размер
17 MB
Звёзды
200
Возраст
3 мес
Коммиты · 90 дней