企业知识代理平台
   
一个采用现代AI Agent架构构建的生产就绪型企业知识管理系统,具有MCP协议支持、多LLM集成、混合RAG检索和全面可观察性。
目录
概述
企业知识代理是一个基于人工智能的系统,旨在帮助组织管理和查询其内部知识库。它将最先进的检索技术与智能代理功能相结合,提供准确的上下文响应和适当的源引用。
关键能力
- 智能文档检索:结合向量相似度和BM25关键字匹配的混合搜索
- 具有推理能力的AI代理:基于ReAct的代理,可以计划多步查询
- MCP协议支持:与Claude Desktop、Cursor和其他MCP兼容客户端集成
- 多LLM灵活性:在OpenAI、Anthropic Claude或当地Ollama模型之间切换
- 生产准备就绪:完成身份验证、速率限制、可观察性和部署配置
目标用例
- 企业知识库搜索
- 内部文件问答
- 人力资源政策咨询
- 技术文件协助
- 客户支持知识管理
建筑
┌────────────────────────────────────────────────────────────────────────┐
│ Enterprise Knowledge Agent Platform │
├────────────────────────────────────────────────────────────────────────┤
│ Interface Layer │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────────┐│
│ │ FastAPI REST │ │ CLI Tool │ │ MCP Server ││
│ │ (Human/Systems) │ │ (Development) │ │ (Claude, Cursor, etc.) ││
│ └────────┬────────┘ └────────┬────────┘ └────────────┬────────────┘│
├───────────┴────────────────────┴────────────────────────┴─────────────┤
│ Agent Core Layer │
│ ┌────────────────────────────────────────────────────────────────┐ │
│ │ Agent Orchestrator │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌────────────────────┐ │ │
│ │ │Query Router │→ │ReAct Engine │→ │Response Synthesizer│ │ │
│ │ │(Intent) │ │(Reasoning) │ │(Citation + Format) │ │ │
│ │ └──────────────┘ └──────────────┘ └────────────────────┘ │ │
│ └────────────────────────────────────────────────────────────────┘ │
├───────────────────────────────────────────────────────────────────────┤
│ RAG Pipeline Layer │
│ ┌─────────────┐ ┌────────────────┐ ┌─────────────┐ ┌───────────┐ │
│ │ Ingestion │ │ Hybrid Search │ │ Reranker │ │ Memory │ │
│ │ Pipeline │ │ Vector + BM25 │ │ (BGE) │ │ Store │ │
│ └─────────────┘ └────────────────┘ └─────────────┘ └───────────┘ │
├───────────────────────────────────────────────────────────────────────┤
│ Infrastructure Layer │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌──────────────┐ │
│ │ Qdrant │ │ Redis │ │ Postgres │ │ S3/MinIO │ │
│ │ (Vectors) │ │ (Cache) │ │ (Metadata) │ │ (Files) │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ └──────────────┘ │
├───────────────────────────────────────────────────────────────────────┤
│ Observability Layer │
│ ┌─────────────────────────┐ ┌────────────────────────────────────┐ │
│ │ Arize Phoenix │ │ Prometheus + Grafana │ │
│ │ (LLM Tracing) │ │ (System Metrics) │ │
│ └─────────────────────────┘ └────────────────────────────────────┘ │
└───────────────────────────────────────────────────────────────────────┘设计原则
该系统遵循 六边形架构(端口和适配器) 图案:
- 核心层:RAG管道和代理逻辑,独立于接口
- 适配器:FastAPI REST、MCP服务器、CLI——都共享同一个核心
- 可扩展:易于添加新的LLM提供者、工具或接口
特性
| 类别 | 功能 | 描述 |
|---|---|---|
| RAG 流程 | 多格式加载 | 支持PDF、Markdown、TXT文档 |
| 智能分块 | 固定、句子和语义分块策略 | |
| 混合搜索 | 向量相似度+BM25与互序融合 | |
| 交叉编码器重新排序 | BGE重新排序以提高精度 | |
| 自动引用 | 自动源跟踪和引用 | |
| 代理 | 意图分类 | 查询路由器以获得最佳响应策略 |
| 再行动推理 | 多步骤规划和执行 | |
| 工具系统 | 自定义工具的可扩展注册表模式 | |
| 接口 | REST API | 使用OpenAPI文档实现完整的FastAPI |
| MCP协议 | 兼容克劳德桌面、光标等。 | |
| 流媒体 | 服务器发送实时响应事件 | |
| 多LLM | OpenAI | GPT-4、GPT-4涡轮增压、GPT-3.5涡轮增压 |
| 人类学 | 克劳德3作品,十四行诗,俳句 | |
| Ollama | 本地模型(Calma 3,Mistral等) | |
| 安全 | 认证 | API密钥和JWT承载令牌支持 |
| 速率限制 | 可配置的每个端点限制 | |
| 可观测性 | 追踪 | Arize Phoenix用于LLM呼叫追踪 |
| 指标 | 普罗米修斯指标导出 | |
| 评估 | Ragas框架集成 | |
| 部署 | Docker | Dockerfile和Docker Compose设置 |
| Kubernetes | k8s部署的完整清单集 | |
| CI/CD | GitHub操作工作流 |
快速开始
先决条件
- Python 3.11+
- Docker和Docker Compose
- OpenAI API密钥(或Anthropic/Ollama)
5分钟设置
# 1. Clone the repository
git clone https://github.com/yourusername/enterprise-knowledge-agent.git
cd enterprise-knowledge-agent
# 2. Install dependencies
poetry install
# 3. Set up environment
cp .env.example .env
# Edit .env and add your OPENAI_API_KEY
# 4. Start infrastructure (Qdrant, Redis, PostgreSQL)
docker compose -f deployment/docker-compose/docker-compose.yml up -d qdrant redis
# 5. Ingest sample documents
poetry run python -m src.cli ingest examples/sample_documents/
# 6. Start the API server
poetry run uvicorn src.api.main:app --reload
# 7. Try a query
curl -X POST http://localhost:8000/api/v1/chat \
-H "Content-Type: application/json" \
-H "X-API-Key: dev-key" \
-d '{"message": "What are the remote work guidelines?"}'安装
使用诗歌(推荐)
# Install Poetry if you haven't
curl -sSL https://install.python-poetry.org | python3 -
# Install project dependencies
poetry install
# Activate virtual environment
poetry shell使用pip
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # Linux/Mac
# or .venv\Scripts\activate # Windows
# Install dependencies
pip install -e .基础设施设置
# Start all services with Docker Compose
docker compose -f deployment/docker-compose/docker-compose.yml up -d
# Or start individual services
docker run -d -p 6333:6333 qdrant/qdrant # Vector DB
docker run -d -p 6379:6379 redis:alpine # Cache
docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=password postgres:15 # Metadata用法
命令行界面
# Ingest documents
poetry run python -m src.cli ingest ./documents/
# Interactive query
poetry run python -m src.cli query "What is our vacation policy?"
# Get system status
poetry run python -m src.cli statusREST API
启动服务器:
poetry run uvicorn src.api.main:app --reload --port 8000API终点:
| 方法 | 端点 | 描述 |
|---|---|---|
POST | /api/v1/chat | 与知识库聊天 |
POST | /api/v1/chat/stream | 流媒体聊天(SSE) |
POST | /api/v1/search | 搜索文档 |
POST | /api/v1/ingest | 上传文档 |
GET | /api/v1/documents | 列出文件 |
GET | /health | 健康检查 |
GET | /metrics | 普罗米修斯指标 |
请求示例:
# Chat (non-streaming)
curl -X POST http://localhost:8000/api/v1/chat \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key" \
-d '{
"message": "How many vacation days do new employees get?",
"top_k": 5
}'
# Search documents
curl -X POST http://localhost:8000/api/v1/search \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key" \
-d '{
"query": "remote work",
"top_k": 10
}'
# Ingest document
curl -X POST http://localhost:8000/api/v1/ingest \
-H "X-API-Key: your-api-key" \
-F "file=@document.pdf"交互式文档可在以下网址获得: http://localhost:8000/docs
MCP服务器
MCP服务器支持与Claude Desktop、Cursor和其他MCP兼容客户端的集成。
Claude桌面设置
添加到您的Claude桌面配置(~/.config/claude/mcp_servers.json):
{
"knowledge-agent": {
"command": "python",
"args": ["-m", "src.mcp_server.server"],
"cwd": "/path/to/enterprise-knowledge-agent",
"env": {
"OPENAI_API_KEY": "your-key"
}
}
}可用的MCP工具
| 工具 | 说明 | 参数 |
|---|---|---|
query_knowledge_base | 从知识库中搜索和回答 | query: str, top_k: int |
get_knowledge_base_stats | 获取收集统计信息 | -- |
search_documents | 按元数据查找文档 | filename_pattern: str, file_type: str |
agent_query | 执行多步骤推理查询 | query: str, max_iterations: int |
可用MCP资源
| 资源 | 描述 |
|---|---|
documents://list | 列出知识库中的所有文档 |
stats://knowledge-base | 知识库统计 |
配置
环境变量
创建一个 .env 文件基于 .env.example:
# LLM Providers
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
OLLAMA_BASE_URL=http://localhost:11434
# Default LLM Settings
LLM_PROVIDER=openai # openai, anthropic, ollama
LLM_MODEL=gpt-4 # Model name
LLM_TEMPERATURE=0.7
LLM_MAX_TOKENS=2048
# Vector Database
QDRANT_URL=http://localhost:6333
QDRANT_COLLECTION=knowledge_base
# Cache & Database
REDIS_URL=redis://localhost:6379
POSTGRES_URL=postgresql://user:pass@localhost:5432/knowledge_agent
# Observability
PHOENIX_ENDPOINT=http://localhost:6006
PROMETHEUS_ENABLED=true
# API Settings
APP_ENV=development
LOG_LEVEL=INFO配置文件
| 文件 | 目的 |
|---|---|
configs/settings.yaml | 主要应用程序设置 |
configs/llm_configs/default.yaml | LLM提供程序配置 |
configs/observability.yaml | 跟踪和指标设置 |
发展
项目结构
enterprise-knowledge-agent/
├── src/
│ ├── agent/ # Agent orchestrator, router, ReAct engine
│ ├── api/ # FastAPI routes, middleware, schemas
│ ├── llm/ # LLM provider abstraction
│ ├── mcp_server/ # MCP protocol implementation
│ ├── observability/ # Tracing, metrics, evaluation
│ └── rag/ # RAG pipeline (ingestion, retrieval, generation)
├── configs/ # YAML configuration files
├── deployment/ # Docker, Kubernetes, scripts
├── docs/ # Documentation
├── examples/ # Sample documents and notebooks
├── tests/ # Unit, integration, e2e tests
└── scripts/ # Utility scripts代码质量
# Format code
poetry run black src/ tests/
poetry run isort src/ tests/
# Lint
poetry run ruff check src/ tests/
# Type check
poetry run mypy src/添加新的LLM提供程序
- 在中创建提供程序类
src/llm/providers/:
from src.llm.base import BaseLLMProvider, LLMConfig
class MyProvider(BaseLLMProvider):
@property
def provider_name(self) -> str:
return "my_provider"
async def generate(self, messages, **kwargs) -> LLMResponse:
# Implementation
pass
async def generate_stream(self, messages, **kwargs):
# Implementation
pass- 注册
src/llm/factory.py - 在中添加配置
configs/llm_configs/
添加新的MCP工具
- 在中创建工具
src/agent/tools/:
from src.agent.tools import BaseTool, ToolParameter, ToolResult
class MyTool(BaseTool):
@property
def name(self) -> str:
return "my_tool"
@property
def description(self) -> str:
return "Description for LLM"
@property
def parameters(self) -> list[ToolParameter]:
return [
ToolParameter(name="param1", type=str, required=True)
]
async def execute(self, **kwargs) -> ToolResult:
# Implementation
return ToolResult(success=True, data={...})- 注册
src/agent/tools/__init__.py - 在中添加MCP包装器
src/mcp_server/server.py
部署
Docker编写(开发/阶段)
# Start all services
docker compose -f deployment/docker-compose/docker-compose.yml up -d
# View logs
docker compose -f deployment/docker-compose/docker-compose.yml logs -f app
# Stop services
docker compose -f deployment/docker-compose/docker-compose.yml downKubernetes(生产)
# Apply manifests
kubectl apply -f deployment/kubernetes/
# Check status
kubectl get pods -l app=knowledge-agent
# View logs
kubectl logs -l app=knowledge-agent -f环境特定配置
| 环境 | 配置 |
|---|---|
| 开发 | 单副本、调试日志记录、热重新加载 |
| 暂存 | 2个副本、信息记录、集成测试 |
| 生产 | 4个以上副本,警告日志记录,全面监控 |
测试
# Run all tests
poetry run pytest
# Run with coverage
poetry run pytest --cov=src --cov-report=html
# Run specific test categories
poetry run pytest tests/unit/ # Unit tests
poetry run pytest tests/integration/ # Integration tests
poetry run pytest tests/e2e/ # End-to-end tests
# Run MCP server tests
poetry run python scripts/test_mcp_server.py测试类别
| 类别 | 描述 | 标记 |
|---|---|---|
| 单元 | 单个组件测试 | -- |
| 集成 | 多组件测试 | @pytest.mark.integration |
| E2E | 全系统测试 | @pytest.mark.e2e |
| 缓慢 | 长时间运行测试 | @pytest.mark.slow |
文档
| 文档 | 描述 |
|---|---|
| 建筑.md | 系统架构详细信息 |
| 框架_评估.md | LangChain与Llama指数分析 |
| 最佳实践.md | AI Agent开发指南 |
| API_REFERENCE.md | 完整的API文件 |
| 部署\_ GIDE.md | 生产部署指南 |
路线图
完成
- \[x\] 第一阶段:基本RAG管道——文档摄取、分块、矢量搜索
- \[x\] 第2阶段:高级检索——混合搜索、重新排序、引用
- \[x\] 第三期:代理+MCP——查询路由器、ReAct引擎、MCP服务器
- \[x\] 阶段4:Multi-LLM+API-提供程序抽象、FastAPI、流
- \[x\] 阶段5:可观测性——凤凰追踪、普罗米修斯度量、拉加斯评估
- \[x\] 第6阶段:部署——Docker、Kubernetes、CI/CD
未来的增强功能
- \[\]多租户支持
- \[\]文档版本控制
- \[\]高级对话记忆
- \[\]自定义嵌入模型微调
- \[\]GraphRAG集成
- \[\]语音接口支持
性能指标
| 指标 | 目标 | 已实现 |
|---|---|---|
| 查询延迟(p95) | \0.85 | 评估就绪 |
| 答案可信度 | >0.90 | 评估就绪 |
| MCP工具成功率 | >95% | 100%(6/6次测试) |
许可证
该项目根据MIT许可证获得许可——请参阅 许可证 文件以获取详细信息。
致谢
- FastMCP --MCP实施框架
- Llama索引 --RAG管道设计灵感
- LangChain --代理框架模式
- Qdrant --矢量数据库
- 干旱凤凰 --LLM可观测性
- 拉格 --RAG评估框架
- 句子变换器 --重新排列模型
- 排名bm25 --BM25实施
联系
有关此项目的问题或讨论,请在GitHub上打开问题。
______________________________________________________________________
Built with ❤️ as a portfolio project demonstrating enterprise AI Agent development
All 6 phases complete! 🎉
