RAG智能代理

一个基于Streamlit的智能代理,通过RAG(检索增强生成)技术提供对存储在PostgreSQL与PGVector中的知识库的对话式访问,支持多种文档格式并生成上下文相关的回答。

  • by stefanopiga
  • HTML
  • 本地部署
  • 更新于
在 GitHub 查看 stefanopiga/Agent-RAG

使用说明

记录RAG代理

🚀 状态和质量

📦 项目信息

⭐ 社区

基于 Streamlit 的智能代理,可通过 PGVector 对存储在 PostgreSQL 中的知识库进行对话访问。使用 RAG(检索增强生成)搜索嵌入式文档,并通过引用来源提供上下文和准确的答案。支持多种文档格式。

🎓 新来Docling?

从教程开始! 咨询海报 docling_basics/ 对于教授Docling基础知识的渐进式示例:

  1. 简单的PDF转换 基本文件处理
  2. 支持多种格式 -格式PDF、Word、PowerPoint
  3. 伊布里多 - RAG系统的智能切割

这些教程为了解这个完整的RAG代理是如何工作的基础。 转到 Docking Basics

功能

  • 💬 与Streamlit交互式Web聊天界面
  • 🔍 通过嵌入式矢量文档进行语义搜索
  • 📚 使用 RAG 管道进行上下文感知响应
  • 🎯 引用提供的所有信息的来源
  • 🔄 在令牌到达时实时串流文本输出
  • 💾 PostgreSQL/PGVector 用于可扩展的知识存储
  • 🧠 在班次之间保持对话历史

先决条件

工具 版本 安装链接
python 3.10+ (推荐3.11) python.org/下载
紫外线 0.9.13+ (推荐最新版本) docs.astral.sh/uv
PostgreSQL 16+带PGVector postgresql.org
码头工人 最新(可选) docker.com

API密钥要求:

提供商数据库支持:

  • PostgreSQL自托管架构PGVector
  • Supabase(管理PostgreSQL)
  • Neon(无服务器PostgreSQL)

快速开始

估计时间:~3-4分钟 (不包括安装先决条件)

1. 克隆并安装依赖关系(~30秒)

# Clona il repository
git clone https://github.com/stefanopiga/Agent-RAG.git
cd Agent-RAG

# Installa le dipendenze usando UV
uv sync

2. 设置环境变量(~30秒)

cp .env.example .env

修改 .env 您的凭据:

# RICHIESTO: Connessione database PostgreSQL con PGVector
DATABASE_URL=postgresql://user:password@localhost:5432/dbname

# RICHIESTO: OpenAI API key
OPENAI_API_KEY=sk-...

# OPZIONALE: Modello LLM (default: gpt-4o-mini)
LLM_CHOICE=gpt-4o-mini

# OPZIONALE: Modello embedding (default: text-embedding-3-small)
EMBEDDING_MODEL=text-embedding-3-small

# OPZIONALE: LangFuse per observability/tracing (MCP server)
LANGFUSE_PUBLIC_KEY=pk-lf-...
LANGFUSE_SECRET_KEY=sk-lf-...
LANGFUSE_BASE_URL=https://cloud.langfuse.com

每个提供程序的 DATABASE_URL 示例:

  • 自托管: postgresql://user:password@localhost:5432/dbname
  • Supabase: postgresql://postgres.[project-ref]:[password]@aws-0-[region].pooler.supabase.com:5432/postgres
  • 霓虹: postgresql://[user]:[password]@[endpoint].neon.tech/[dbname]

3. 设置数据库(~1分钟)

新安装:

# Esegui lo schema completo (include HNSW index ottimizzato)
# Per Supabase: Usa SQL Editor e incolla contenuto di optimize_index.sql
psql $DATABASE_URL < sql/optimize_index.sql

关于Supabase/Neon: 使用内置的SQL编辑器并粘贴内容 sql/optimize_index.sql.

升级现有数据库:

uv run python scripts/verification/optimize_database.py --apply

