智能检索增强生成系统

一个轻量级、生产就绪的检索增强生成(RAG)系统,结合ChromaDB向量搜索、Ollama LLM智能和网络搜索功能,从知识库中提供准确、上下文感知的响应。

  • by rduffyuk
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 rduffyuk/querymind

使用说明

QueryMind

具有智能查询路由、语义搜索和web回退的多代理RAG系统

QueryMind是一个轻量级的、可用于生产的检索增强生成(RAG)系统,它结合了ChromaDB矢量搜索、Ollama LLM智能和网络搜索功能,从您的知识库中提供准确、上下文感知的响应。

✨ 特性

  • 🤖 智能查询路由 -自动将查询路由到最佳搜索策略
  • 🔍 语义搜索 -基于ChromaDB的向量搜索,嵌入mxbai大型嵌入
  • 💡 LLM意图分析 -Ollama集成用于查询理解和关键字提取
  • 🌐 网络搜索回退 -当vault没有结果时,无缝回退到Serper.dev
  • 📊 结构化日志记录 -基于环境的日志记录,包括调试、信息、警告、错误级别
  • 🛡️ 安全强化 -输入消毒、注射保护和验证
  • 🧪 经过全面测试 -涵盖导入、路由逻辑和安全性的27个测试
  • 📦 Pip可安装 -带有pyproject.toml的标准Python包

🏗️ 建筑

QueryMind实现了 多agent体系结构 使用智能路由:

User Query → Router → [ Fast Search Agent   ] → Results
                      [ Deep Research Agent ]
                      [ Web Search (fallback) ]

代理类型

  1. 快速搜索代理 -简单查询的直接关键字匹配(<1s)
  2. 深度研究代理 -Ollama支持的复杂问题语义分析(~10s)
  3. WebSearch客户端 -Serper.dev API外部知识集成

查询路由启发式

查询将根据以下内容自动路由:

  • 长度:>10个字→ 深入研究
  • 疑问词:“如何”、“为什么”、“什么”、“解释”→ 深入研究
  • 逻辑操作:“和”、“或”、“不是”→ 深入研究
  • 默认:简单关键字→ 快速搜索

🚀 快速开始

先决条件

系统要求:

  • Python 3.9或更高版本
  • 8GB+RAM(建议使用16GB以获得更好的性能)
  • (可选)NVIDIA GPU,可实现更快的嵌入

所需服务:

  • 奥拉玛 -本地LLM推理(误译:7b或类似)
  • 色度数据库 -用于语义搜索的矢量数据库
  • 瑞迪斯 -查询缓存(可选但推荐)

第一步:安装Olama

Ollama为查询分析提供本地LLM推理。

macOS/Linux:

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

# Pull the mistral model (7B parameters, ~4GB)
ollama pull mistral:7b

# Verify installation
ollama list

窗户:

  1. 从下载安装程序https://ollama.com/download
  2. 运行安装程序并按照提示操作
  3. 打开PowerShell并运行: ollama pull mistral:7b

确认Ollama正在运行:

curl http://localhost:11434/api/tags
# Should return list of installed models

步骤2:安装ChromaDB

ChromaDB提供矢量搜索功能。

选项A:作为Python包安装(建议用于开发)

# ChromaDB will be installed automatically with QueryMind
# It runs in-process (no separate server needed)

选项B:运行ChromaDB服务器(建议用于生产)

# Install ChromaDB server
pip install chromadb

# Run ChromaDB server
chroma run --host localhost --port 8000

# Verify server is running
curl http://localhost:8000/api/v1/heartbeat

步骤3:安装Redis(可选)

Redis提供查询缓存以获得更好的性能(73%的缓存命中率)。

macOS:

brew install redis
brew services start redis

Ubuntu/Debian:

sudo apt update
sudo apt install redis-server
sudo systemctl start redis

窗户:

# Download from https://github.com/microsoftarchive/redis/releases
# Or use WSL2 with Ubuntu instructions above

验证Redis:

redis-cli ping
# Should return: PONG

步骤4:安装QueryMind

# Clone the repository
git clone https://github.com/rduffyuk/querymind.git
cd querymind

# Create virtual environment (recommended)
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install QueryMind with all dependencies
pip install .

# Or install in development mode
pip install -e ".[dev]"

步骤5:配置环境

创建 .env 示例中的文件:

cp .env.example .env

编辑 .env 使用您的设置:

# Required - Path to your markdown documents
VAULT_PATH=/path/to/your/obsidian-vault

# ChromaDB settings
CHROMADB_URL=http://localhost:8000  # Or leave blank for in-process mode

