NeuralFlow 是一个面向作品集与真实原型场景的 企业 AI 知识库 Agent 平台。
它把以下能力整合到一套可运行系统里:
- FastAPI 后端
- Agent Runtime
- Function Calling
- MCP Tool 集成
- Redis Working Memory
- ChromaDB Vector Retrieval
- Document RAG Pipeline
- Hybrid Retrieval(keyword + vector)
- Advanced RAG Pipeline(query transformation → corrective loop)
- Multimodal RAG(image / table extraction with vision LLM)
- RAG Evaluation(LLM-as-judge answer quality scoring)
- Pipeline Observability(tracing with DB persistence + API)
- Streaming Chat / SSE Runtime Events
- Next.js Runtime Console
- Multi-tenant Isolation
- Celery 异步摄入任务
这不是一个只会聊天的 demo,而是一套围绕 文档知识库 + Agent + 检索增强生成 的工程化骨架。
当前版本的 NeuralFlow 目标是:
将通用 Agent Runtime 升级为可扩展的企业知识库 AI Agent 平台。
它支持把 PDF、Markdown、TXT、DOCX 文档上传进系统,自动完成:
- 文件存储
- 文档解析(含图片/表格多模态提取)
- Chunk 切分
- Embedding 生成
- ChromaDB 建索引
- Query Retrieval(Hybrid keyword + vector search)
- RAG Context Assembly(含 Advanced RAG 纠错循环)
- 注入聊天 / Agent Prompt
- 在前端展示引用来源与检索 chunks
- LLM-as-judge 回答质量评估与 Pipeline 追踪
/chat同步对话/chat/streamSSE 流式响应/chat/reactReAct / Function Calling agent/chat/orchestrate多 Agent 编排
- 支持上传:
PDF / Markdown / TXT / DOCX - 文档状态管理:
uploaded / queued / parsing / chunking / embedding / indexing / ready / failed - 多租户隔离
- 文档详情 / chunk 浏览
- 文档解析(PDF / Markdown / TXT / DOCX)
- token-aware recursive chunk splitting
- configurable overlap
- OpenAI-compatible embedding provider
- embedding cache(in-memory + Redis)
- ChromaDB retrieval
- Hybrid retrieval(keyword + vector)
- Advanced RAG pipeline(query transformation → grading → corrective loop → context building)
- Multimodal RAG(image description extraction from PDF/DOCX, table extraction → markdown)
- token-budget-aware context builder
- citations / source support
- LLM-as-judge answer evaluation(relevance / faithfulness / completeness scoring)
- Pipeline tracing with DB persistence
- Prometheus eval metrics(Gauges / Histograms for answer scores)
- Eval API endpoints(受控 dataset_id、Celery 异步运行、租户隔离、状态查询)
- Trace API endpoints(filterable trace spans, full trace tree)
- documents 页面
- chunk 可视化
- runtime panel 检索展示
- 聊天消息下方 source citations 展示
- 上传后自动刷新文档列表
- 文档处理中自动轮询状态
- 文档详情 / 列表页可直接发起单文档总结与 scoped chat
- SQLAlchemy metadata storage
- Celery ingestion queue
- structured logging
- tenant middleware
- Prometheus metrics
- runtime config hot patch
- pytest regression coverage(696 tests)
- Performance benchmarks(ingestion latency / retrieval latency / token usage)
- GitHub Actions CI/CD(auto-merge for Dependabot, eval gate, multi-stage workflows)
完整变更记录见:
发布前建议先做一轮本地验证:
bash scripts/verify-local.sh注意:这个脚本使用 bash 特性(例如 set -euo pipefail),不要用 sh scripts/verify-local.sh,否则会直接报错。
默认会:
- 使用
uv同步后端依赖 - 运行
pytest - 执行前端
npm ci/lint/typecheck/build - 在国内网络环境默认优先使用清华 PyPI 镜像并提高超时时间
本地验证未通过前,不应推送发布链路相关改动。
- FastAPI
- SQLAlchemy
- Redis
- ChromaDB
- Celery
- LiteLLM / OpenAI-compatible API
- httpx(async HTTP client)
- PyMuPDF(PDF text / image / table extraction)
- python-docx
- markdown-it-py
- tiktoken
- Next.js 15
- TypeScript
- Zustand
- React Query
完整 RAG 架构说明见:
高层数据流:
Upload File (PDF / DOCX / MD / TXT)
-> Document Record (DB)
-> Async Ingestion Task (Celery)
-> Parse (text + images + tables for multimodal)
-> Chunk (token-aware, configurable overlap)
-> Embed (OpenAI-compatible API, in-memory + Redis cache)
-> Chroma Index (vectors + metadata)
User Query
-> [Optional] Query Transformation (rewrite / expand)
-> Hybrid Retrieval (keyword BM25 + vector search)
-> Relevance Grading (LLM-as-judge filter)
-> [Optional] Corrective Loop (rewrite query → re-retrieve)
-> Context Builder (token-budget-aware assembly)
-> Agent / Chat Prompt
-> LLM Response
-> Answer Evaluation (LLM-as-judge score)
-> Pipeline Trace (persisted to DB for observability)
-> Citations / Sources (frontend display)
如果你要把这个项目作为求职作品集,最值得展示的是这条完整链路:
- 启动 FastAPI / Celery Worker / Next.js Frontend
- 在
Documents页面上传一份 PDF / Markdown / TXT / DOCX(含图片和表格的 PDF 可以同时展示多模态提取) - 观察文档状态从
queued -> parsing -> chunking -> embedding -> indexing -> ready - 在文档列表页或详情页点击:
Summarize this documentChat with this document
- 系统会创建一个绑定当前 document_id 的新会话
- 在首页 Runtime Console 中继续追问,检索会被限制在该文档范围内
- 在右侧 runtime panel 查看:
- retrieval 事件
- matched chunks
- source citations
这条流程能够完整展示:
- 异步文档摄入 pipeline(含多模态图片/表格提取)
- Hybrid 检索(keyword + vector)
- Advanced RAG 纠错循环
- 单文档 scoped retrieval
- Agent / Chat runtime observability
- 前后端联动的产品闭环
NeuralFlow/
├── app/
│ ├── agents/
│ ├── api/
│ │ ├── documents.py
│ │ ├── eval.py
│ │ ├── retrieval.py
│ │ ├── streaming.py
│ │ └── traces.py
│ ├── core/
│ ├── db/
│ ├── documents/
│ ├── embeddings/
│ ├── evals/
│ ├── ingestion/
│ │ └── multimodal/ # image/table extraction
│ ├── memory/
│ ├── observability/
│ │ ├── trace_manager.py
│ │ ├── trace_persister.py
│ │ └── eval_metrics.py
│ ├── rag/
│ ├── retrieval/
│ └── main.py
├── frontend/
│ ├── app/
│ │ ├── chat/
│ │ └── documents/
│ ├── components/
│ │ ├── documents/
│ │ ├── rag/
│ │ └── ui/
│ ├── features/
│ ├── services/
│ └── types/
├── docs/
│ └── rag-architecture.md
├── tests/
└── worker.py
POST /api/documents/uploadmultipart/form-data:
filetitle(optional)
GET /api/documentsGET /api/documents/{document_id}GET /api/documents/{document_id}/chunksDELETE /api/documents/{document_id}POST /api/documents/{document_id}/reindexPOST /api/retrieval/search请求示例:
{
"query": "员工请假制度是什么?",
"top_k": 5,
"score_threshold": 0.2,
"filters": {}
}POST /chat示例请求:
{
"session_id": "demo-1",
"message": "员工请假制度是什么?",
"use_retrieval": true
}示例响应(节选):
{
"session_id": "demo-1",
"intent": "general",
"reply": "...",
"citations": [
{
"index": 1,
"label": "Employee Handbook",
"document_id": "doc_xxx",
"chunk_id": "chk_xxx",
"page_number": 3
}
]
}POST /chat/streamSSE events 包含:
retrievalchunkthinkingmessagedoneerror
cd ~/github/NeuralFlow
cp .env.example .env
uv syncML 相关依赖(ChromaDB vector store、cross-encoder reranker)默认不安装。 如果需要完整功能,运行
uv sync --extra ml。
uv run uvicorn app.main:app --reloadmacOS / 本地演示环境建议使用
--pool=solo,避免 prefork 在文档摄入时出现子进程崩溃。
cd ~/github/NeuralFlow
. .venv/bin/activate
python -m celery -A worker.celery_app worker --loglevel=info --pool=solo或用 uv run:
cd ~/github/NeuralFlow
uv run python -m celery -A worker.celery_app worker --loglevel=info --pool=solocd frontend
npm install
npm run devdocker compose up --build仓库已提供:
.env.production.exampledocker-compose.prod.ymldeploy/Caddyfile
推荐流程:
cp .env.production.example .env.production
# 填好域名、数据库、LLM、Embedding 配置
docker compose -f docker-compose.prod.yml up -d --build核心变量:
REDIS_HOSTREDIS_PORTREDIS_DBCHROMA_HOSTCHROMA_PORTDATABASE_URLDOCUMENTS_STORAGE_DIRLLM_API_BASELLM_API_KEYOPENAI_API_KEYLITELLM_MODELMCP_BASE_URL
RAG 相关:
EMBEDDING_MODEL(代码默认text-embedding-3-small)EMBEDDING_API_BASE(建议与 chat LLM 分开配置)EMBEDDING_API_KEYrag_default_top_krag_score_threshold
多模态 RAG(可选):
MULTIMODAL_ENABLED(默认false)VISION_MODEL(默认gpt-4o)MULTIMODAL_MAX_IMAGES(默认 20)MULTIMODAL_MAX_TABLES(默认 50)
生产环境建议:
- 将
LLM_API_BASE/LLM_API_KEY与EMBEDDING_API_BASE/EMBEDDING_API_KEY分开配置,避免某些代理只支持 chat 不支持 embeddings。 - 将
OFFLINE_FALLBACK_ENABLED=false,避免线上静默降级。 CORS_ALLOW_ORIGINS设置为明确域名,不要保留*。- 优先使用 PostgreSQL,而不是默认 SQLite。
- Linux 服务器如果稳定可尝试
CELERY_WORKER_POOL=prefork;首版上线建议先用solo。
系统通过 TenantIsolationMiddleware 基于 Header 传入租户上下文:
X-Tenant-IDX-Tenant-ScopeX-Tenant-RolesX-Tenant-Subject
文档 metadata、chunk metadata、retrieval filter 全链路带 tenant_id。
这版项目的亮点不在”接了一个向量库”,而在于它展示了从文档摄入到高级 RAG 再到评估观测的完整工程链路:
- 文档上传与多格式解析
- 多模态提取(图片描述 + 表格→markdown)
- 异步 ingestion pipeline(Celery)
- 向量检索 + Hybrid retrieval(keyword BM25)
- Advanced RAG(query transformation → grading → corrective loop)
- RAG context assembly(token-budget-aware)
- Agent / Chat integration
- LLM-as-judge 回答质量评估
- Pipeline tracing with DB persistence
- 引用来源展示
- 多租户隔离
- streaming observability
- 689 regression tests
- Performance benchmarks
- 自动化 CI/CD(path filtering、auto-merge、eval gate)
如果你要把它写进简历或作品集,最适合强调的关键词是:
- Enterprise RAG
- AI Knowledge Base Platform
- Agent Runtime
- Function Calling / MCP
- Advanced RAG Pipeline(query transformation + corrective loop)
- Hybrid Retrieval(keyword + vector)
- Multimodal RAG(vision LLM image extraction)
- RAG Evaluation(LLM-as-judge)
- Pipeline Observability(tracing + metrics)
- Multi-tenant Retrieval
- Async Ingestion Pipeline
- Source-aware Citation UX
如果你要快速演示这套系统,建议按下面顺序:
在三个独立的终端中分别运行:
终端 1 - 后端 API:
cd ~/github/NeuralFlow
uv run uvicorn app.main:app --reload终端 2 - Celery Worker(文档处理必需):
cd ~/github/NeuralFlow
. .venv/bin/activate
python -m celery -A worker.celery_app worker --loglevel=info终端 3 - 前端:
cd ~/github/NeuralFlow/frontend
npm run dev浏览器访问:
http://localhost:3000/documents
上传一个示例文件,例如:
- 员工手册 PDF
- 团队规范 Markdown
- 产品需求 TXT
- 培训材料 DOCX
上传前注意: 一定要确保 Celery Worker 在后台运行(终端 2),否则文件会卡在 queued 状态。
观察点:
- 文档是否出现在列表里
- 状态是否从
queued→parsing→chunking→embedding→indexing→ready进行 - chunk 数量是否可见
点击文档进入详情页,确认:
- 文档 metadata 正常
- chunk 已生成
- page / token / section 信息可见
重要: 只有当文档状态为 ready 时,Chat 才能检索到文档内容。上传后,文件会经过以下处理阶段:
uploaded- 文件已上传queued- 等待 Celery worker 处理parsing- 解析文件内容中chunking- 分割成 chunks 中embedding- 生成向量嵌入中indexing- 建立 ChromaDB 索引中ready✓ - 现在可以检索了
当状态变为 ready 后,你现在有两种推荐方式:
- 点击
Summarize this document - 点击
Chat with this document
- 查看 chunk
- 点击
Summarize this document - 点击
Chat with this document
这两个入口都会:
- 创建一个新的 chat session
- 把当前
document_id绑定到该 session - 回到首页 Runtime Console
- 后续检索只在这份文档范围内进行
在自动创建的新会话里,你可以继续追问:
员工请假制度是什么?这份规范里对代码评审有什么要求?把这份文档总结成 5 条重点根据知识库,总结一下 onboarding 流程。
如果当前 session 是从文档页发起的,那么这些问题会自动限定在该文档范围内,而不是在整个知识库里做无约束检索。
观察点:
- Runtime Panel 中是否出现 retrieved chunks
- 是否出现 source / score / page 信息
- assistant 回答下方是否展示 citations
使用 /chat/stream 路径时,可以重点展示:
- retrieval 事件
- chunk 事件
- streaming tokens
- 最终 answer + sources
这一步很适合在面试或作品集录屏中展示,因为它能直观看出系统不是“黑盒聊天框”,而是可观测的 RAG Agent Runtime。
运行新增的 RAG 关键测试:
RAG Pipeline 关键测试:
uv run pytest -q \
tests/test_rag_chat.py \
tests/test_rag_context_builder.py \
tests/test_advanced_pipeline.py \
tests/test_hybrid_retrieval.py \
tests/test_documents_api.py \
tests/test_ingestion_pipeline.py \
tests/test_retrieval_api.py评估与可观测性测试:
uv run pytest -q \
tests/test_answer_evaluator.py \
tests/test_eval_api.py \
tests/test_eval_regression.py \
tests/test_trace_manager.py \
tests/test_trace_persister.py多模态 RAG 测试:
uv run pytest -q \
tests/test_multimodal_extractor.py \
tests/test_multimodal_config.py \
tests/test_multimodal_processor.py运行全量测试:
uv run pytest tests/ -v- 文档上传系统
- 文件元数据存储
- 多用户 / 多租户隔离
- PDF / Markdown / TXT / DOCX 解析
- token-aware chunk pipeline
- embedding provider abstraction(in-memory + Redis cache)
- ChromaDB retrieval
- RAG context builder
- Agent / Chat RAG injection
- 前端 documents 页面
- source citations 展示
- retrieval chunk 可视化
- 异步 ingestion 任务
- 测试覆盖主链路(689 tests)
- Hybrid retrieval(keyword + vector search)
- Advanced RAG pipeline(query transformation + correctness grading + corrective loop)
- Performance benchmarks(ingestion / retrieval / token usage, HTML reports)
- LLM-as-judge answer evaluation(relevance / faithfulness / completeness)
- Pipeline tracing with DB persistence + API
- Prometheus eval metrics gauges
- Multimodal RAG(image description from PDF/DOCX, table→markdown extraction)
- CI/CD 自动合入(auto-merge for Dependabot, eval gate)
- Security headers(CSP)
- Redis-backed embedding cache with connection pooling
- Rich metadata filters(tags / owner / document groups, multi-value $in support)
- Markdown heading hierarchy parsing & chunking
- OCR pipeline(pytesseract + pdf2image for scanned documents)
- Cross-encoder reranker(lazy-loaded transformer model)
- Signed file preview URLs(HMAC time-limited tokens)
- Postgres production migration guide(MIGRATION.md + .env.production.example)
- Deployment manifests(K8s + Helm charts)
- role-based knowledge base ACL — 文档/知识库按角色粒度的访问控制,需要补全 auth 系统后再做
- auth / SSO integration — 用户认证与单点登录,已完成 JWT 基础框架,对接 OAuth/OIDC 待实现
evaluation dashboard— 已完成:recharts 图表(趋势/分布/雷达)+ 触发评估 + 逐 Case 下钻advanced reranker model— 已完成:CrossEncoderReranker 已接入真实检索流程,支持RERANKER_MODEL切换更强模型,RERANKER_HEURISTIC_WEIGHTS_JSON可调启发式兜底权重hybrid search index tuning— 已完成:BM25_K1/BM25_B环境变量可配置,传递给 VectorRetriever 内存混合检索的 BM25 评分streaming eval monitoring— 已完成:chat SSE stream 中注入 eval 事件,前端 runtime 面板展示评分徽章
当前仓库更适合作为:
- AI 应用架构作品集
- 企业知识库 Agent 原型
- RAG 平台工程模板
如果你要进一步产品化,建议下一步优先补:
- Postgres migration
- object storage abstraction
- auth / ACL
- observability dashboard
- deployment manifests