Il文件SQL(sql/optimize_index.sql创建:

  • ✅ 所需的扩展(vector, uuid-ossp, pg_trgm)
  • ✅ Tabella documents 存储带元数据的原始文档
  • ✅ Tabella chunks 每个文本片段有1536个尺寸的嵌入
  • ✅ 函数 match_chunks() 向量相似性搜索
  • ✅ 优化的HNSW指数 (比旧版IVFFlat快10-100倍)
  • ✅ 每次筛选e源查询的性能指标

Epic 3-会话跟踪(Opzionale):

要在 Streamlit UI 中启用会话跟踪和成本可视性:

# Esegui schema Epic 3 (crea tabelle sessions e query_logs)
# Per Supabase: Usa SQL Editor e incolla contenuto di sql/epic-3-sessions-schema.sql
psql $DATABASE_URL < sql/epic-3-sessions-schema.sql

这将创建:

  • ✅ Tabella sessions 每会话跟踪统计(查询计数、总成本、平均延迟)
  • ✅ Tabella query_logs 用于记录查询的成本和时间
  • ✅ RLS政策 service_role 全面保护(Full Protection)
  • ✅ 每个性能的索引(会话id、时间戳查找)

HNSW的优势:

  • 🚀 向量搜索速度提高50-80%
  • 📈 随着数据集的增长一致性能
  • 🎯 最适合 <1M 个矢量(典型 RAG 使用场所)

4. 插入文档(~1-2分钟的初始设置)

将您的文档添加到文件夹 documents/. 通过Docling支持多种格式:

支持的格式:

  • 📄 PDF (.pdf)
  • 📝 字 (.docx, .doc)
  • 📊 幻灯片 (.pptx, .ppt)
  • 📈 Excel (.xlsx, .xls)
  • 🌐 超文本标记语言 (.html, .htm)
  • 📋 标记语言 (.md, .markdown)
  • 📃 文本 (.txt)
# Ingerisci tutti i documenti supportati nella cartella documents/
# NOTA: Di default, questo CANCELLA i dati esistenti prima dell'ingestione
uv run python -m ingestion.ingest --documents documents/

# Regola la dimensione dei chunk (default: 1000)
uv run python -m ingestion.ingest --documents documents/ --chunk-size 800

⚠️ 重要提示: 摄入过程 自动删除所有现有文档和块 在添加新文档之前从数据库中删除。这确保了清洁状态并防止重复。

摄入管道:

  1. 自动检测文件类型 并使用 Docling 处理 PDF、Office 文档和 HTML
  2. 转换为Markdown 一致的处理
  3. 分块语义 可配置尺寸
  4. 通用嵌入 使用 OpenAI
  5. PostgreSQL中的Memorizza 使用PGVector搜索相似性

💡 最佳实践 - 组织文件:

将文档组织成子文件夹以利用源过滤:

documents/
├── docling/
│   ├── docs/
│   │   ├── getting-started.md
│   │   └── architecture.md
│   └── README.md
├── langfuse-docs/
│   ├── deployment/
│   │   ├── cloud.md
│   │   └── docker.md
│   ├── api/
│   │   └── tracing.md
│   └── guides/
└── company-docs/
    ├── policies.pdf
    └── procedures.docx

优势:

  • ✅ 具有完整路径的精确报价
  • ✅ 按特定文档过滤(“仅在 Docling 文档中搜索”)
  • ✅ 易于维护和更新
  • ✅ 不同知识来源之间的逻辑分离

5. 运行应用程序(~10秒)

# esegui api così accendi la parte sotto il cofano
uv run uvicorn api.main:app --host 0.0.0.0 --port 8000

# esegui streamlit cosi puoi interagire con l'UI
uv run streamlit run app.py

应用程序将在浏览器中自动打开: http://localhost:8501

功能:

  • 💬 界面聊天 有消息历史
  • 📊 删除聊天按钮 重置对话
  • 🎨 UI现代版 使用Streamlit构建
  • 🔍 实时流媒体 答案
  • 📚 知识库状态 在 sidebar

互动示例:

Tu: Quali argomenti sono trattati nella knowledge base?
Assistant: Sulla base della knowledge base, gli argomenti principali includono...

[Fonte: company-overview.md]
Contenuto dal documento...

建筑

┌─────────────┐     ┌──────────────┐     ┌─────────────┐
│  Streamlit  │────▶│  RAG Agent   │────▶│ PostgreSQL  │
│     UI      │     │ (PydanticAI) │     │  PGVector   │
└─────────────┘     └──────────────┘     └─────────────┘
                           │
                    ┌──────┴──────┐
                    │             │
              ┌─────▼────┐  ┌────▼─────┐
              │  OpenAI  │  │  OpenAI  │
              │   LLM    │  │Embeddings│
              └──────────┘  └──────────┘

关键组件

RAG代理

主要代理人(rag_agent.py)车:

  • 通过连接池管理数据库连接
  • 为 RAG 操作提供 search_knowledge_base 工具
  • 通过 app.py 与 Streamlit 界面集成
  • 按上下文跟踪对话历史记录

工具搜索_知识库

工具功能注册与代理:

  • 通用查询嵌入usando OpenAI
  • 使用 PGVector 共音相似性进行搜索
  • 返回最相关的 top-k 块
  • 使用源引用格式化结果
  • 支持按来源过滤 针对特定文档进行有针对性的搜索

先进过滤能力: 当用户请求时,代理可以按特定来源自动过滤搜索。

有过滤的查询示例:

  • “如何仅使用 Docling 文档部署 Docling?”
  • “根据Langfuse文档解释追踪,而不是查看其他来源”
  • “在廊坊部署”→ 自动过滤器 langfuse-docs

工具定义示例:

async def search_knowledge_base(
    ctx: RunContext[None],
    query: str,
    limit: int = 5,
    source_filter: str | None = None  # Filtro opzionale per fonte
) -> str:
    """Cerca nella knowledge base usando similarità semantica.

    Args:
        query: Query di ricerca
        limit: Numero massimo risultati
        source_filter: Filtro opzionale (es: "docling", "langfuse-docs")
    """
    # Genera embedding per la query
    # Cerca in PostgreSQL con PGVector
    # Applica filtro fonte se specificato
    # Formatta e restituisce i risultati

架构数据库

  • documents存储带元数据的原始文档

    • id, title, source, content, metadata, created_at, updated_at
  • chunks存储带有矢量嵌入的文本片段

    • id, document_id, content, embedding (向量(1536)), chunk_index, metadata, token_count
  • match_chunks()PostgreSQL 函数用于向量相似性搜索

    • 使用共弦相似性(1 - (embedding <=> query_embedding))
    • 返回相似度分数高于门槛的片段

🚀 每个游标IDE的MCP服务器

该项目包括一个 模型上下文协议(MCP)服务器 与 Cursor IDE 集成。

设置MCP:

  1. 运行命令启动mcp服务器:

# avvia il server mcp
uv run python mcp_server.py

# apri la porta locale http://localhost:8080/health
curl http://localhost:8080/health

  1. 配置 .cursor/mcp.json:
{
  "mcpServers": {
    "docling-rag": {
      "command": "uv",
      "args": [
        "run",
        "--project",
        "/path/to/docling-rag-agent",
        "python",
        "/path/to/docling-rag-agent/mcp_server.py"
      ]
    }
  }
}
  1. 重新启动游标 MCP服务器自动启动

  2. 使用工具 在光标中:

Chiedi: "What is Docling?"
Il MCP tool cercherà nella knowledge base e risponderà con context

性能MCP:

  • ✅ 全局嵌入器实例:-70%延迟(消除300-500ms的开销)
  • ✅ HNSW指数:-61%查询时间(平均1395ms,缓存237ms)
  • ✅ 优化的连接池: -20%的开销
  • ✅ 每次监测的定时仪器

完整文档:

  • docs/performance-optimization-guide.md - 详细技术指南
  • docs/optimization-summary.md - 结果分析
  • docs/optimization-deployment.md -部署指南

🤖 代码质量和CI/CD

CodeRabbit集成

repository 使用 CodeRabbit 对每个提取请求进行AI驱动的自动代码审查。

功能:

  • ✅ 自动审查每个PR
  • 📝 最佳实践建议
  • 🔒 安全分析自动化
  • 📊 高级别修改摘要

CI/CD管道

GitHub Actions 在每个 PR 上自动运行,并推送到 main/develop:

Job Descrizione Tool
棉绒 棉绒格式检查 Ruff
类型检查 类型检查统计 Mypy
测试 单元/集成测试覆盖率>70% Pytest
构建 Docker镜像构建验证(<500MB) Docker Buildx
秘密扫描 秘密扫描预防 TruffleLog OSS

📚 开发者资源

文档

  • 建筑:完整的系统架构、设计决策和组件描述
  • 编码标准:代码风格指南、命名约定、文档标准和最佳实践
  • **测试策略**TDD工作流程、测试组织、RAGAS评估和CI/CD集成
  • 开发指南:设置说明、开发工作流程和故障排除
  • 文档索引:带有快速链接和导航的完整文档索引

快速链接

  • 代码风格:参见 编码标准 Python风格指南、类型提示、错误处理模式
  • 写作测试:参见 测试策略 TDD方法、测试组织、覆盖要求
  • 项目结构:参见 统一的项目结构 用于目录组织、文件放置规则、史诗映射
  • 架构模式:参见 建筑 用于设计决策、集成模式、可观察性

📊 LangFuse可观测性

MCP 服务器集成 浪焰 用于追踪和观察AI呼叫。

设置LangFuse

  1. 创建LangFuse帐户:

  2. 设置环境变量:

# LangFuse Configuration (opzionale)
LANGFUSE_PUBLIC_KEY=pk-lf-...
LANGFUSE_SECRET_KEY=sk-lf-...
LANGFUSE_BASE_URL=https://cloud.langfuse.com  # Default, oppure URL self-hosted
  1. 重新启动il服务器MCP - 轨道将自动出现在LangFuse中

追踪功能

  • 🔍 自动跟踪 所有 MCP 工具调用
  • 📊 详细元数据:tool_name、查询、限制、源
  • ⏱️ 时间与绩效 对于每个操作
  • 🔄 优雅降级即使没有 LangFuse,系统也能工作

成本跟踪(故事2.2)

系统会自动跟踪OpenAI API的使用成本:

  • 💰 嵌入成本跟踪每代成本: 通过嵌入 langfuse.openai 包装器
  • 📈 代币自动计数:每个嵌入的输入令牌,每个LLM的输入/输出令牌
  • 💵 价格更新LangFuse SDK 自动更新 OpenAI 价格
  • 📊 成本细分显示嵌入和LLM生成的单独成本

模型和价格跟踪:

型号 类型 成本
text-embedding-3-small 嵌入 $0.00002/1K代币
gpt-4o-mini LLM(输入) 0.00015/1K美元代币
gpt-4o-mini LLM(输出) 0.0006/1K代币

它是如何工作的:

  1. Il包装纸 langfuse.openai 取代直接的 OpenAI 客户端
  2. 每个 API 调用都会自动跟踪 token count
  3. 使用当前OpenAI价格计算成本
  4. 每个跟踪的成本细目可在 LangFuse 仪表板中查看

注: 成本跟踪是自动的,不需要额外的代码。如果没有配置 LangFuse,系统将正常运行而无需追踪(优雅降解)。

绩效指标(故事2.3)

该系统通过专用 HTTP 服务器显示 Prometheus 指标来监控性能。

可用的端点:

Endpoint 格式 描述
/metrics Prometheus 采用OpenMetrics格式的Metriche(文本/纯文本)
/health JSON 健康检查状态服务(正常/降级/关闭)

普罗米修斯:

公制 类型 描述
mcp_requests_total MCP 请求总数 (标签: 工具, 状态)
mcp_request_duration_seconds 柱状图 Latenza richieste(桶SLO对齐)
rag_embedding_time_seconds 直方图 时间生成嵌入
rag_db_search_time_seconds 直方图 时间搜索数据库
rag_llm_generation_time_seconds 直方图 时间生成LLM
mcp_active_requests Gauge 活跃的竞争对手请求

Prometheus 配置prometheus.yml):