# Redis settings (optional - will fall back to in-memory cache)
REDIS_URL=redis://localhost:6379

# Ollama settings
OLLAMA_API_URL=http://localhost:11434

# Optional - Web search API key (100 free queries/month)
SERPER_API_KEY=your-api-key-here

# Logging
LOG_LEVEL=INFO  # DEBUG, INFO, WARNING, ERROR

步骤6:验证安装

运行测试套件以验证一切正常:

# Run all tests
pytest tests/ -v

# Should see: 25 passed, 2 skipped

测试一个简单的查询:

from querymind import auto_search

# Simple test query
result = auto_search("test query", n_results=1)
print(f"Status: {result.status}")
print(f"Agent: {result.agent_type}")

可选:获取Serper.dev API密钥

对于网络搜索回退功能:

  1. 注册地址:https://serper.dev
  2. 从仪表板获取API密钥
  3. 添加 .env: SERPER_API_KEY=your-key-here
  4. 免费套餐:每月100次查询
  5. 免费等级后:每1000次查询0.30美元

可选:安装Obsidian进行文档管理

Obsidian是一个功能强大的markdown编辑器,非常适合管理QueryMind搜索的文档库。虽然不是必需的,但它为创建和组织知识库提供了一个很好的界面。

macOS:

# Download from website
open https://obsidian.md/download

# Or install via Homebrew
brew install --cask obsidian

Linux:

# Download AppImage from website
wget https://github.com/obsidianmd/obsidian-releases/releases/download/v1.4.16/Obsidian-1.4.16.AppImage

# Make executable and run
chmod +x Obsidian-1.4.16.AppImage
./Obsidian-1.4.16.AppImage

# Or install via Snap
sudo snap install obsidian --classic

窗户:

# Download installer from website
start https://obsidian.md/download

# Or install via Chocolatey
choco install obsidian

设置保管库:

  1. 开放式黑曜石
  2. 在以下位置创建新vault或打开现有vault VAULT_PATH 从你的 .env
  3. 开始创建markdown文档
  4. QueryMind将自动索引和搜索这些文档

故障排除

Ollama连接失败:

# Check if Ollama is running
ollama list

# Restart Ollama
# macOS/Linux: sudo systemctl restart ollama
# Windows: Restart Ollama Desktop app

ChromaDB错误:

# If using server mode, check if running
curl http://localhost:8000/api/v1/heartbeat

# If in-process mode, ensure adequate RAM
# ChromaDB needs ~2-4GB for mxbai-embed-large model

Redis不可用:

# QueryMind will fall back to in-memory cache
# To use Redis, ensure it's running:
redis-cli ping

📖 用法

基本搜索

from querymind import auto_search

# Simple query (uses FastSearchAgent)
result = auto_search("Redis caching")
print(f"Found {result.result_count} results")
for r in result.results:
    print(f"  - {r['file']}: {r['score']:.2f}")

# Complex query (uses DeepResearchAgent)
result = auto_search("How to implement Redis caching for APIs?")
print(f"Agent: {result.agent_type}")
print(f"Time: {result.elapsed_time:.2f}s")

高级用法

from querymind.agents.router import AgentRouter

# Initialize router with custom configuration
router = AgentRouter(
    model="mistral:7b",
    enable_web_fallback=True
)

# Execute search with verbose logging
result = router.search(
    query="Explain StatefulSet vs Deployment",
    n_results=10,
    verbose=True
)

# Get routing statistics
stats = router.get_stats()
print(f"Fast searches: {stats['fast_searches']}")
print(f"Deep searches: {stats['deep_searches']}")

直接代理访问

from querymind.agents.vault_search_agent_local import VaultSearchAgentLocal
from querymind.agents.web_search_client import WebSearchClient

# Use vault search agent directly
vault_agent = VaultSearchAgentLocal(model="mistral:7b")
result = vault_agent.search("kubernetes deployment patterns")

# Use web search directly
web_client = WebSearchClient(api_key="your-key")
results = web_client.search_sync("latest FastAPI best practices", n_results=5)

🧪 测试

运行测试套件:

# Run all tests
pytest tests/ -v

# Run specific test file
pytest tests/test_router_basic.py -v

# Run with coverage
pytest tests/ --cov=querymind --cov-report=html

测试覆盖范围:

  • ✅ 总共27次测试
  • ✅ 通过25次(92.6%)
  • ⏭️ 跳过2个(可选依赖项)

测试套件

  • test_imports_work.py -验证所有模块是否可以导入
  • test_router_basic.py -验证查询路由逻辑和启发式方法
  • test_security_validation.py -测试输入消毒和注射保护

