WeKnora RAG框架深度解析:构建企业级文档理解与智能检索系统的实战指南
WeKnora是一款开源的、基于大语言模型(LLM)的知识管理框架,专为企业级文档理解、语义检索与智能推理场景打造。该项目围绕三大核心能力构建:RAG快速问答、ReAct Agent智能推理和Wiki模式,支持从原始文档到可查询知识库的全流程自动化处理。作为企业级RAG框架,WeKnora采用模块化架构,支持多模态输入、混合检索策略和知识图谱增强,能够将分散文档沉淀为可查询、可推理、可持续演进的专属知识资产。
一、技术概览与架构设计
1.1 系统架构解析
WeKnora采用分层架构设计,将文档处理、检索增强和智能生成解耦,形成完整的技术栈。系统架构图清晰展示了从输入渠道到核心引擎再到外部服务的完整技术链路。
核心架构模块包括:
- 输入渠道层:支持Web UI & API、6种IM机器人渠道(企业微信、飞书、Slack等)、网站嵌入Widget、MCP Server、浏览器扩展和CLI工具,实现多场景接入能力
- 文档处理引擎:包含多格式解析器(支持EPUB/MHTML等格式)、智能分块(Chunking)、向量嵌入(Embedding)、知识图谱构建和Wiki生成模块
- RAG & Agent引擎:实现查询理解、混合检索(BM25+向量+图检索)、ReACT代理循环和响应生成(SSE流式输出)
- 存储层:采用多类型存储系统,包括PostgreSQL关系数据库、8+向量数据库后端、可选Neo4j图数据库、7种对象存储服务和Redis缓存
- 外部服务集成:支持20+ LLM提供商、网络搜索服务、MCP工具(带OAuth2认证)、数据源和Langfuse可观测性平台
1.2 核心技术栈
- 编程语言:Go(后端核心)+ Python(文档解析)+ TypeScript(前端)
- 数据库:PostgreSQL(主数据库)+ 向量数据库(pgvector/Elasticsearch等)+ Redis(缓存)
- 容器化:Docker + Docker Compose + Kubernetes(Helm Chart)
- 模型集成:支持OpenAI、DeepSeek、Qwen、智谱、混元、Gemini等主流LLM厂商
- 安全机制:AES-256-GCM加密、多租户RBAC、审计日志、SSRF防护
二、部署与配置实战
2.1 快速部署指南
通过Docker Compose可以快速部署完整的WeKnora服务栈:
# 克隆项目仓库
git clone https://gitcode.com/GitHub_Trending/we/WeKnora
cd WeKnora
# 启动所有服务
./scripts/start_all.sh
# 停止服务
./scripts/start_all.sh --stop
服务启动后访问地址:
- Web UI:
http://localhost - 后端API:
http://localhost:8080 - 链路追踪:
http://localhost:16686(如果启用Jaeger)
2.2 关键配置详解
首次访问Web UI会自动跳转到初始化配置页面,需要配置以下核心参数:
模型配置(config/config.yaml):
# LLM模型配置
llm:
provider: "openai"
model_name: "gpt-4"
base_url: "https://api.openai.com/v1"
api_key: "${OPENAI_API_KEY}"
# Embedding模型配置
embedding:
provider: "openai"
model_name: "text-embedding-3-small"
dimensions: 1536
# 向量数据库配置
vector_store:
provider: "pgvector"
connection_string: "postgresql://user:password@localhost:5432/weknora"
多模态处理配置:
vlm_config:
enabled: true
model_name: "qwen2.5vl:3b"
interface_type: "ollama"
base_url: "http://host.docker.internal:11435/v1"
asr_config:
enabled: true
model_path: "/path/to/whisper-model"
2.3 数据库初始化
系统支持多种数据库后端,初始化脚本位于migrations/目录:
# PostgreSQL初始化
docker-compose exec postgres psql -U postgres -d weknora -f /app/migrations/sqlite/001_initial_schema.sql
# 向量数据库索引创建
docker-compose exec app ./weknora migrate --vector-store pgvector
三、核心模块深度解析
3.1 文档处理流水线
WeKnora的文档处理流程遵循典型的RAG架构,从数据准备到最终生成形成完整闭环:
核心处理阶段:
- 数据加载与解析:支持PDF、Word、Excel、图片等10+种格式,通过docreader模块进行多引擎解析
- 智能分块策略:采用自适应三层分块,根据文档结构动态调整分块大小和重叠
- 向量化处理:使用OpenAI兼容API或Ollama模型生成文本向量表示
- 知识图谱构建:从文档中提取实体和关系,构建可查询的知识图谱
- 索引存储:将处理结果存入向量数据库和关系数据库
关键技术实现:
- 多格式解析器:
docreader/parser/目录包含各种文档格式的解析器 - 智能分块算法:
internal/infrastructure/chunker/实现自适应分块逻辑 - 向量嵌入服务:
internal/models/embedding/提供统一的Embedding接口
3.2 混合检索引擎
WeKnora采用混合检索策略,结合多种检索技术提升召回率和准确性:
// 混合检索实现示例(internal/application/service/retriever/composite.go)
type HybridRetriever struct {
bm25Retriever *BM25Retriever // BM25文本检索
denseRetriever *DenseRetriever // 向量相似度检索
graphRetriever *GraphRetriever // 图路径检索
reranker *Reranker // 重排序模型
}
func (h *HybridRetriever) Search(ctx context.Context, query string, options SearchOptions) ([]SearchResult, error) {
// 并行执行多种检索
var wg sync.WaitGroup
var results []SearchResult
// BM25检索
wg.Add(1)
go func() {
defer wg.Done()
bm25Results := h.bm25Retriever.Search(query, options)
results = append(results, bm25Results...)
}()
// 向量检索
wg.Add(1)
go func() {
defer wg.Done()
denseResults := h.denseRetriever.Search(query, options)
results = append(results, denseResults...)
}()
// 图检索(如果启用)
if h.graphRetriever != nil && options.EnableGraphSearch {
wg.Add(1)
go func() {
defer wg.Done()
graphResults := h.graphRetriever.Search(query, options)
results = append(results, graphResults...)
}()
}
wg.Wait()
// 结果去重和重排序
results = deduplicateResults(results)
if h.reranker != nil {
results = h.reranker.Rerank(query, results)
}
return results, nil
}
检索策略优势:
- BM25检索:基于传统TF-IDF的文本匹配,适合精确关键词查询
- 向量检索:基于语义相似度的深度匹配,适合语义相近但词汇不同的查询
- 图检索:基于知识图谱的关系推理,适合需要上下文关联的复杂查询
- 重排序:使用LLM对初步结果进行相关性重排,提升最终结果质量
3.3 Agent推理引擎
WeKnora的Agent引擎基于ReACT(Reasoning and Acting)框架,支持复杂多步推理:
// Agent引擎核心逻辑(internal/agent/engine.go)
type AgentEngine struct {
llmClient LLMClient
toolRegistry *ToolRegistry
memory MemoryManager
maxIterations int
}
func (e *AgentEngine) Run(ctx context.Context, query string, knowledgeBaseID string) (*AgentResponse, error) {
var thoughts []string
var actions []ToolCall
var observation string
// ReACT循环
for i := 0; i < e.maxIterations; i++ {
// 思考阶段:LLM分析当前状态并决定下一步行动
thought, action := e.think(ctx, query, observation, thoughts, actions)
thoughts = append(thoughts, thought)
if action.Type == "final_answer" {
// 生成最终答案
return e.generateFinalAnswer(ctx, thoughts, query)
}
// 执行阶段:调用工具
observation = e.act(ctx, action)
actions = append(actions, action)
// 更新记忆
e.memory.AddStep(query, thought, action, observation)
}
return e.handleMaxIterations(ctx, thoughts, query)
}
Agent能力特性:
- 支持工具调用(内置工具、MCP工具、网络搜索)
- 多轮对话上下文管理
- 知识库检索增强
- 自主决策和推理链构建
四、知识库管理与可视化
4.1 知识库创建与管理
通过Web界面或API可以轻松创建和管理知识库:
知识库类型支持:
- FAQ知识库:适合问答对形式的静态知识
- 文档知识库:支持PDF、Word、Excel等文档格式
- Wiki知识库:Agent自动从文档生成结构化Wiki页面
API创建示例:
curl -X POST "http://localhost:8080/api/v1/knowledge-bases" \
-H "Content-Type: application/json" \
-H "X-API-Key: your_api_key" \
-d '{
"name": "技术文档库",
"description": "公司技术文档集合",
"type": "document",
"chunking_config": {
"chunk_size": 1000,
"chunk_overlap": 200,
"strategy": "recursive"
},
"retrieval_config": {
"enable_bm25": true,
"enable_vector": true,
"enable_graph": false,
"top_k": 10,
"rerank_enabled": true
}
}'
4.2 知识图谱可视化
WeKnora的知识图谱功能能够自动从文档中提取实体和关系,构建可视化的知识网络:
图谱构建流程:
- 实体提取:使用NER技术从文档中识别命名实体
- 关系抽取:分析实体间的语义关系
- 图谱构建:将实体和关系存储到图数据库(Neo4j)
- 可视化渲染:使用D3.js等前端技术进行交互式展示
图谱检索优势:
- 支持关系路径查询,发现隐藏的关联
- 提供上下文感知的检索结果
- 增强复杂查询的推理能力
五、API集成与二次开发
5.1 RESTful API设计
WeKnora提供完整的RESTful API,支持知识库管理、文档检索、智能问答等功能:
核心API端点:
GET /api/v1/knowledge-bases- 获取知识库列表POST /api/v1/knowledge-bases- 创建知识库POST /api/v1/knowledge-bases/{id}/knowledge/file- 上传文档到知识库POST /api/v1/chat/completions- 智能对话接口POST /api/v1/search- 语义检索接口
认证机制:
# API Key认证
curl -H "X-API-Key: your_api_key" \
-H "Content-Type: application/json" \
http://localhost:8080/api/v1/knowledge-bases
# JWT Token认证(企业版)
curl -H "Authorization: Bearer your_jwt_token" \
http://localhost:8080/api/v1/chat/completions
5.2 客户端SDK使用
项目提供Go语言客户端SDK,简化集成开发:
package main
import (
"context"
"fmt"
"github.com/weknora/client"
)
func main() {
// 初始化客户端
cfg := &client.Config{
BaseURL: "http://localhost:8080",
APIKey: "your_api_key",
}
cli, err := client.New(cfg)
if err != nil {
panic(err)
}
// 创建知识库
kbReq := &client.CreateKnowledgeBaseRequest{
Name: "技术文档",
Description: "技术团队文档库",
Type: "document",
}
kb, err := cli.KnowledgeBase.Create(context.Background(), kbReq)
if err != nil {
panic(err)
}
fmt.Printf("创建知识库成功: %s\n", kb.ID)
// 上传文档
file, _ := os.Open("document.pdf")
defer file.Close()
uploadReq := &client.UploadKnowledgeRequest{
KnowledgeBaseID: kb.ID,
File: file,
FileName: "document.pdf",
ProcessConfig: &client.ProcessConfig{
ChunkSize: 1000,
ChunkOverlap: 200,
},
}
result, err := cli.Knowledge.UploadFile(context.Background(), uploadReq)
if err != nil {
panic(err)
}
fmt.Printf("文档上传成功,任务ID: %s\n", result.TaskID)
}
5.3 自定义插件开发
WeKnora支持通过MCP(Model Context Protocol)扩展工具能力:
MCP服务器开发示例:
# mcp-server/main.py
from mcp import Client, StdioServerTransport
import asyncio
class CustomToolServer:
def __init__(self):
self.tools = [
{
"name": "get_weather",
"description": "获取指定城市的天气信息",
"inputSchema": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称"}
},
"required": ["city"]
}
}
]
async def handle_tool_call(self, tool_name, arguments):
if tool_name == "get_weather":
city = arguments.get("city", "北京")
# 调用天气API
return f"{city}的天气是晴,温度25°C"
return "工具未找到"
async def main():
server = CustomToolServer()
transport = StdioServerTransport()
client = Client(transport)
# 注册工具
await client.initialize(tools=server.tools)
# 处理请求
async for message in client.listen():
if message.type == "tool_call":
result = await server.handle_tool_call(
message.tool_name,
message.arguments
)
await client.send_tool_result(message.call_id, result)
if __name__ == "__main__":
asyncio.run(main())
六、高级功能与扩展
6.1 多租户RBAC系统
WeKnora提供企业级的多租户权限管理系统,支持四级角色矩阵:
角色权限矩阵:
- Owner:完全控制权,可管理租户所有资源
- Admin:管理权限,可管理用户和知识库
- Contributor:贡献者,可创建和编辑内容
- Viewer:查看者,只读权限
权限配置示例(config/config.yaml):
rbac:
enabled: true
default_roles:
- name: "owner"
permissions: ["*"]
- name: "admin"
permissions: ["knowledge_base.*", "user.manage", "document.*"]
- name: "contributor"
permissions: ["knowledge_base.create", "document.upload", "document.edit"]
- name: "viewer"
permissions: ["knowledge_base.read", "document.read"]
resource_scopes:
- type: "knowledge_base"
attributes: ["tenant_id", "created_by"]
- type: "document"
attributes: ["knowledge_base_id", "tenant_id"]
6.2 网站嵌入Widget
通过嵌入Widget可以将智能体发布到外部网站:
<!-- 在网站中嵌入WeKnora Widget -->
<script src="http://your-weknora-domain.com/widget.js"></script>
<script>
WeKnoraWidget.init({
apiKey: "your_embed_api_key",
knowledgeBaseId: "kb_123456",
theme: "light",
position: "bottom-right",
welcomeMessage: "您好,我是智能助手,有什么可以帮您?",
language: "zh-CN",
features: {
fileUpload: true,
voiceInput: true,
history: true
}
});
</script>
安全配置:
# 安全模式配置
embed:
security_mode: "token_exchange"
allowed_domains:
- "https://example.com"
- "https://app.example.com"
rate_limit:
requests_per_minute: 60
burst_size: 10
token_exchange:
enabled: true
jwt_secret: "${JWT_SECRET}"
token_ttl: "1h"
6.3 可观测性与监控
集成Langfuse提供全链路可观测性:
监控指标:
- LLM调用延迟和Token使用
- 检索命中率和相关性评分
- Agent推理步骤和工具调用
- 用户会话分析和行为跟踪
配置示例:
tracing:
provider: "langfuse"
langfuse:
public_key: "${LANGFUSE_PUBLIC_KEY}"
secret_key: "${LANGFUSE_SECRET_KEY}"
host: "https://cloud.langfuse.com"
enabled: true
spans:
- name: "llm_call"
attributes: ["model", "provider", "token_count"]
- name: "retrieval"
attributes: ["strategy", "top_k", "hit_rate"]
- name: "agent_step"
attributes: ["tool_name", "iteration", "success"]
七、性能调优与问题排查
7.1 检索性能优化
向量数据库索引优化:
-- PostgreSQL pgvector HNSW索引优化
CREATE INDEX idx_knowledge_embedding
ON knowledge
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
-- Elasticsearch向量索引配置
PUT /knowledge/_mapping
{
"properties": {
"embedding": {
"type": "dense_vector",
"dims": 1536,
"index": true,
"similarity": "cosine"
}
}
}
缓存策略配置:
cache:
redis:
enabled: true
address: "redis:6379"
password: "${REDIS_PASSWORD}"
db: 0
strategies:
- name: "query_cache"
ttl: "5m"
max_size: 10000
enabled: true
- name: "embedding_cache"
ttl: "24h"
max_size: 50000
enabled: true
7.2 常见问题排查
1. 服务启动失败
# 查看服务日志
docker-compose logs -f app
# 检查数据库连接
docker-compose exec postgres psql -U postgres -d weknora -c "\dt"
# 验证向量数据库
curl http://localhost:9200/_cluster/health
2. 文档解析失败
- 检查文档格式支持:确认文件格式在支持列表中
- 查看解析器日志:
docker-compose logs -f docreader - 验证多模态配置:确保VLM和ASR服务正常
3. 检索结果不准确
- 调整分块参数:减小chunk_size或增加chunk_overlap
- 启用重排序:配置rerank模型提升相关性
- 优化检索策略:调整BM25/向量/图检索的权重比例
4. Agent推理超时
- 增加超时设置:
agent.timeout: "120s" - 限制迭代次数:
agent.max_iterations: 10 - 启用工具缓存:减少重复工具调用
7.3 监控与告警
Prometheus指标采集:
metrics:
enabled: true
port: 9090
path: "/metrics"
counters:
- name: "requests_total"
help: "Total number of HTTP requests"
labels: ["method", "path", "status"]
- name: "llm_calls_total"
help: "Total number of LLM API calls"
labels: ["model", "provider", "status"]
histograms:
- name: "request_duration_seconds"
help: "HTTP request duration in seconds"
buckets: [0.1, 0.5, 1, 2, 5, 10]
- name: "llm_latency_seconds"
help: "LLM API call latency in seconds"
buckets: [0.5, 1, 2, 5, 10, 30]
Grafana监控面板:
- QPS监控:请求量、响应时间、错误率
- LLM使用:Token消耗、API调用延迟、模型使用分布
- 检索性能:召回率、响应时间、缓存命中率
- 系统资源:CPU、内存、磁盘、网络使用情况
八、技术生态与社区资源
8.1 项目结构解析
WeKnora/
├── cmd/ # 应用入口点
│ ├── desktop/ # 桌面端应用
│ ├── server/ # 服务端入口
│ └── download/ # 资源下载工具
├── internal/ # 核心业务逻辑
│ ├── agent/ # Agent引擎
│ ├── application/ # 应用服务层
│ ├── config/ # 配置管理
│ ├── handler/ # HTTP处理器
│ ├── infrastructure/ # 基础设施层
│ ├── models/ # 数据模型
│ └── types/ # 类型定义
├── client/ # Go客户端SDK
├── frontend/ # Vue.js前端
├── docreader/ # 文档解析服务
├── mcp-server/ # MCP服务器实现
├── config/ # 配置文件
├── docs/ # 项目文档
├── scripts/ # 部署脚本
└── migrations/ # 数据库迁移
8.2 核心配置文件
主要配置文件路径:
- 主配置:
config/config.yaml- 系统全局配置 - 模型配置:
config/builtin_models.yaml.example- 内置模型配置示例 - Agent配置:
config/builtin_agents.yaml- 内置Agent配置 - 提示模板:
config/prompt_templates/- 各种提示词模板
开发配置文件示例:
# config/config.yaml
app:
name: "weknora"
version: "0.6.3"
environment: "development"
server:
host: "0.0.0.0"
port: 8080
read_timeout: "30s"
write_timeout: "30s"
database:
driver: "postgres"
dsn: "host=localhost user=postgres password=password dbname=weknora port=5432 sslmode=disable"
vector_store:
provider: "pgvector"
connection_string: "host=localhost user=postgres password=password dbname=weknora port=5432 sslmode=disable"
llm:
default_provider: "openai"
providers:
openai:
api_key: "${OPENAI_API_KEY}"
base_url: "https://api.openai.com/v1"
models:
- name: "gpt-4"
max_tokens: 8192
- name: "gpt-3.5-turbo"
max_tokens: 4096
8.3 学习资源与社区
官方文档:
- 快速开始:
README_CN.md- 中文快速入门指南 - 架构设计:
docs/WeKnora.md- 系统架构详细说明 - API参考:
docs/api/- 完整的API文档 - 开发指南:
docs/开发指南.md- 二次开发指南
实战示例:
- 客户端示例:
client/example.go- Go客户端使用示例 - 技能开发:
skills/preloaded/- 预置技能示例 - 数据集:
dataset/samples/- 测试数据集
社区贡献:
- 问题反馈:通过GitHub Issues提交
- 代码贡献:遵循项目代码规范
- 文档改进:补充使用案例和技术文档
8.4 最佳实践总结
部署建议:
- 生产环境使用Docker Compose或Kubernetes部署
- 配置持久化存储确保数据安全
- 启用监控和告警机制
- 定期备份数据库和向量索引
性能优化:
- 根据文档类型调整分块策略
- 启用缓存减少重复计算
- 合理配置向量数据库索引
- 使用CDN加速静态资源
安全建议:
- 启用API Key认证和RBAC权限控制
- 配置TLS加密通信
- 定期轮换密钥和证书
- 启用审计日志记录操作历史
结语
WeKnora作为企业级RAG框架,通过模块化设计和丰富的功能集,为企业知识管理提供了完整的解决方案。从文档解析、向量检索到智能问答,再到知识图谱构建和Wiki生成,WeKnora覆盖了知识管理的全生命周期。其开源的特性、灵活的架构和活跃的社区,使其成为构建智能知识系统的理想选择。
无论是初创团队快速搭建知识问答系统,还是大型企业构建复杂的知识管理平台,WeKnora都能提供可靠的技术支撑。随着项目的持续发展,更多功能和优化将持续加入,为开发者提供更强大的工具和更好的体验。
技术要点总结:
- 混合检索策略(BM25+向量+图)提供高精度召回
- ReACT Agent框架支持复杂推理任务
- 多租户RBAC满足企业级权限需求
- 全链路可观测性保障系统稳定性
- 丰富的集成生态降低部署成本
通过本文的深度解析,希望能够帮助开发者更好地理解WeKnora的技术架构和使用方法,在实际项目中充分发挥其价值。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考