scrape_configs:
  - job_name: "docling-rag-agent"
    scrape_interval: 15s # Default raccomandato (60s per cost-sensitive)
    static_configs:
      - targets: ["localhost:8080"]

计量服务器启动 :

# Avvia il server HTTP per metriche e health check (porta 8080)
uv run python -m docling_mcp.http_server

# Oppure con porta personalizzata
METRICS_PORT=9090 uv run python -m docling_mcp.http_server

健康检查响应:

{
  "status": "ok",
  "timestamp": 1732700400.123,
  "services": {
    "database": {
      "status": "up",
      "message": "PostgreSQL connection successful",
      "latency_ms": 5.2
    },
    "langfuse": {
      "status": "up",
      "message": "LangFuse client initialized",
      "latency_ms": 0.1
    },
    "embedder": {
      "status": "up",
      "message": "Embedder initialized and ready",
      "latency_ms": 0.5
    }
  }
}

状态逻辑:

  • ok所有运营服务
  • degradedLangFuse不可用(优雅降解,MCP可用)
  • down数据库或嵌入不可用(关键服务)

查看轨道

在LangFuse仪表板中,您将看到每个工具调用的跟踪:

工具 元数据跟踪
query_knowledge_base 查询、限制、源过滤器、源=“mcp”
ask_knowledge_base 问题、限制、来源=“mcp”
list_knowledge_base_documents 限制、偏移、源=“mcp”
get_knowledge_base_document document_id,来源=“mcp”
get_knowledge_base_overview 来源=“mcp”