🛠️ 发展

设置开发环境

# Clone repository
git clone https://github.com/rduffyuk/querymind.git
cd querymind

# Create virtual environment
python -m venv venv
source venv/bin/activate  # or `venv\Scripts\activate` on Windows

# Install with dev dependencies
pip install -e ".[dev]"

# Run tests
pytest tests/

代码质量

# Format code
black querymind/ tests/

# Lint code
ruff querymind/ tests/

📋 项目结构

querymind/
├── querymind/
│   ├── __init__.py           # Package initialization
│   ├── core/                 # Core functionality
│   │   ├── __init__.py
│   │   ├── config.py         # Configuration management
│   │   ├── logging_config.py # Structured logging (NEW)
│   │   ├── embeddings.py     # ChromaDB embeddings
│   │   ├── cache.py          # Query caching (Redis)
│   │   └── conversation_memory.py  # Conversation stub (NEW)
│   ├── agents/               # Multi-agent system
│   │   ├── __init__.py
│   │   ├── base_agent.py     # Abstract base agent
│   │   ├── fast_search_agent.py    # Quick keyword search
│   │   ├── deep_research_agent.py  # LLM-powered search
│   │   ├── vault_search_agent_local.py  # Ollama integration (NEW)
│   │   ├── web_search_client.py    # Web search fallback (NEW)
│   │   └── router.py         # Intelligent routing
│   └── mcp/                  # Model Context Protocol
│       └── server.py         # FastMCP server
├── tests/                    # Test suite (NEW)
│   ├── __init__.py
│   ├── test_imports_work.py  # Import verification
│   ├── test_router_basic.py  # Routing logic tests
│   └── test_security_validation.py  # Security tests
├── pyproject.toml            # Package configuration (NEW)
├── requirements.txt          # Dependencies
├── .env.example              # Environment template
├── .gitignore                # Git ignore rules
├── LICENSE.txt               # MIT License
└── README.md                 # This file

⚙️ 配置

QueryMind使用环境变量进行配置。看 .env.example 对于所有可用选项:

核心设置

变量 描述 默认值
VAULT_PATH 标记文档的路径 /vault
CHROMADB_URL ChromaDB HTTP端点 http://localhost:8000
REDIS_URL Redis缓存端点 redis://localhost:6379
OLLAMA_API_URL Ollama LLM终点 http://localhost:11434
LOG_LEVEL 日志记录级别(调试/信息/警告/错误) INFO

可选功能

变量 描述 默认值
SERPER_API_KEY Serper.dev 用于web搜索的API密钥 无
DISABLE_WEB_SEARCH 禁用web回退 false

🤝 贡献

欢迎投稿!请遵循以下指南:

  1. 分叉存储库
  2. 创建要素分支(git checkout -b feature/amazing-feature)
  3. 进行更改
  4. 运行测试(pytest tests/)
  5. 提交您的更改(git commit -m 'Add amazing feature')
  6. 推到分支(git push origin feature/amazing-feature)
  7. 打开拉取请求

编码标准

  • 跟随 PEP 8 风格指南
  • 使用 黑色 用于代码格式化
  • 为新功能添加测试
  • 根据需要更新文档
  • 使用结构化日志记录(不打印报表)

🗺️ 路线图

电流(v0.1.0)

  • [x] 具有7种启发式算法的智能查询路由
  • [x] FastSearch、DeepResearch、WebSearch代理
  • [x] Ollama集成用于意图分析
  • [x] ChromaDB矢量搜索
  • [x] 结构化测井系统
  • [x] 综合测试套件(27项测试)
  • [x] 安全强化和输入验证

计划(v0.2.0)

  • []使用聚集缓存增强缓存
  • []异步支持并发搜索
  • []ChromaDB的连接池
  • []高级指标和监控
  • []REST API端点
  • []用于查询测试的Web UI

未来(v1.0.0)

  • []完成对话记忆实现
  • []热重新加载以更改配置
  • []Docker Compose部署
  • []Kubernetes部署指南
  • []多语言支持

📝 许可证

此项目根据MIT许可证获得许可-请参阅 LICENSE.txt 文件以获取详细信息。

🙏 致谢

QueryMind建立在优秀的开源项目之上:


QueryMind -智能搜索您的知识库

制作❤️ 通过 瑞安·达菲


关于

建造于 瑞安·达菲 --SRE专家记录AI基础设施 rduffy.uk / blog.rduffy.ukRootweaver平台探索的一部分——在K3上构建RAG、MCP、多代理编排和个人AI基础设施的公共系列。