Xantus-集成MCP的私人RAG聊天系统
一个生产就绪的RAG(检索增强生成)系统,用于与您的文档聊天
*考虑隐私•可通过MCP扩展•多提供商AI支持*
特性 • 快速开始 • 建筑 • MCP集成 • 配置 • API 参考
______________________________________________________________________
目录
______________________________________________________________________
概述
Xantus是一个 隐私第一 RAG系统允许您使用人工智能与文档聊天。与纯云解决方案不同,Xantus可以运行 完全本地化 或者使用云提供商——由您选择。
是什么让Xantus与众不同?
- 隐私第一:所有数据都保留在本地AI的系统中
- 可扩展:用于外部工具的MCP(模型上下文协议)集成
- 多个用户界面:流式接口+支持OpenAI的API
- 多供应商:支持Ollama、OpenAI、Anthropic等
- 模块化:轻松交换LLM、嵌入、向量存储
- 生产准备就绪:依赖注入、正确的错误处理、日志记录
______________________________________________________________________
特性
核心功能
- 文档聊天:上传PDF、DOCX、TXT、Markdown并与他们聊天
- 语义搜索:使用ChromaDB或Qdrant进行RAG驱动的检索
- 多个接口:
- 为终端用户提供干净的Streamlit UI - 用于集成的RESTful API - 面向开发人员的Python SDK
- 灵活的AI后端:
- 本地:Ollama(隐私优先) - 云:OpenAI,人类学 - 混合:云LLM+本地嵌入
高级功能
- MCP集成:连接外部工具(计算器、文件系统、数据库)
- ⚙可配置的:YAML+环境变量
- 多个矢量存储:ChromaDB,Qdrant
- RAG调谐:调整块大小、重叠、top-k检索
- 安全:通过环境变量进行API密钥管理
- 可扩展的:具有正确依赖项注入的异步API
______________________________________________________________________
建筑
Xantus建立在现代模块化架构之上:
┌─────────────────────────────────────────────────────────┐
│ User │
└────────────┬────────────────────────────┬───────────────┘
│ │
┌────────▼────────┐ ┌────────▼─────────┐
│ Streamlit UI │ │ API Clients │
│ (Port 8501) │ │ (curl, SDK) │
└────────┬────────┘ └────────┬─────────┘
│ │
└────────────┬───────────────┘
│
┌────────▼─────────┐
│ FastAPI Server │
│ (Port 8000) │
└────────┬─────────┘
│
┌───────────────┼───────────────┐
│ │ │
┌──────▼──────┐ ┌──────▼───────┐ ┌────▼─────┐
│ Chat Service│ │Ingest Service│ │ MCP │
└──────┬──────┘ └──────┬───────┘ │ Service │
│ │ └────┬─────┘
│ │ │
┌──────▼───────────────▼──────────────▼─────┐
│ Dependency Injection Container │
│ (LLM • Embeddings • Vector Store • MCP) │
└────────────────────┬──────────────────────┘
│
┌───────────────┼───────────────┐
│ │ │
┌────▼────┐ ┌─────▼─────┐ ┌───▼────┐
│ LLM │ │ Embeddings│ │ Vector │
│Provider │ │ Provider │ │ Store │
└─────────┘ └───────────┘ └────────┘
│Ollama │ │HuggingFace│ │Chroma │
│OpenAI │ │ Ollama │ │Qdrant │
│Anthropic│ │ OpenAI │ └────────┘
└─────────┘ └───────────┘
┌──────────┐
│MCP Server│
│TypeScript│
└──────────┘
│Calculator│
│FileSystem│
│TextProc │
└──────────┘技术栈
| 组件 | 技术 | 目的 |
|---|---|---|
| 后端 | FastAPI+Python 3.10+ | 高性能异步API |
| RAG框架 | LlamaIndex | 文档索引和检索 |
| 用户界面 | Streamlit | 用户友好的聊天界面 |
| 配置 | Pydantic+YAML | 类型安全设置 |
| DI | 注入器 | 清除依赖注入 |
| 矢量数据库 | ChromaDB/Qdrant | 语义搜索 |
| 主控程序 | 模型上下文协议 | 外部工具集成 |
项目结构
xantus/
├── .env.example # Environment variable template
├── .gitignore # Git ignore patterns
├── config.yaml # Main configuration file
├── requirements.txt # Python dependencies
├── setup_mcp.sh # MCP setup automation
├── start_api.sh # API server startup script
├── start_ui.sh # UI startup script
│
├── xantus/ # Main application package
│ ├── __init__.py
│ ├── main.py # FastAPI application entry
│ ├── container.py # Dependency injection setup
│ │
│ ├── api/ # API endpoints
│ │ ├── chat_router.py # /v1/chat/completions
│ │ ├── ingest_router.py # /v1/ingest/*
│ │ └── embeddings_router.py # /v1/embeddings
│ │
│ ├── services/ # Business logic
│ │ ├── chat_service.py # RAG-powered chat
│ │ ├── ingest_service.py # Document processing
│ │ └── mcp_service.py # MCP tool orchestration
│ │
│ ├── components/ # Component factories
│ │ ├── llm/
│ │ │ └── llm_factory.py # LLM provider factory
│ │ ├── embeddings/
│ │ │ └── embedding_factory.py
│ │ └── vector_store/
│ │ └── vector_store_factory.py
│ │
│ ├── models/ # Data models
│ │ └── schemas.py # Pydantic request/response models
│ │
│ └── config/ # Configuration
│ └── settings.py # Settings management with Pydantic
│
├── ui/ # User interface
│ └── streamlit_app.py # Streamlit chat application
│
├── mcp-servers/ # MCP integration (git submodules)
│ └── mcp-starter-template-ts/ # TypeScript MCP server
│ ├── dist/ # Compiled JavaScript
│ │ └── start.js # Entry point
│ └── src/ # TypeScript source
│ └── tools/ # Tool implementations
│
├── data/ # Data directory (gitignored)
│ └── vector_store/ # Persisted vector embeddings
│
└── docs/ # Documentation
├── MCP_INTEGRATION.md # MCP technical guide
├── README_MCP.md # MCP quick start
└── SETUP_COMPLETE.md # Setup summary______________________________________________________________________
快速开始
先决条件
- Python 3.10+ (检查:
python --version) - Node.js 18+ (对于MCP集成,请检查:
node --version) - Git (用于克隆子模块)
- (可选)Ollama (适用于本地AI)
安装
步骤1:克隆存储库
# Clone with MCP submodules
git clone --recurse-submodules https://github.com/onamfc/rag-chat
cd xantus
# OR if you already cloned without submodules:
git submodule update --init --recursive第二步:创建虚拟环境
# Create virtual environment
python -m venv venv
# Activate it
source venv/bin/activate # Linux/Mac
# OR
venv\Scripts\activate # Windows步骤3:安装Python依赖项
pip install -r requirements.txt步骤4:设置MCP(可选但推荐)
# This will:
# - Initialize MCP submodules
# - Install npm dependencies
# - Build TypeScript MCP server
./setup_mcp.sh步骤5:配置环境变量
# Copy the example file
cp .env.example .env
# Edit .env and add your API keys (if using cloud providers)
# For Anthropic:
XANTUS_LLM__API_KEY=sk-ant-api03-your-key-here
# For OpenAI:
# XANTUS_LLM__API_KEY=sk-your-openai-key-here步骤6:配置设置
编辑 config.yaml 选择您的供应商:
选项A:完全本地(隐私优先)
llm:
provider: ollama
model: llama3.2
embedding:
provider: huggingface
model: BAAI/bge-small-en-v1.5
mcp:
enabled: true # Enable MCP tools选项B:云驱动(人工智能)
llm:
provider: anthropic
model: claude-sonnet-4-20250514
api_key: null # Read from .env
embedding:
provider: huggingface # Keep embeddings local
model: BAAI/bge-small-en-v1.5
mcp:
enabled: true选项C:OpenAI
llm:
provider: openai
model: gpt-4
api_key: null # Read from .env
embedding:
provider: openai
model: text-embedding-3-small
api_key: null首次运行
启动API服务器
# Option 1: Using the startup script
./start_api.sh
# Option 2: Manual start
python -m xantus.main
# The API will be available at http://localhost:8000
# API docs at http://localhost:8000/docs您应该看到:
INFO - Starting Xantus application...
INFO - Loaded settings with LLM provider: anthropic
INFO - Dependency injection container initialized
INFO - Starting server on 127.0.0.1:8000启用MCP后,您还将看到:
INFO - Starting MCP server 'mcp-starter-template': node mcp-servers/...
INFO - Loaded 4 tools from 'mcp-starter-template': ['calculate', 'filesystem', 'text-processing', 'weather']启动UI(在新终端中)
# Activate venv again
source venv/bin/activate
# Start Streamlit
streamlit run ui/streamlit_app.py
# The UI will open in your browser at http://localhost:8501上传文档并聊天!
- 点击 “上载文档” 在侧边栏中
- 选择PDF、TXT、DOCX或Markdown文件
- 等待处理(您将看到进度)
- 询问有关文档的问题!
示例问题:
- “本文档的主要主题是什么?”
- “总结要点”
- “计算第3节中提到的总收入”(使用MCP计算器)
- “将其与./reports/2023.pdf中的文件进行比较”(使用MCP文件系统)
______________________________________________________________________
MCP集成
MCP(模型上下文协议)允许Claude在回答问题时使用外部工具。
有哪些可用的工具?
您的TypeScript MCP服务器(位于 mcp-servers/mcp-starter-template-ts/)提供:
| 工具 | 功能 | 示例使用 |
|---|---|---|
| 计算器 | 数学运算 | “计算Q1-Q4收入之和” |
| 文件系统 | 读/写/列出文件 | “在../reports/中与去年的报告进行比较” |
| 文本处理 | 字数、情绪、案例转换 | “分析客户反馈情绪” |
| 天气 | 天气数据(模拟) | “检查天气以制定活动计划” |
MCP架构
User Question
↓
Xantus retrieves document context (RAG)
↓
Sends to Claude with available MCP tools
↓
Claude decides to use a tool (e.g., calculator)
↓
Xantus forwards tool call to MCP server (TypeScript)
↓
MCP server executes tool and returns result
↓
Claude incorporates result into answer
↓
User gets comprehensive response启用/禁用MCP
在 config.yaml:
mcp:
enabled: true # Set to false to disable MCP
servers:
- name: "mcp-starter-template"
command: "node"
args: ["mcp-servers/mcp-starter-template-ts/dist/start.js"]添加更多MCP服务器
您可以连接多个MCP服务器:
mcp:
enabled: true
servers:
# Your custom tools
- name: "my-tools"
command: "node"
args: ["mcp-servers/mcp-starter-template-ts/dist/start.js"]
# Database access
- name: "postgres"
command: "npx"
args: ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"]
# Web search
- name: "brave-search"
command: "npx"
args: ["-y", "@modelcontextprotocol/server-brave-search"]MCP文件
对于完整的MCP设置和定制:
- 快速开始:
README_MCP.md
______________________________________________________________________
配置
环境变量
创建一个 .env 项目根目录中的文件:
# ===== LLM API Keys =====
# For Anthropic (double underscore for nested config!)
XANTUS_LLM__API_KEY=sk-ant-api03-your-key-here
# For OpenAI
# XANTUS_LLM__API_KEY=sk-your-openai-key-here
# ===== Embedding API Keys (optional) =====
# XANTUS_EMBEDDING__API_KEY=sk-your-key-here
# ===== Override Other Settings =====
# Format: XANTUS_
__=value
# Examples:
# XANTUS_LLM__TEMPERATURE=0.5
# XANTUS_RAG__SIMILARITY_TOP_K=10
# XANTUS_SERVER__PORT=8001重要:使用 双下划线 (__)用于嵌套配置!
提供商设置
Ollama的本地设置
- 安装Ollama: https://ollama.com/download
- 启动Ollama:
ollama serve- 拉模型:
ollama pull llama3.2 # For chat
ollama pull nomic-embed-text # For embeddings- 配置
config.yaml:
llm:
provider: ollama
model: llama3.2
api_base: http://localhost:11434 # Default
embedding:
provider: ollama
model: nomic-embed-text拟人设置
- 获取API密钥: https://console.anthropic.com/
- 添加到
.env:
XANTUS_LLM__API_KEY=sk-ant-api03-your-key-here- 配置
config.yaml:
llm:
provider: anthropic
model: claude-sonnet-4-20250514
api_key: null # Read from environment
temperature: 0.7
max_tokens: 4096
embedding:
provider: huggingface # Use local for cost savings
model: BAAI/bge-small-en-v1.5OpenAI设置
- 获取API密钥: https://platform.openai.com/api-keys
- 添加到
.env:
XANTUS_LLM__API_KEY=sk-your-openai-key-here- 配置
config.yaml:
llm:
provider: openai
model: gpt-4-turbo-preview
api_key: null
embedding:
provider: openai
model: text-embedding-3-small
api_key: nullRAG调谐
微调检索 config.yaml:
rag:
# Number of relevant chunks to retrieve
similarity_top_k: 5
# Size of text chunks (characters)
chunk_size: 1024
# Overlap between chunks (prevents context loss)
chunk_overlap: 200
# Enable advanced reranking (requires additional setup)
enable_reranking: false调整指南:
- 大块 (1024-2048):更适合长篇内容
- 小块 (512-1024):更适合具体事实
- 更高的top_k (8-10):上下文更多,但速度较慢
- 下顶_k (3-5):速度更快,但可能会错过上下文
- 重叠:建议使用chunk_size的15-20%
矢量存储配置
vector_store:
provider: chroma # or qdrant
# Path to persist vector data
persist_path: ./data/vector_store
# Collection name
collection_name: xantus_documents服务器配置
server:
host: 127.0.0.1 # Change to 0.0.0.0 for network access
port: 8000
# CORS settings
cors_enabled: true
cors_origins:
- "*" # Be more restrictive in production!______________________________________________________________________
用法
流线型UI
使用Xantus的最简单方法:
- 启动API (终端1):
./start_api.sh- 启动UI (终端2):
./start_ui.sh
# OR
streamlit run ui/streamlit_app.py- 导航至 http://localhost:8501
- 上传文件 通过侧边栏
- 聊天 和你的文件!
特性:
- ✅ 文档上传进度
- ✅ 文档管理(列表/删除)
- ✅ 聊天历史记录
- ✅ 上下文切换(是否使用RAG)
- ✅ 健康监测
API终点
健康检查
curl http://localhost:8000/health答复:
{
"status": "healthy",
"version": "0.1.0",
"components": {
"llm": "anthropic",
"embedding": "huggingface",
"vector_store": "chroma"
}
}聊天完成(与RAG)
curl -X POST http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"messages": [
{"role": "user", "content": "What are the main findings in the report?"}
],
"use_context": true,
"stream": false
}'答复:
{
"id": "chat-123abc",
"object": "chat.completion",
"created": 1730000000,
"model": "claude-sonnet-4-20250514",
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "Based on the documents, the main findings are..."
},
"finish_reason": "stop"
}]
}上传文档
curl -X POST http://localhost:8000/v1/ingest/file \
-F "file=@/path/to/document.pdf"答复:
{
"status": "success",
"document_id": "doc_abc123",
"chunks_created": 42
}列出文件
curl http://localhost:8000/v1/ingest/documents删除文档
curl -X DELETE http://localhost:8000/v1/ingest/documents/doc_abc123生成嵌入
curl -X POST http://localhost:8000/v1/embeddings \
-H "Content-Type: application/json" \
-d '{"input": "Text to embed", "model": "default"}'Python客户端
import requests
# Start a session
session = requests.Session()
api_url = "http://localhost:8000"
# Upload a document
with open("document.pdf", "rb") as f:
response = session.post(
f"{api_url}/v1/ingest/file",
files={"file": f}
)
print(f"Uploaded: {response.json()}")
# Chat with RAG
response = session.post(
f"{api_url}/v1/chat/completions",
json={
"messages": [
{"role": "user", "content": "Summarize the key points"}
],
"use_context": True,
"stream": False
}
)
result = response.json()
print(result["choices"][0]["message"]["content"])______________________________________________________________________
发展
项目理念
- 隐私第一:默认为本地,支持云
- 模块化:易于更换任何组件
- 简洁:最小抽象
- 类型安全:到处都是双关语
- 生产就绪:正确的DI、错误处理、日志记录
添加新的LLM提供程序
- 添加到设置 (
xantus/config/settings.py):
provider: Literal["ollama", "openai", "anthropic", "your-provider"]- 执行工厂 (
xantus/components/llm/llm_factory.py):
def _create_your_provider_llm(config: LLMConfig) -> LLM:
return YourProviderLLM(
model=config.model,
api_key=config.api_key,
temperature=config.temperature
)- 更新工厂调度:
elif config.provider == "your-provider":
return _create_your_provider_llm(config)添加新的矢量存储
类似的过程 xantus/components/vector_store/vector_store_factory.py
代码的风格
# Format code
black xantus/
# Lint
ruff check xantus/
# Type check
mypy xantus/测试
# Install test dependencies
pip install pytest pytest-asyncio
# Run tests
pytest tests/______________________________________________________________________
故障排除
常见问题
1.“无法连接到Ollama”
解决方案:确保Olama正在运行
ollama serve2.“ValueError:需要Anthropic API密钥”
解决方案:检查您的 .env 文件:
# Correct (double underscore!):
XANTUS_LLM__API_KEY=sk-ant-...
# Wrong (single underscore):
XANTUS_LLM_API_KEY=sk-ant-...3.“导入错误:没有名为'xantus'的模块”
解决方案:确保你在正确的目录中
cd xantus
python -c "import xantus; print('OK')"4.“MCP服务器未启动”
解决方案:构建MCP服务器
./setup_mcp.sh
# OR manually:
cd mcp-servers/mcp-starter-template-ts
npm install
npm run build5.“端口8000已在使用中”
解决方案:终止现有进程或更改端口
# Kill existing
pkill -f "python.*xantus"
# OR change port in config.yaml:
server:
port: 80016.“矢量存储错误”
解决方案:清除并重新创建
rm -rf data/vector_store
mkdir -p data/vector_store
# Restart server, re-upload documents调试模式
启用详细日志记录:
# In xantus/main.py
import logging
logging.basicConfig(level=logging.DEBUG)______________________________________________________________________
常见问题解答
Q: 我的数据会离开我的机器吗? A: 仅当您使用云提供商(OpenAI/Anthropic)时。有了Olrama+HuggingFace,一切都保持在当地。
Q: 哪个更快——本地还是云? A: 云(OpenAI/Anthropic)通常更快。本地(Ollama)取决于您的硬件。
Q: 我可以使用多个文档吗? A: 是的!上传任意数量。它们都在矢量存储中被索引。
Q: 文档的最大尺寸是多少? A: 没有硬性限制,但处理较大的文档需要更长的时间。
Q: 我可以删除文档吗? A: 是,通过API /v1/ingest/documents/{doc_id} 或流式UI。
Q: 是否支持流媒体? A: 是的!集 "stream": true 在聊天完成请求中。
Q: 什么LLM是最好的? A.
- 最佳品质:克劳德·十四行诗4,GPT-4
- 最佳本地:拉玛3.2,米斯特拉尔
- 最佳平衡:克劳德·海库,GPT-3.5涡轮增压
Q: 如何添加身份验证? A: 在中添加FastAPI中间件 xantus/main.py 用于API密钥或OAuth。
______________________________________________________________________
额外资源
- MCP快速入门:
README_MCP.md - API文档: http://localhost:8000/docs(运行时)
- LlamaIdex文档: https://docs.llamaindex.ai/
- FastAPI文档: https://fastapi.tiangolo.com/
- 简化文档: https://docs.streamlit.io/
______________________________________________________________________
贡献
欢迎投稿!该项目旨在:
- 易于理解
- 易于扩展
- 有据可查
请随意:
- 添加新提供者
- 优化用户界面
- 增强MCP工具
- 修复bug
- 改进文档
______________________________________________________________________
许可证
本项目按原样提供,用于教育和研究目的。
______________________________________________________________________
内置:
______________________________________________________________________
由以下材料制成❤️ 对于开源社区
