Files
startrail-org--leann/README.md
T
wehub-resource-sync fc77fbf023
CI / build (push) Failing after 1h20m48s
Link Check / link-check (push) Has been cancelled
docs: make Chinese README the default
2026-07-13 10:47:37 +00:00

51 KiB
Executable File
Raw Blame History

Note

本文档由 WeHub 基于上游 README 翻译整理,属于社区翻译,非官方中文文档。
English · 原始项目 · 上游 README
原作者、版权与许可证归属以原始项目及本仓库 LICENSE 文件为准。

LEANN Logo

yichuan-w/LEANN | Trendshift

Python 版本 CI 状态 平台 MIT 许可证 MCP 集成 加入 Slack

参与调查

我们零遥测。这份调查是你告诉我们接下来更想要
GPU 加速还是更多集成的唯一途径。
👉 点击此处投票(约 2 分钟)

💬 加入我们的 Slack 社区!

我们诚挚邀请你加入 LEANN 社区!
👉 加入 LEANN Slack
如果邀请链接已过期或加入遇到问题,请提交 issue,我们会协助你加入!

世界上最小的向量索引。用 LEANN RAG Everything

LEANN 是一款创新的向量数据库,让个人 AI 触手可及。将你的笔记本电脑变成强大的 RAG 系统,可索引并搜索数百万份文档,相比传统方案存储占用减少 97%,且不损失精度

LEANN 通过基于图的选择性重计算高度保留剪枝实现这一目标,按需计算嵌入向量,而非全部存储。架构示意图 → | 论文 →

准备好 RAG Everything 了吗? 将你的笔记本电脑变成个人 AI 助手,可对文件系统邮件浏览器历史聊天记录WeChatiMessage)、智能体记忆ChatGPTClaude)、实时数据SlackTwitter)、代码库*,或外部知识库(例如 6000 万份文档)进行语义搜索——全部在你的笔记本电脑上完成,零云成本,完全隐私。

  • Claude Code 仅支持基础的 grep 风格关键词搜索。LEANN 是一款可即插即用的语义搜索 MCP 服务,与 Claude Code 完全兼容,无需改变你的工作流即可解锁智能检索。🔥 查看简易配置 →

为什么选择 LEANN

LEANN 与传统向量数据库存储对比

数据不言自明: 仅 6GB 即可索引 6000 万条文本块,而非 201GB。从邮件到浏览器历史,一切都能装进你的笔记本电脑。查看下方不同应用的详细基准测试 ↓

🔒 隐私: 你的数据永不离开笔记本电脑。无需 OpenAI、无需云端、没有「服务条款」。

🪶 轻量: 基于图的重计算消除了沉重的嵌入存储负担,智能图剪枝与 CSR 格式将图存储开销降至最低。存储更少、内存占用更低!

📦 便携: 以极低成本在设备间(甚至与他人)转移整个知识库——你的个人 AI 记忆随身而行。

📈 可扩展: 处理会让传统向量数据库崩溃的杂乱个人数据,轻松管理不断增长的个人化数据与智能体生成的记忆!

无精度损失: 在存储占用减少 97% 的同时,保持与重量级方案相同的搜索质量。

安装

📦 前置条件:安装 uv

如果尚未安装,请先安装 uv。通常可通过以下命令安装:

curl -LsSf https://astral.sh/uv/install.sh | sh

🚀 快速安装

克隆仓库以访问所有示例并体验精彩应用,

git clone https://github.com/yichuan-w/LEANN.git leann
cd leann

然后从 PyPI 安装 LEANN,即可立即运行:

uv venv
source .venv/bin/activate
uv pip install leann

# CPU-only (Linux): use the `cpu` extra (e.g. `leann[cpu]`)
🔧 从源码构建(推荐用于开发)
git clone https://github.com/yichuan-w/LEANN.git leann
cd leann
git submodule update --init --recursive

macOS

注意:DiskANN 需要 macOS 13.3 或更高版本。

brew install libomp boost protobuf zeromq pkgconf
uv sync --extra diskann

LinuxUbuntu/Debian):

注意:在 Ubuntu 20.04 上,你可能需要构建较新版本的 Abseil 并固定 Protobuf 版本(例如 v3.20.x)以构建 DiskANN。分步说明请参阅 Issue #30

你可以手动安装 Intel oneAPI MKL 替代 libmkl-full-dev 用于 DiskANN。你也可以使用 libopenblas-dev 仅构建 HNSW,方法是在下方命令中移除 --extra diskann

sudo apt-get update && sudo apt-get install -y \
  libomp-dev libboost-all-dev protobuf-compiler libzmq3-dev \
  pkg-config libabsl-dev libaio-dev libprotobuf-dev \
  libmkl-full-dev

uv sync --extra diskann

LinuxArch Linux):

sudo pacman -Syu && sudo pacman -S --needed base-devel cmake pkgconf git gcc \
  boost boost-libs protobuf abseil-cpp libaio zeromq

# For MKL in DiskANN
sudo pacman -S --needed base-devel git
git clone https://aur.archlinux.org/paru-bin.git
cd paru-bin && makepkg -si
paru -S intel-oneapi-mkl intel-oneapi-compiler
source /opt/intel/oneapi/setvars.sh

uv sync --extra diskann

LinuxRHEL / CentOS Stream / Oracle / Rocky / AlmaLinux):

更多详情请参阅 Issue #50

sudo dnf groupinstall -y "Development Tools"
sudo dnf install -y libomp-devel boost-devel protobuf-compiler protobuf-devel \
  abseil-cpp-devel libaio-devel zeromq-devel pkgconf-pkg-config