注: 如果没有配置 LangFuse 变量,则服务器正常运行而无需追踪(优雅降级)。

LangFuse仪表板(故事2.4)

LangFuse 仪表板可实时查看 MCP 服务器的性能和成本。

Metriche仪表板:

| 描述 | 来源 | | ------------- | ------------------------------ | ---------------------- | | Total Queries | 请求总数 | 跟踪计数 | |平均延迟|延迟媒体|坎波 latency 痕迹| | 总成本 | 总成本(嵌入 + LLM) | 自动代币使用 |

可用的视图:

  • 成本趋势成本图表(每日/每周/每月)
  • 延迟分布工具的延迟分布
  • 跟踪详细信息视图:输入、输出、成本明细、时间明细、嵌套跨度

跟踪详细信息视图:

每个轨迹显示:

  • 输入查询文本
  • 输出响应
  • 成本明细: embedding_cost + llm_generation_cost
  • 时间细分: embedding_time, db_search_time, llm_generation_time
  • 嵌套跨度: embedding-generation, vector-search, llm-generation

自定义图表:

LangFuse 支持可配置的自定义图表:

  • 尺寸: time, tool_name, metadata.source
  • 度量 : count, totalCost, avgLatency, p95Latency

完整指南: 咨询 docs/langfuse-dashboard-guide.md 用于详细的仪表板配置。

性能优化

🎯 性能优化(2025-11)

该系统针对响应性能进行了优化:

应用优化:

  1. HNSW矢量索引 (关键)

    • 升级da IVFFlat(lists=1)HNSW
    • 向量搜索速度10-100倍
    • 随着数据集的增长一致性能
  2. 全局嵌入器实例

    • 具有持久缓存的Embedder Singleton
    • 消除每次查询300-500ms的开销
    • 缓存命中率:66%
  3. 连接池优化

    db_pool = await asyncpg.create_pool(
        DATABASE_URL,
        min_size=2,              # Ottimizzato per MCP burst traffic
        max_size=10,             # Sufficient per concurrent queries
        statement_cache_size=100 # Prepared statements abilitati
    )
    
  4. 性能仪表

    • 每个组件的详细定时故障
    • 监控日志: embedding_ms | db_ms | total_ms

性能基线:

Metrica 之前 之后 改进
平均查询时间 3563毫秒 1395毫秒 -61%
缓存查询 298毫秒 237毫秒 -20%
DB搜索 100-300ms 20-60ms -75%

性能工具:

# Verifica status DB index
uv run python scripts/verification/optimize_database.py --check

# Applica ottimizzazioni (upgrade HNSW index)
uv run python scripts/verification/optimize_database.py --apply