# For MKL in DiskANN
sudo dnf install -y intel-oneapi-mkl intel-oneapi-mkl-devel \
  intel-oneapi-openmp || sudo dnf install -y intel-oneapi-compiler
source /opt/intel/oneapi/setvars.sh

uv sync --extra diskann

Windows

需要 Visual Studio 2022 Build Tools,并安装 C++ desktop development 工作负载,以及 vcpkg.

# Install toolchain (if not already present)
choco install cmake swig pkgconfiglite nuget.commandline -y

# Install C++ dependencies via vcpkg
vcpkg install zeromq:x64-windows openblas:x64-windows lapack:x64-windows `
  boost-program-options:x64-windows protobuf:x64-windows

# Set environment variables (adjust VCPKG_ROOT to your vcpkg path)
$env:CMAKE_PREFIX_PATH = "$env:VCPKG_ROOT\installed\x64-windows"
$env:PKG_CONFIG_PATH = "$env:VCPKG_ROOT\installed\x64-windows\lib\pkgconfig"
$env:PKG_CONFIG_EXECUTABLE = "C:\ProgramData\chocolatey\bin\pkg-config.exe"
$env:OPENBLAS_LIB = "$env:VCPKG_ROOT\installed\x64-windows\lib\openblas.lib"
$env:PATH += ";$env:VCPKG_ROOT\installed\x64-windows\bin"
$env:PATH += ";$env:VCPKG_ROOT\installed\x64-windows\tools\protobuf"

uv sync --extra diskann

快速开始

我们的声明式 API 让 RAG 像编写配置文件一样简单。

查看 demo.ipynb,或 Open In Colab

from leann import LeannBuilder, LeannSearcher, LeannChat
from pathlib import Path
INDEX_PATH = str(Path("./").resolve() / "demo.leann")

# Build an index
builder = LeannBuilder(backend_name="hnsw")
builder.add_text("LEANN saves 97% storage compared to traditional vector databases.")
builder.add_text("Tung Tung Tung Sahur called—they need their bananacrocodile hybrid back")
builder.build_index(INDEX_PATH)

# Search
searcher = LeannSearcher(INDEX_PATH)
results = searcher.search("fantastical AI-generated creatures", top_k=1)

# Chat with your data
chat = LeannChat(INDEX_PATH, llm_config={"type": "hf", "model": "Qwen/Qwen3-0.6B"})
response = chat.ask("How much storage does LEANN save?", top_k=1)

万物皆可 RAG

LEANN 支持多种数据源的 RAG,包括文档(.pdf.txt.md)、Apple Mail、Google 搜索历史、微信、ChatGPT 对话、Claude 对话、iMessage 对话,以及通过 MCPModel Context Protocol,模型上下文协议)服务器从任意平台获取的实时数据——包括 Slack、Twitter 等。

生成模型配置

LLM 后端

LEANN 支持众多 LLM 提供商进行文本生成(HuggingFace、Ollama、Anthropic 以及任何兼容 OpenAI 的 API)。

🔑 OpenAI API 配置(默认)

将 OpenAI API 密钥设置为环境变量:

export OPENAI_API_KEY="your-api-key-here"

使用 CLI 时,请务必使用 --llm openai 标志。 你也可以通过 --llm-model <model-name> 标志指定模型名称。

🛠️ 支持的 LLM 与 Embedding 提供商(通过 OpenAI 兼容性)

得益于 OpenAI API 格式的广泛采用,LEANN 开箱即用地兼容大量 LLM 与 embedding 提供商。只需设置 OPENAI_BASE_URLOPENAI_API_KEY 环境变量,即可连接你偏好的服务。

export OPENAI_API_KEY="xxx"
export OPENAI_BASE_URL="http://localhost:1234/v1" # base url of the provider

在 CLI 界面中使用兼容 OpenAI 的端点:

若用于文本生成,请务必使用 --llm openai 标志,并通过 --llm-model <model-name> 标志指定模型名称。

若用于 embedding,请设置 --embedding-mode openai 标志,并通过 --embedding-model <MODEL> 指定模型名称。


以下是常见提供商的 Base URL 列表,供你快速上手。

🖥️ 本地推理引擎(推荐,可最大程度保护隐私)

提供商 示例 Base URL
Ollama http://localhost:11434/v1
LM Studio http://localhost:1234/v1
vLLM http://localhost:8000/v1
llama.cpp http://localhost:8080/v1
SGLang http://localhost:30000/v1
LiteLLM http://localhost:4000

☁️ 云服务提供商

🚨 隐私提示: 在选择云服务提供商之前,请仔细查阅其隐私与数据保留政策。根据其条款,你的数据可能被用于其自身目的,包括但不限于人工审核与模型训练;若处理不当,可能带来严重后果。

提供商 Base URL
OpenAI https://api.openai.com/v1
OpenRouter https://openrouter.ai/api/v1
Gemini https://generativelanguage.googleapis.com/v1beta/openai/
x.AI (Grok) https://api.x.ai/v1
Groq AI https://api.groq.com/openai/v1
DeepSeek https://api.deepseek.com/v1
SiliconFlow https://api.siliconflow.cn/v1
Zhipu (BigModel) https://open.bigmodel.cn/api/paas/v4/
Mistral AI https://api.mistral.ai/v1
Anthropic https://api.anthropic.com/v1
Jina AI (Embeddings) https://api.jina.ai/v1

💡 提示:分离 Embedding 提供商

若要为 embedding 使用不同的提供商(例如 Jina AI),同时为 LLM 使用另一家,可使用 --embedding-api-base--embedding-api-key

leann build my-index --docs ./docs \
  --embedding-mode openai \
  --embedding-model jina-embeddings-v3 \
  --embedding-api-base https://api.jina.ai/v1 \
  --embedding-api-key $JINA_API_KEY

若你的提供商不在此列表中,别担心!查看其文档中的 OpenAI 兼容端点——很可能同样兼容 OpenAI!

🔧 Ollama 配置(推荐,可最大程度保护隐私)

macOS

首先,下载适用于 macOS 的 Ollama.

# Pull a lightweight model (recommended for consumer hardware)
ollama pull llama3.2:1b

Linux

# Install Ollama
curl -fsSL https://ollama.ai/install.sh | sh

# Start Ollama service manually
ollama serve &

# Pull a lightweight model (recommended for consumer hardware)
ollama pull llama3.2:1b

灵活配置

LEANN 为 embedding 模型、检索策略与数据处理提供灵活参数,以适应你的具体需求。

📚 需要配置最佳实践? 查看我们的配置指南,获取详细优化技巧、模型选择建议,以及 embedding 速度慢或检索质量差等常见问题的解决方案。

📋 点击展开:通用参数(所有示例均可用)

所有 RAG 示例共享这些通用参数。所有示例均支持交互模式——只需不带 --query 运行,即可启动持续问答会话,连续提问。输入 'quit' 退出。

# Environment Variables (GPU Device Selection)
LEANN_EMBEDDING_DEVICE       # GPU for embedding model (e.g., cuda:0, cuda:1, cpu)
LEANN_LLM_DEVICE             # GPU for HFChat LLM (e.g., cuda:1, or "cuda" for multi-GPU auto)

# Core Parameters (General preprocessing for all examples)
--index-dir DIR              # Directory to store the index (default: current directory)
--query "YOUR QUESTION"      # Single query mode. Omit for interactive chat (type 'quit' to exit), and now you can play with your index interactively
--max-items N                # Limit data preprocessing (default: -1, process all data)
--force-rebuild              # Force rebuild index even if it exists

# Embedding Parameters
--embedding-model MODEL      # e.g., facebook/contriever, text-embedding-3-small, mlx-community/Qwen3-Embedding-0.6B-8bit or nomic-embed-text
--embedding-mode MODE        # sentence-transformers, openai, mlx, or ollama

# LLM Parameters (Text generation models)
--llm TYPE                   # LLM backend: openai, ollama, hf, or anthropic (default: openai)
--llm-model MODEL            # Model name (default: gpt-4o) e.g., gpt-4o-mini, llama3.2:1b, Qwen/Qwen2.5-1.5B-Instruct
--thinking-budget LEVEL      # Thinking budget for reasoning models: low/medium/high (supported by o3, o3-mini, GPT-Oss:20b, and other reasoning models)

# Search Parameters
--top-k N                    # Number of results to retrieve (default: 20)
--search-complexity N        # Search complexity for graph traversal (default: 32)

# Chunking Parameters
--chunk-size N               # Size of text chunks (default varies by source: 256 for most, 192 for WeChat)
--chunk-overlap N            # Overlap between chunks (default varies: 25-128 depending on source)

# Index Building Parameters
--backend-name NAME          # Backend to use: hnsw or diskann (default: hnsw)
--graph-degree N             # Graph degree for index construction (default: 32)
--build-complexity N         # Build complexity for index construction (default: 64)
--compact / --no-compact     # Use compact storage (default: true). Must be `no-compact` for `no-recompute` build.
--recompute / --no-recompute # Enable/disable embedding recomputation (default: enabled). Should not do a `no-recompute` search in a `recompute` build.

📄 个人数据管理器:处理任意文档(.pdf.txt.md)!

直接对你的个人 PDF、文档以及包含文件的任意目录提问!

LEANN Document Search Demo

下面的示例会就我们的论文摘要提出问题(使用 data/ 中的默认数据,该目录包含多种数据源:两篇论文、《傲慢与偏见》,以及一份关于华为 LLM 的中文技术报告),这也是最容易在此运行的示例

source .venv/bin/activate # Don't forget to activate the virtual environment
python -m apps.document_rag --query "What are the main techniques LEANN explores?"
📋 点击展开:文档专用参数

参数

--data-dir DIR           # Directory containing documents to process (default: data)
--file-types .ext .ext   # Filter by specific file types (optional - all LlamaIndex supported types if omitted)

示例命令

# Process all documents with larger chunks for academic papers
python -m apps.document_rag --data-dir "~/Documents/Papers" --chunk-size 1024

# Filter only markdown and Python files with smaller chunks
python -m apps.document_rag --data-dir "./docs" --chunk-size 256 --file-types .md .py

# Enable AST-aware chunking for code files
python -m apps.document_rag --enable-code-chunking --data-dir "./my_project"

# Or use the specialized code RAG for better code understanding
python -m apps.code_rag --repo-dir "./my_codebase" --query "How does authentication work?"

🎨 ColQwen:基于视觉语言模型的多模态 PDF 检索

使用 ColQwen2/ColPali 模型,结合文本与视觉理解搜索 PDF。非常适合研究论文、技术文档,以及任何版式复杂、包含图表或示意图的 PDF。

🍎 Mac 用户ColQwen 针对 Apple Silicon 进行了优化,支持 MPS 加速以提升推理速度!

# Build index from PDFs
python -m apps.colqwen_rag build --pdfs ./my_papers/ --index research_papers

# Search with text queries
python -m apps.colqwen_rag search research_papers "How does attention mechanism work?"

# Interactive Q&A
python -m apps.colqwen_rag ask research_papers --interactive
📋 点击展开:ColQwen 设置与用法

前置条件

# Install dependencies
uv pip install colpali_engine pdf2image pillow matplotlib qwen_vl_utils einops seaborn
brew install poppler  # macOS only, for PDF processing

构建索引

python -m apps.colqwen_rag build \
  --pdfs ./pdf_directory/ \
  --index my_index \
  --model colqwen2  # or colpali

搜索

python -m apps.colqwen_rag search my_index "your question here" --top-k 5

模型

  • ColQwen2colqwen2):最新的视觉语言模型,性能更优
  • ColPalicolpali):成熟的多模态检索器

详细用法请参阅 ColQwen 指南

📧 你的个人邮件秘书:基于 Apple Mail 的 RAG

注意: 以下示例目前仅支持 macOS。Windows 支持即将推出。

LEANN Email Search Demo

在运行下面的示例之前,你需要在「系统设置 → 隐私与安全性 → 完全磁盘访问权限」中为终端/VS Code 授予完全磁盘访问权限。

python -m apps.email_rag --query "What's the food I ordered by DoorDash or Uber Eats mostly?"

780K 邮件分块 → 78MB 存储空间。 终于可以像用 Google 搜索一样搜索你的邮件了。

📋 点击展开:邮件专用参数

参数

--mail-path PATH         # Path to specific mail directory (auto-detects if omitted)
--include-html          # Include HTML content in processing (useful for newsletters)

示例命令

# Search work emails from a specific account
python -m apps.email_rag --mail-path "~/Library/Mail/V10/WORK_ACCOUNT"

# Find all receipts and order confirmations (includes HTML)
python -m apps.email_rag --query "receipt order confirmation invoice" --include-html
📋 点击展开:可尝试的示例查询

索引构建完成后,你可以提出如下问题:

  • "Find emails from my boss about deadlines"
  • "What did John say about the project timeline?"
  • "Show me emails about travel expenses"

🔍 网页时光机:对你的整个 Chrome 浏览历史进行 RAG!

LEANN Browser History Search Demo

python -m apps.browser_rag --query "Tell me my browser history about machine learning?"

38K 条浏览记录 → 6MB 存储空间。 让你的浏览历史成为你的个人搜索引擎。

📋 点击展开:浏览器专用参数

参数

--chrome-profile PATH    # Path to Chrome profile directory (auto-detects if omitted)

示例命令

# Search academic research from your browsing history
python -m apps.browser_rag --query "arxiv papers machine learning transformer architecture"

# Track competitor analysis across work profile
python -m apps.browser_rag --chrome-profile "~/Library/Application Support/Google/Chrome/Work Profile" --max-items 5000
📋 点击展开:如何找到你的 Chrome 配置文件

默认 Chrome 配置文件路径已针对典型的 macOS 环境进行配置。如需找到你的具体 Chrome 配置文件:

  1. 打开终端(Terminal
  2. 运行:ls ~/Library/Application\ Support/Google/Chrome/
  3. 查找类似 "Default"、"Profile 1"、"Profile 2" 等的文件夹
  4. 将完整路径用作 --chrome-profile 参数

常见 Chrome 配置文件位置:

  • macOS~/Library/Application Support/Google/Chrome/Default
  • Linux~/.config/google-chrome/Default
💬 点击展开:可尝试的示例查询

索引构建完成后,你可以提出如下问题:

  • "What websites did I visit about machine learning?"
  • "Find my search history about programming"
  • "What YouTube videos did I watch recently?"
  • "Show me websites I visited about travel planning"

💬 微信侦探:解锁你的珍贵回忆!

LEANN WeChat Search Demo

python -m apps.wechat_rag --query "Show me all group chats about weekend plans"

400K 条消息 → 64MB 存储空间 用任意语言搜索多年的聊天记录。

🔧 点击展开:安装要求

首先,你需要安装 WeChat exporter,

brew install sunnyyoung/repo/wechattweak-cli

或手动安装(如果你在使用 Homebrew 时遇到问题):

sudo packages/wechat-exporter/wechattweak-cli install

故障排除:

  • 安装问题:请查看 WeChatTweak-CLI issues page
  • 导出错误:如果遇到以下错误,请尝试重启微信
    Failed to export WeChat data. Please ensure WeChat is running and WeChatTweak is installed.
    Failed to find or export WeChat data. Exiting.
    
📋 点击展开:微信专用参数

参数

--export-dir DIR         # Directory to store exported WeChat data (default: wechat_export_direct)
--force-export          # Force re-export even if data exists

示例命令

# Search for travel plans discussed in group chats
python -m apps.wechat_rag --query "travel plans" --max-items 10000

# Re-export and search recent chats (useful after new messages)
python -m apps.wechat_rag --force-export --query "work schedule"
💬 点击展开:你可以尝试的示例查询

索引构建完成后,你可以提出类似这样的问题:

  • "我想买魔术师约翰逊的球衣,给我一些对应聊天记录?" (中文:Show me chat records about buying Magic Johnson's jersey)

🤖 ChatGPT 聊天记录:你的个人 AI 对话档案库!

将你的 ChatGPT 对话转化为可搜索的知识库!检索你所有关于编程、研究、头脑风暴等内容的 ChatGPT 讨论。

python -m apps.chatgpt_rag --export-path chatgpt_export.html --query "How do I create a list in Python?"

解锁你的 AI 对话历史。 再也不会从 ChatGPT 讨论中丢失有价值的洞见。

📋 点击展开:如何导出 ChatGPT 数据

分步导出流程:

  1. 登录 ChatGPT
  2. 点击右上角的 个人资料图标
  3. 进入 Settings(设置)Data Controls(数据控制)
  4. 在 Export Data(导出数据)下 点击 "Export"(导出)
  5. 确认导出 请求
  6. 通过邮件中的链接 下载 ZIP 文件24 小时内有效)
  7. 解压或直接使用 LEANN 处理

支持的格式:

  • 来自 ChatGPT 导出的 .html 文件
  • 来自 ChatGPT 的 .zip 压缩包
  • 包含多个导出文件的目录
📋 点击展开:ChatGPT 专用参数

参数

--export-path PATH           # Path to ChatGPT export file (.html/.zip) or directory (default: ./chatgpt_export)
--separate-messages         # Process each message separately instead of concatenated conversations
--chunk-size N              # Text chunk size (default: 512)
--chunk-overlap N           # Overlap between chunks (default: 128)

示例命令

# Basic usage with HTML export
python -m apps.chatgpt_rag --export-path conversations.html

# Process ZIP archive from ChatGPT
python -m apps.chatgpt_rag --export-path chatgpt_export.zip

# Search with specific query
python -m apps.chatgpt_rag --export-path chatgpt_data.html --query "Python programming help"

# Process individual messages for fine-grained search
python -m apps.chatgpt_rag --separate-messages --export-path chatgpt_export.html

# Process directory containing multiple exports
python -m apps.chatgpt_rag --export-path ./chatgpt_exports/ --max-items 1000
💡 点击展开:你可以尝试的示例查询

ChatGPT 对话完成索引后,你可以用类似这样的查询进行搜索:

  • "What did I ask ChatGPT about Python programming?"
  • "Show me conversations about machine learning algorithms"
  • "Find discussions about web development frameworks"
  • "What coding advice did ChatGPT give me?"
  • "Search for conversations about debugging techniques"
  • "Find ChatGPT's recommendations for learning resources"

🤖 Claude 聊天记录:你的个人 AI 对话档案库!

将你的 Claude 对话转化为可搜索的知识库!检索你所有关于编程、研究、头脑风暴等内容的 Claude 讨论。

python -m apps.claude_rag --export-path claude_export.json --query "What did I ask about Python dictionaries?"

解锁你的 AI 对话历史。 再也不会从 Claude 讨论中丢失有价值的洞见。

📋 点击展开:如何导出 Claude 数据

分步导出流程:

  1. 在浏览器中 打开 Claude
  2. 进入 Settings(设置)(查找齿轮图标或设置菜单)
  3. 在账户设置中 找到 Export/Download(导出/下载) 选项
  4. 下载对话数据(通常为 JSON 格式)
  5. 将文件 放到你的项目目录

注意:Claude 的导出方式可能因你使用的界面而异。请查阅 Claude 的帮助文档以获取最新的导出说明。

支持的格式:

  • .json 文件(推荐)
  • 包含 JSON 数据的 .zip 压缩包
  • 包含多个导出文件的目录
📋 点击展开:Claude 专用参数

参数

--export-path PATH           # Path to Claude export file (.json/.zip) or directory (default: ./claude_export)
--separate-messages         # Process each message separately instead of concatenated conversations
--chunk-size N              # Text chunk size (default: 512)
--chunk-overlap N           # Overlap between chunks (default: 128)

示例命令

# Basic usage with JSON export
python -m apps.claude_rag --export-path my_claude_conversations.json

# Process ZIP archive from Claude
python -m apps.claude_rag --export-path claude_export.zip

# Search with specific query
python -m apps.claude_rag --export-path claude_data.json --query "machine learning advice"

# Process individual messages for fine-grained search
python -m apps.claude_rag --separate-messages --export-path claude_export.json

# Process directory containing multiple exports
python -m apps.claude_rag --export-path ./claude_exports/ --max-items 1000
💡 点击展开:你可以尝试的示例查询

Claude 对话完成索引后,你可以用类似这样的查询进行搜索:

  • "What did I ask Claude about Python programming?"
  • "Show me conversations about machine learning algorithms"
  • "Find discussions about software architecture patterns"
  • "What debugging advice did Claude give me?"
  • "Search for conversations about data structures"
  • "Find Claude's recommendations for learning resources"

💬 iMessage 记录:你的个人对话档案库!

将你的 iMessage 对话转化为可搜索的知识库!检索你与朋友、家人和同事的所有短信、群聊和对话。

python -m apps.imessage_rag --query "What did we discuss about the weekend plans?"

解锁你的消息历史。 再也不会从 iMessage 历史中丢失重要对话、分享的链接或难忘时刻。

📋 点击展开:如何访问 iMessage 数据

iMessage 数据位置:

iMessage 对话存储在 Mac 上的 SQLite 数据库中,路径为:

~/Library/Messages/chat.db

重要的设置要求:

  1. 向终端或 IDE 授予完全磁盘访问权限(Full Disk Access

    • 打开 System Preferences(系统偏好设置)Security & Privacy(安全性与隐私)Privacy(隐私)
    • 在左侧边栏选择 Full Disk Access(完全磁盘访问权限)
    • 点击 + 按钮,添加你的终端应用(Terminal、iTerm2)或 IDEVS Code 等)
    • 授权后重启终端/IDE
  2. 备选方案:使用备份数据库

    • 如果你有 Time Machine 备份或数据库的手动副本
    • 使用 --db-path 指定自定义位置

支持的格式:

  • 直接访问 ~/Library/Messages/chat.db(默认)
  • 通过 --db-path 指定自定义数据库路径
  • 可配合数据库备份副本使用
📋 点击展开:iMessage 专用参数

参数

--db-path PATH                    # Path to chat.db file (default: ~/Library/Messages/chat.db)
--concatenate-conversations       # Group messages by conversation (default: True)
--no-concatenate-conversations    # Process each message individually
--chunk-size N                    # Text chunk size (default: 1000)
--chunk-overlap N                 # Overlap between chunks (default: 200)

示例命令

# Basic usage (requires Full Disk Access)
python -m apps.imessage_rag

# Search with specific query
python -m apps.imessage_rag --query "family dinner plans"

# Use custom database path
python -m apps.imessage_rag --db-path /path/to/backup/chat.db

# Process individual messages instead of conversations
python -m apps.imessage_rag --no-concatenate-conversations

# Limit processing for testing
python -m apps.imessage_rag --max-items 100 --query "weekend"
💡 点击展开:可尝试的示例查询

当你的 iMessage 对话完成索引后,可以使用如下查询进行搜索:

  • "我们关于度假计划讨论了什么?"
  • "查找关于餐厅推荐的消息"
  • "显示我与 John 关于该项目的对话"
  • "搜索关于技术的分享链接"
  • "查找群聊中关于周末活动的讨论"
  • "妈妈关于家庭聚会说了什么?"

MCP 集成:基于任意平台实时数据的 RAG

通过 Model Context ProtocolMCP)连接实时数据源。LEANN 现已支持通过标准化 MCP 服务器,在 Slack、Twitter 等平台上进行实时 RAGRetrieval-Augmented Generation,检索增强生成)。

主要优势:

  • 实时数据访问:无需手动导出即可获取实时数据
  • 标准化协议:可使用任意兼容 MCP 的服务器
  • 易于扩展:以最少代码即可添加新平台
  • 安全访问:由 MCP 服务器处理身份验证

💬 Slack 消息:搜索团队对话

将你的 Slack 工作区转变为可搜索的知识库!在所有频道中查找讨论、决策和共享知识。

# Test MCP server connection
python -m apps.slack_rag --mcp-server "slack-mcp-server" --test-connection

# Index and search Slack messages
python -m apps.slack_rag \
  --mcp-server "slack-mcp-server" \
  --workspace-name "my-team" \
  --channels general dev-team random \
  --query "What did we decide about the product launch?"

📖 完整设置指南:有关详细设置说明、常见问题排查(如 "users cache is not ready yet")以及高级配置选项,请参阅我们的 Slack 设置指南

快速设置:

  1. 安装 Slack MCP 服务器(例如 npm install -g slack-mcp-server
  2. 创建 Slack 应用并获取 API 凭据(参见上方详细指南)
  3. 设置环境变量:
    export SLACK_BOT_TOKEN="xoxb-your-bot-token"
    export SLACK_APP_TOKEN="xapp-your-app-token"  # Optional
    
  4. 使用 --test-connection 标志测试连接

参数:

  • --mcp-server:启动 Slack MCP 服务器的命令
  • --workspace-name:用于组织的 Slack 工作区名称
  • --channels:要索引的特定频道(可选)
  • --concatenate-conversations:按频道分组消息(默认:true
  • --max-messages-per-channel:每个频道的消息数量限制(默认:100)
  • --max-retries:缓存同步问题的最大重试次数(默认:5)
  • --retry-delay:重试之间的初始延迟(秒)(默认:2.0)

🐦 Twitter 书签:你的个人推文库

搜索你的 Twitter 书签!找到你保存以备后用的那篇完美文章、推文串或见解。

# Test MCP server connection
python -m apps.twitter_rag --mcp-server "twitter-mcp-server" --test-connection

# Index and search Twitter bookmarks
python -m apps.twitter_rag \
  --mcp-server "twitter-mcp-server" \
  --max-bookmarks 1000 \
  --query "What AI articles did I bookmark about machine learning?"

设置要求:

  1. 安装 Twitter MCP 服务器(例如 npm install -g twitter-mcp-server
  2. 获取 Twitter API 凭据:
    • developer.twitter.com 申请 Twitter 开发者账号
    • 在 Twitter Developer Portal 中创建新应用
    • 生成具有 "Read" 权限的 API 密钥和访问令牌
    • 要访问书签,你可能需要具备相应权限范围的 Twitter API v2
    export TWITTER_API_KEY="your-api-key"
    export TWITTER_API_SECRET="your-api-secret"
    export TWITTER_ACCESS_TOKEN="your-access-token"
    export TWITTER_ACCESS_TOKEN_SECRET="your-access-token-secret"
    
  3. 使用 --test-connection 标志测试连接

参数:

  • --mcp-server:启动 Twitter MCP 服务器的命令
  • --username:按用户名筛选书签(可选)
  • --max-bookmarks:获取书签的最大数量(默认:1000
  • --no-tweet-content:排除推文内容,仅保留元数据
  • --no-metadata:排除互动元数据
💡 点击展开:可尝试的示例查询

Slack 查询:

  • "团队关于项目截止日期讨论了什么?"
  • "查找关于新功能发布的消息"
  • "显示关于预算规划的对话"
  • "dev-team 频道中做出了哪些决策?"

Twitter 查询:

  • "我上个月收藏了哪些 AI 文章?"
  • "查找关于机器学习技术的推文"
  • "显示我收藏的关于创业建议的推文串"
  • "我保存了哪些 Python 教程?"
🔧 在 CLI 命令中使用 MCP

想在常规 LEANN CLI 中使用 MCP 数据? 你可以将 MCP 应用与 CLI 命令结合使用:

# Step 1: Use MCP app to fetch and index data
python -m apps.slack_rag --mcp-server "slack-mcp-server" --workspace-name "my-team"

# Step 2: The data is now indexed and available via CLI
leann search slack_messages "project deadline"
leann ask slack_messages "What decisions were made about the product launch?"

# Same for Twitter bookmarks
python -m apps.twitter_rag --mcp-server "twitter-mcp-server"
leann search twitter_bookmarks "machine learning articles"

MCP 与手动导出对比:

  • MCP:实时数据、自动更新,需要服务器设置
  • 手动导出:一次性设置、可离线使用,需要手动导出数据
🔧 添加新的 MCP 平台

想为其他平台添加支持?LEANN 的 MCP 集成专为易于扩展而设计:

  1. 查找或创建适用于你平台的 MCP 服务器
  2. 创建 reader 类,遵循 apps/slack_data/slack_mcp_reader.py 中的模式
  3. 创建 RAG 应用,遵循 apps/slack_rag.py 中的模式
  4. 测试并回馈社区!

值得探索的热门 MCP 服务器:

  • GitHub 仓库与 issue
  • Discord 消息
  • Notion 页面
  • Google Drive 文档
  • MCP 生态系统中还有更多!

🚀 Claude Code 集成:改变你的开发工作流!

AST 感知代码分块

LEANN 提供智能代码分块功能,可为 Python、Java、C# 和 TypeScript 保留语义边界(函数、类、方法),相比基于文本的分块能更好地理解代码。

📖 阅读 AST 分块指南 →

代码辅助的未来已来。 通过 LEANN 面向 Claude Code 的原生 MCP 集成,改变你的开发工作流。索引整个代码库,并在 IDE 中直接获得智能代码辅助。

主要特性:

  • 🔍 语义代码搜索:覆盖整个项目,完全本地索引且轻量
  • 🧠 AST 感知分块:保留代码结构(函数、类)
  • 📚 上下文感知辅助:用于调试与开发
  • 🚀 零配置设置:自动语言检测
# Install LEANN globally for MCP integration
uv tool install leann-core --with leann
claude mcp add --scope user leann-server -- leann_mcp
# Setup is automatic - just start using Claude Code!

试用我们完整的智能体流水线,支持自动查询重写、语义搜索规划等功能:

LEANN MCP Integration

🔥 准备好大幅提升你的编码效率了吗? 完整设置指南 →

命令行界面

LEANN 包含功能强大的 CLI,用于文档处理与搜索。非常适合快速文档索引和交互式对话。

安装

如果你已按照快速入门操作,leann 已安装在你的虚拟环境中:

source .venv/bin/activate
leann --help

要使其全局可用:

# Install the LEANN CLI globally using uv tool
uv tool install leann-core --with leann


# Now you can use leann from anywhere without activating venv
leann --help

注意:与 Claude Code 集成需要全局安装。leann_mcp 服务器依赖于全局可用的 leann 命令。

使用示例

# build from a specific directory, and my_docs is the index name(Here you can also build from multiple dict or multiple files)
leann build my-docs --docs ./your_documents

# Search your documents
leann search my-docs "machine learning concepts"

# Interactive chat with your documents
leann ask my-docs --interactive

# Ask a single question (non-interactive)
leann ask my-docs "Where are prompts configured?"

# Detect file changes since last build/watch checkpoint
leann watch my-docs

# List all your indexes
leann list

# Remove an index
leann remove my-docs

主要 CLI 功能:

  • 自动检测文档格式(PDF、TXT、MD、DOCX、PPTX 及代码文件)
  • 针对 Python、Java、C#、TypeScript 文件的 🧠 基于 AST 的分块(AST-aware chunking
  • 对其他所有内容采用带重叠的智能文本分块
  • 通过 Merkle 树快照实现 📂 文件变更检测leann watch
  • 支持多种 LLM 提供商(Ollama、OpenAI、HuggingFace
  • .leann/indexes/ 中进行有序的索引存储(项目本地)
  • 支持高级搜索参数
📋 点击展开:完整 CLI 参考

你可以使用 leann --help,或 leann build --helpleann search --helpleann watch --helpleann ask --helpleann list --helpleann remove --help 获取完整的 CLI 参考。

构建命令:

leann build INDEX_NAME --docs DIRECTORY|FILE [DIRECTORY|FILE ...] [OPTIONS]

Options:
  --backend {hnsw,diskann}     Backend to use (default: hnsw)
  --embedding-model MODEL      Embedding model (default: facebook/contriever)
  --graph-degree N             Graph degree (default: 32)
  --complexity N               Build complexity (default: 64)
  --force                      Force rebuild existing index
  --compact / --no-compact     Use compact storage (default: true). Must be `no-compact` for `no-recompute` build.
  --recompute / --no-recompute Enable recomputation (default: true)

搜索命令:

leann search INDEX_NAME QUERY [OPTIONS]

Options:
  --top-k N                     Number of results (default: 5)
  --complexity N                Search complexity (default: 64)
  --recompute / --no-recompute  Enable/disable embedding recomputation (default: enabled). Should not do a `no-recompute` search in a `recompute` build.
  --pruning-strategy {global,local,proportional}

监视命令:

leann watch INDEX_NAME

# Compares the current file system state against the last checkpoint (Merkle tree snapshot)
# and reports which files have been added, removed, or modified, along with their chunk IDs.
#
# - Automatically saves a new checkpoint after detecting changes
# - Each subsequent run compares against the most recent checkpoint
# - File change detection uses SHA-256 content hashing via a Merkle tree
#
# Example output:
#   === Changes since last checkpoint ===
#   modified (1):
#     - /path/to/file.py
#       chunks: 42, 43, 44

提问命令:

leann ask INDEX_NAME [OPTIONS]

Options:
  --llm {ollama,openai,hf,anthropic}    LLM provider (default: ollama)
  --model MODEL                         Model name (default: qwen3:8b)
  --interactive                         Interactive chat mode
  --top-k N                             Retrieval count (default: 20)

列表命令:

leann list

# Lists all indexes across all projects with status indicators:
# ✅ - Index is complete and ready to use
# ❌ - Index is incomplete or corrupted
# 📁 - CLI-created index (in .leann/indexes/)
# 📄 - App-created index (*.leann.meta.json files)

删除命令:

leann remove INDEX_NAME [OPTIONS]

Options:
  --force, -f    Force removal without confirmation

# Smart removal: automatically finds and safely removes indexes
# - Shows all matching indexes across projects
# - Requires confirmation for cross-project removal
# - Interactive selection when multiple matches found
# - Supports both CLI and app-created indexes

🚀 高级功能

🎯 元数据过滤

LEANN 提供简单的元数据过滤系统,支持按日期/类型筛选文档、按文件扩展名搜索代码,以及基于自定义条件的内容管理等高级用例。

# Add metadata during indexing
builder.add_text(
    "def authenticate_user(token): ...",
    metadata={"file_extension": ".py", "lines_of_code": 25}
)

# Search with filters
results = searcher.search(
    query="authentication function",
    metadata_filters={
        "file_extension": {"==": ".py"},
        "lines_of_code": {"<": 100}
    }
)

支持的运算符==!=<<=>>=innot_incontainsstarts_withends_withis_trueis_false

📖 完整元数据过滤指南 →

🔍 Grep 搜索

如需精确文本匹配而非语义搜索,请使用 use_grep 参数:

# Exact text search
results = searcher.search("bananacrocodile", use_grep=True, top_k=1)

用例:查找特定代码模式、错误消息、函数名或精确短语,无需语义相似度。

📖 完整 grep 搜索指南 →

🏗️ 架构与工作原理

LEANN Architecture

精髓所在: 大多数向量数据库会存储每一个嵌入向量(成本高)。LEANN 存储经过剪枝的图结构(成本低),并仅在需要时重新计算嵌入向量(速度快)。

核心技术:

  • 基于图的选择性重计算: 仅为搜索路径中的节点计算嵌入向量
  • 高度保留剪枝: 保留重要的「枢纽」节点,同时移除冗余连接
  • 动态批处理: 高效批量计算嵌入向量以提升 GPU 利用率
  • 两级搜索: 智能图遍历,优先探索有希望的节点

后端:

  • HNSW(默认):适用于大多数数据集,通过完全重计算实现最大存储节省
  • DiskANN:高级选项,搜索性能更优,采用基于 PQ 的图遍历与实时重排序,在速度与精度之间取得最佳平衡

基准测试

DiskANN 与 HNSW 性能对比 → - 对比两种后端的搜索性能

简单示例:对比 LEANN 与 FAISS → - 直观了解存储节省效果

📊 存储对比

系统 DPR (2.1M) Wiki (60M) Chat (400K) Email (780K) Browser (38K)
传统向量数据库(例如 FAISS 3.8 GB 201 GB 1.8 GB 2.4 GB 130 MB
LEANN 324 MB 6 GB 64 MB 79 MB 6.4 MB
节省 91% 97% 97% 97% 95%

复现我们的结果

uv run benchmarks/run_evaluation.py    # Will auto-download evaluation data and run benchmarks
uv run benchmarks/run_evaluation.py benchmarks/data/indices/rpj_wiki/rpj_wiki --num-queries 2000    # After downloading data, you can run the benchmark with our biggest index

评估脚本在首次运行时会自动下载数据。最后三项结果是使用部分个人数据测试的,你也可以使用自己的数据进行复现!

🔬 论文

如果你觉得 Leann 有用,请引用:

LEANN: A Low-Storage Vector Index

@misc{wang2025leannlowstoragevectorindex,
      title={LEANN: A Low-Storage Vector Index},
      author={Yichuan Wang and Shu Liu and Zhifei Li and Yongji Wu and Ziming Mao and Yilong Zhao and Xiao Yan and Zhiying Xu and Yang Zhou and Ion Stoica and Sewon Min and Matei Zaharia and Joseph E. Gonzalez},
      year={2025},
      eprint={2506.08276},
      archivePrefix={arXiv},
      primaryClass={cs.DB},
      url={https://arxiv.org/abs/2506.08276},
}

详细功能 →

🤝 贡献指南 →

常见问题 →

📈 路线图 →

📄 许可证

MIT 许可证 — 详情请参阅 LICENSE

🙏 致谢

核心贡献者:Yichuan Wang & Zhifei Li.

活跃贡献者:Gabriel Dehan, Aakash Suresh

欢迎更多贡献者参与!欢迎提交 Issue 或 PR。

本项工作在 Berkeley Sky Computing Lab. 完成

Star 历史

Star History Chart

如果 Leann 对您的研究或应用有帮助,欢迎在 GitHub 上为我们标 Star

由 Leann 团队用 ❤️ 制作

🤖 用 AI 探索 LEANN

LEANN 已收录于 DeepWiki,,您可以通过 Deep Research 向 LLM 提问,探索代码库并获得添加新功能的帮助。