# Test performance
uv run python scripts/testing/test_mcp_performance.py

缓存嵌入

该嵌入器包括用于频繁查询的LRU(2000条目)缓存,减少了60-70%的OpenAI API调用。

Streaming中的答案

token-per-token流式传输提供即时反馈:

async with agent.run_stream(user_input, message_history=history) as result:
    async for text in result.stream_text(delta=False):
        print(f"\rAssistant: {text}", end="", flush=True)

高级功能

按文档来源过滤

代理人支持 智能过滤 按特定来源进行搜索,以隔离不同的文档。

它是如何工作的: 用户可以从特定来源请求信息,并且代理会自动应用适当的过滤器。

查询示例 :

查询用户 代理行为
“如何部署?” 搜索整个知识库
“如何仅使用 Docling 文档部署 Docling?” 自动过滤 source_filter="docling"
“在Langfuse中解释跟踪,不要看其他来源” 过滤器 source_filter="langfuse-docs"
“Langfuse部署文档的第二次部署” Filtra su source_filter="langfuse-docs/deployment"

优势:

  • 🎯 准确答案 来自特定来源
  • 🚫 零污染 不同文件之间
  • 🤖 全自动 代理人承认意图
  • 📁 灵活的模式 支持部分路径

查询SQL查询:

SELECT c.content, d.title, d.source
FROM chunks c
JOIN documents d ON c.document_id = d.id
WHERE d.source ILIKE '%docling%'  -- Filtro applicato
ORDER BY c.embedding <=> query_embedding

部署Docker

Docker的先决条件

  • Docker桌面24.0+(下载)
  • Docker Compose v2.0+(包括Docker桌面版)

快速启动Docker(约2分钟)

启动完整的应用程序:

# Avvia tutti i servizi
docker-compose up --build -d

# Visualizza i log
docker-compose logs -f rag-agent

该应用程序将可在 http://localhost:8501

使用 Docker 输入文件:

# Default: CANCELLA il DB e reingerisce tutto (raccomandato)
docker-compose --profile ingestion up ingestion

# AGGIUNGERE documenti senza cancellare (può creare duplicati)
# Usa il doppio slash per Windows + Git Bash
docker-compose run --rm ingestion uv run python -m ingestion.ingest --documents //app/documents --no-clean

# Con opzioni personalizzate
docker-compose run --rm ingestion uv run python -m ingestion.ingest \
  --documents /app/documents \
  --chunk-size 800 \
  --verbose

⚠️ 注: default 命令 自动删除 摄入前的所有现有数据,以避免重复。美国 --no-clean 只有当您想要添加新文档而不触摸现有文档时。

有用的命令 :

# Ferma tutti i servizi
docker-compose down

# Ricostruisci le immagini dopo modifiche al codice
docker-compose build

# Visualizza i container attivi
docker-compose ps

# Accedi al container per debugging
docker-compose exec rag-agent bash

故障排除

常见问题

问题 原因 解决方案
connection refused 数据库无法访问 检查 DATABASE_URL PostgreSQL是活跃的。
extension "vector" not found PGVector 未安装 运行 CREATE EXTENSION vector; 使用 Docker 映像 pgvector/pgvector:pg16
OPENAI_API_KEY not set 缺少变量 添加 OPENAI_API_KEY 在文件中 .env
uv: command not found UV 未安装 安装: curl -LsSf https://astral.sh/uv/install.sh | sh
Python version mismatch Python < 3.10 将 Python 更新到 3.10+
ImportError: docling 缺少依赖性 执行 uv sync

数据库连接

# Verifica connessione
psql $DATABASE_URL -c "SELECT 1"

# Verifica estensione PGVector
psql $DATABASE_URL -c "SELECT * FROM pg_extension WHERE extname = 'vector'"

# Test performance index
python scripts/verification/optimize_database.py --check

重置环境

# Rimuovi cache e reinstalla
rm -rf .venv
uv sync

# Reset database (ATTENZIONE: cancella tutti i dati)
psql $DATABASE_URL < sql/optimize_index.sql

API 参考

工具搜索_知识库

async def search_knowledge_base(
    ctx: RunContext[None],
    query: str,
    limit: int = 5,
    source_filter: str | None = None
) -> str:
    """
    Cerca nella knowledge base usando similarità semantica.

    Args:
        query: La query di ricerca per trovare informazioni rilevanti
        limit: Numero massimo di risultati da restituire (default: 5)
        source_filter: Filtro opzionale per cercare solo in fonti specifiche
                      Esempi: "docling", "langfuse-docs", "langfuse-docs/deployment"
                      Se fornito, verranno cercati solo documenti il cui percorso
                      sorgente contiene questa stringa

    Returns:
        Risultati di ricerca formattati con citazioni delle fonti
    """

使用过滤器的例子:

# Cerca in tutta la knowledge base
await search_knowledge_base(query="come fare il deploy")

# Cerca solo nella documentazione Docling
await search_knowledge_base(
    query="come fare il deploy",
    source_filter="docling"
)

# Cerca solo nella sezione deployment di Langfuse
await search_knowledge_base(
    query="deployment cloud",
    source_filter="langfuse-docs/deployment"
)

过滤器是如何工作的:

  • 代理在用户指定源时自动识别
  • 使用 pattern matching case-insensitive 应用过滤器
  • 用于分离不同的文档(Docking,Langfuse等)
  • 防止反应中的跨文档污染

数据库函数

-- Ricerca similarità vettoriale
SELECT * FROM match_chunks(
    query_embedding::vector(1536),
    match_count INT,
    similarity_threshold FLOAT DEFAULT 0.7
)

返回 chunk :

  • id:UUID数据块
  • content: 文本内容
  • embedding: 矢量嵌入
  • similarity共弦相似度评分(0-1)
  • document_title: 源文件标题
  • document_source: 源文件路径

📚 文档

完整的项目文档,包括API参考,可在 guide/.

本地视图

您可以启动本地服务器以浏览文档:

# Avvia il server di documentazione
uv run mkdocs serve

文件将可在 http://127.0.0.1:8000.

静态生成

要生成静态文档 (HTML):

# Genera la documentazione in site/
uv run mkdocs build

GitHub页面

文档在每次推送到分支时都会自动发布到 GitHub Pages main.

项目结构

docling-rag-agent/
├── app.py                         # Interfaccia web Streamlit
├── docling_mcp/                   # MCP server per Cursor IDE (standalone)
├── core/
│   ├── agent.py                   # PydanticAI agent wrapper
│   └── rag_service.py             # Core RAG logic (decoupled)
├── ingestion/
│   ├── ingest.py                  # Pipeline ingestione documenti
│   ├── embedder.py                # Generazione embedding con caching
│   └── chunker.py                 # Chunking intelligente (Docling HybridChunker)
├── utils/
│   ├── providers.py               # Configurazione modelli/client OpenAI
│   ├── db_utils.py                # Connection pooling ottimizzato
│   └── models.py                  # Modelli Pydantic per validazione
├── sql/
│   └── optimize_index.sql         # Schema completo + HNSW index ottimizzato
├── scripts/
│   ├── optimize_database.py       # Tool gestione index e performance
│   └── test_mcp_performance.py    # Performance test suite
├── docs/
│   ├── optimization-summary.md    # Analisi performance optimization
│   ├── performance-optimization-guide.md
│   └── optimization-deployment.md
├── documents/                     # Documenti per ingestione
├── pyproject.toml                 # Dipendenze progetto (uv)
├── .env.example                   # Template variabili d'ambiente
└── README.md                      # Questo file