Commit 88ce838f by 黄南光

新增llm-rag系统,修复日志打印,修复切块和查询处理

1 parent 57529979
......@@ -32,3 +32,13 @@ GEMINI.md
# .env
.env
# ref
/src/ref/
#AgentTool
CLAUDE.md
AGENTS.md
GEMINI.md
......@@ -136,6 +136,7 @@ export default function EnterpriseWiki() {
reasoning?: ReasoningStep[];
startTime?: number;
endTime?: number;
isStreaming?: boolean;
}[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [isDeleting, setIsDeleting] = useState<string | null>(null);
......@@ -685,8 +686,10 @@ export default function EnterpriseWiki() {
// 超时保护:90 秒内没有任何 SSE 数据则自动断开
const TIMEOUT_MS = 90_000;
let lastEventTime = Date.now();
let streamFinished = false;
let streamError: Error | null = null;
while (true) {
while (!streamFinished) {
// 检查超时
if (Date.now() - lastEventTime > TIMEOUT_MS) {
reader.cancel();
......@@ -705,13 +708,52 @@ export default function EnterpriseWiki() {
if (!trimmedLine || !trimmedLine.startsWith("data: ")) continue;
const dataStr = trimmedLine.slice(6).trim();
if (dataStr === "[DONE]") break;
if (dataStr === "[DONE]") {
streamFinished = true;
setIsLoading(false);
setAbortController(null);
break;
}
if (dataStr === "[INIT]") continue;
try {
const data = JSON.parse(dataStr);
const m_id = data.id || `msg-${Date.now()}`;
if (data.type === "heartbeat") {
continue;
}
if (data.type === "done") {
streamFinished = true;
setIsLoading(false);
setAbortController(null);
setChatHistory(prev => {
if (prev.length === 0) return prev;
const newHistory = [...prev];
for (let i = newHistory.length - 1; i >= 0; i--) {
if (newHistory[i].role === "ai") {
newHistory[i] = {
...newHistory[i],
isStreaming: false,
endTime: newHistory[i].endTime || Date.now()
};
break;
}
}
return newHistory;
});
break;
}
if (data.type === "error") {
streamError = new Error(data.content || "Wiki 查询失败");
streamFinished = true;
setIsLoading(false);
setAbortController(null);
break;
}
if (data.type === "sources") {
const sources = data.content;
setChatHistory(prev => {
......@@ -736,7 +778,7 @@ export default function EnterpriseWiki() {
time: new Date().toLocaleTimeString('zh-CN', { hour12: false })
});
}
newHistory[lastIdx] = { ...last, reasoning };
newHistory[lastIdx] = { ...last, reasoning, isStreaming: true, endTime: undefined };
}
return newHistory;
});
......@@ -746,7 +788,7 @@ export default function EnterpriseWiki() {
let lastIdx = newHistory.length - 1;
if (lastIdx < 0 || newHistory[lastIdx].role !== "ai") {
newHistory.push({ role: "ai", content: "", reasoning: [], startTime: Date.now() });
newHistory.push({ role: "ai", content: "", reasoning: [], startTime: Date.now(), isStreaming: true });
lastIdx = newHistory.length - 1;
}
......@@ -772,7 +814,7 @@ export default function EnterpriseWiki() {
});
}
newHistory[lastIdx] = { ...last, reasoning };
newHistory[lastIdx] = { ...last, reasoning, isStreaming: true, endTime: undefined };
return newHistory;
});
} else if (data.type === "bot" || data.type === "stream") {
......@@ -794,12 +836,14 @@ export default function EnterpriseWiki() {
const lastIdx = newHistory.length - 1;
if (lastIdx < 0 || newHistory[lastIdx].role !== "ai") {
newHistory.push({ role: "ai", content: aiResponse, reasoning: [], startTime: Date.now() });
newHistory.push({ role: "ai", content: aiResponse, reasoning: [], startTime: Date.now(), isStreaming: true });
} else {
newHistory[lastIdx] = {
...newHistory[lastIdx],
content: aiResponse,
startTime: newHistory[lastIdx].startTime || Date.now()
startTime: newHistory[lastIdx].startTime || Date.now(),
isStreaming: true,
endTime: undefined
};
}
return newHistory;
......@@ -809,6 +853,10 @@ export default function EnterpriseWiki() {
console.error("Parse error", e, dataStr);
}
}
if (streamError) {
throw streamError;
}
}
} catch (e) {
if (e instanceof Error && e.name === 'AbortError') {
......@@ -823,10 +871,21 @@ export default function EnterpriseWiki() {
if (prev.length === 0) return prev;
const newHistory = [...prev];
const lastIdx = newHistory.length - 1;
if (newHistory[lastIdx].role === "ai") {
const finishedAt = Date.now();
for (let i = 0; i < newHistory.length; i++) {
if (newHistory[i].role === "ai" && newHistory[i].isStreaming) {
newHistory[i] = {
...newHistory[i],
isStreaming: false,
endTime: newHistory[i].endTime || finishedAt
};
}
}
if (newHistory[lastIdx].role === "ai" && !newHistory[lastIdx].endTime) {
newHistory[lastIdx] = {
...newHistory[lastIdx],
endTime: Date.now()
isStreaming: false,
endTime: finishedAt
};
}
return newHistory;
......@@ -1461,7 +1520,7 @@ export default function EnterpriseWiki() {
role={msg.role}
content={msg.content}
reasoning={msg.reasoning}
isStreaming={isLoading && idx === chatHistory.length - 1}
isStreaming={msg.isStreaming ?? (isLoading && idx === chatHistory.length - 1 && !msg.endTime)}
startTime={msg.startTime}
endTime={msg.endTime}
/>
......
......@@ -7,7 +7,7 @@ import {
RefreshCw, RotateCcw, Search,
Send, Trash2, Upload, MessageSquare, MoreVertical, X, Filter, Folder, Eraser,
CheckSquare, Square, ChevronDown, ChevronRight, Wrench, CheckCircle2, BookOpen, Clock,
FileImage, FileSpreadsheet, FileArchive, FileCode, AlertCircle
FileImage, FileSpreadsheet, FileArchive, FileCode, AlertCircle, Download
} from "lucide-react";
import { cn } from "@/lib/utils";
import type { RagChunk, RagFile, RagMessage, RagReasoningStep } from "@/lib/rag-types";
......@@ -103,6 +103,7 @@ export default function RagWorkspace() {
const inputRef = useRef<HTMLInputElement>(null);
const chatEndRef = useRef<HTMLDivElement>(null);
const chatAbortRef = useRef<AbortController | null>(null);
const actionRunning = useRef(false);
const handleUploadSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files.length > 0) {
......@@ -241,6 +242,8 @@ export default function RagWorkspace() {
};
const runAction = async (action: () => Promise<unknown>, successMsg?: string) => {
if (actionRunning.current) return;
actionRunning.current = true;
setLoading(true);
try {
await action();
......@@ -250,6 +253,7 @@ export default function RagWorkspace() {
} catch (error) {
alert(error instanceof Error ? error.message : "操作失败");
} finally {
actionRunning.current = false;
setLoading(false);
}
};
......@@ -385,6 +389,54 @@ export default function RagWorkspace() {
setSelectedIds(new Set());
};
const handleBatchDownload = async () => {
const ids = Array.from(selectedIds);
if (!ids.length) return alert("请先勾选文件");
setLoading(true);
try {
const API_BASE = process.env.NEXT_PUBLIC_API_URL || (typeof window !== "undefined" ? `http://${window.location.hostname}:8104` : "http://127.0.0.1:8104");
const res = await fetch(`${API_BASE}/rag/files/batch_download`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids })
});
if (!res.ok) {
const errorData = await res.json().catch(() => ({ detail: "下载失败" }));
throw new Error(errorData.detail || "下载失败");
}
const blob = await res.blob();
let filename = ids.length === 1 ? "download" : "batch_download.zip";
const disposition = res.headers.get('Content-Disposition');
if (disposition && disposition.includes("filename*=utf-8''")) {
filename = decodeURIComponent(disposition.split("filename*=utf-8''")[1]);
} else if (disposition && disposition.includes('filename=')) {
filename = disposition.split('filename=')[1].replace(/"/g, '');
} else if (ids.length === 1) {
const selectedFile = files.find(f => f.id === ids[0]);
if (selectedFile) filename = selectedFile.name;
}
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
setSelectedIds(new Set());
} catch (error) {
alert(error instanceof Error ? error.message : "下载失败");
} finally {
setLoading(false);
}
};
return (
......@@ -441,6 +493,9 @@ export default function RagWorkspace() {
<button title="批量删除" onClick={handleBatchDelete} className="rounded-md p-1.5 hover:bg-slate-100 text-slate-600">
<Trash2 className="h-4 w-4" />
</button>
<button title="批量下载" onClick={handleBatchDownload} className="rounded-md p-1.5 hover:bg-slate-100 text-slate-600">
<Download className="h-4 w-4" />
</button>
<button title="刷新" onClick={() => refresh()} className="rounded-md p-1.5 hover:bg-slate-100 text-slate-600">
<RefreshCw className="h-4 w-4" />
......@@ -463,6 +518,19 @@ export default function RagWorkspace() {
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<input
type="checkbox"
className="cursor-pointer rounded border-slate-300 text-blue-600 focus:ring-blue-500"
checked={filteredFiles.length > 0 && selectedIds.size === filteredFiles.length}
onChange={(e) => {
if (e.target.checked) {
setSelectedIds(new Set(filteredFiles.map(f => f.id)));
} else {
setSelectedIds(new Set());
}
}}
title="全选/取消全选"
/>
<Filter className="h-3.5 w-3.5 text-slate-400" />
<select
className="text-xs bg-transparent outline-none text-slate-600 cursor-pointer"
......@@ -544,7 +612,7 @@ export default function RagWorkspace() {
)}
</div>
</div>
{file.error_message && <div className="mt-2 line-clamp-2 text-xs text-red-600 ml-7">{file.error_message}</div>}
{file.status !== "Indexing" && file.error_message && <div className="mt-2 line-clamp-2 text-xs text-red-600 ml-7">{file.error_message}</div>}
</div>
))}
{filteredFiles.length === 0 && <div className="text-center text-sm text-slate-400 py-10">暂无匹配文件</div>}
......
......@@ -43,6 +43,8 @@ python-frontmatter==1.3.0
lxml==6.1.1
# Utils & Misc
typing_extensions>=4.15.0
Pygments>=2.18.0
pytest>=8.0.0
python-dotenv==1.2.2
requests==2.34.2
......
-- 轻量级 RAG 已收敛为 rag_files / rag_chunks / rag_query_logs 三张核心表。
-- 以下表属于旧的“平台化日志/会话/评测”设计,线上链路不再依赖。
-- 请在确认不需要保留历史日志后,手动连接当前业务数据库执行本脚本。
-- Drop legacy RAG tables that are no longer used by the independent RAG flow.
-- This script does not drop the current core tables:
-- rag_documents, rag_chunks, rag_index_runs, rag_query_logs
DROP TABLE IF EXISTS rag_retrieval_logs;
DROP TABLE IF EXISTS rag_messages;
......
-- Rebuild the independent RAG schema from scratch.
-- This script is intentionally destructive for RAG tables only.
-- Before running it in a shared environment, back up data and recreate the
-- Qdrant collection so DB rows and vector payloads stay consistent.
SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS rag_query_logs;
DROP TABLE IF EXISTS rag_index_runs;
DROP TABLE IF EXISTS rag_chunks;
DROP TABLE IF EXISTS rag_files;
DROP TABLE IF EXISTS rag_documents;
SET FOREIGN_KEY_CHECKS = 1;
CREATE TABLE rag_documents (
id VARCHAR(36) NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
file_type VARCHAR(50) NOT NULL,
size BIGINT NOT NULL DEFAULT 0,
word_count INT NOT NULL DEFAULT 0,
status VARCHAR(50) NOT NULL DEFAULT 'Pending',
source_path VARCHAR(1024) NOT NULL,
content_hash VARCHAR(128) NULL,
metadata_json LONGTEXT NULL,
parser_version VARCHAR(50) NULL,
chunker_version VARCHAR(50) NULL,
block_count INT NOT NULL DEFAULT 0,
chunk_count INT NOT NULL DEFAULT 0,
parent_chunk_count INT NOT NULL DEFAULT 0,
child_chunk_count INT NOT NULL DEFAULT 0,
index_duration_ms INT NOT NULL DEFAULT 0,
error_message LONGTEXT NULL,
created_at DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
index_started_at DATETIME NULL,
indexed_at DATETIME NULL,
INDEX idx_rag_documents_status (status),
INDEX idx_rag_documents_hash (content_hash)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE rag_chunks (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
chunk_id VARCHAR(64) NOT NULL,
document_id VARCHAR(36) NOT NULL,
parent_chunk_id VARCHAR(64) NULL,
chunk_level VARCHAR(20) NOT NULL,
chunk_index INT NOT NULL DEFAULT 0,
content LONGTEXT NOT NULL,
content_hash VARCHAR(128) NOT NULL,
token_estimate INT NOT NULL DEFAULT 0,
title_path VARCHAR(1024) NULL,
source_name VARCHAR(255) NOT NULL,
source_path VARCHAR(1024) NOT NULL,
file_type VARCHAR(50) NOT NULL,
page_number INT NULL,
page_start INT NULL,
page_end INT NULL,
slide_number INT NULL,
sheet_name VARCHAR(255) NULL,
row_start INT NULL,
row_end INT NULL,
char_start INT NULL,
char_end INT NULL,
prev_chunk_id VARCHAR(64) NULL,
next_chunk_id VARCHAR(64) NULL,
status VARCHAR(50) NOT NULL DEFAULT 'active',
intent_type VARCHAR(50) NULL,
page_type VARCHAR(50) NULL,
brand VARCHAR(100) NULL,
brand_series VARCHAR(100) NULL,
business_category VARCHAR(100) NULL,
sub_business VARCHAR(100) NULL,
content_kind VARCHAR(50) NULL,
section_title VARCHAR(255) NULL,
section_path_json LONGTEXT NULL,
parse_status VARCHAR(50) NULL,
parse_quality VARCHAR(50) NULL,
table_header_json LONGTEXT NULL,
qdrant_point_id VARCHAR(64) NULL,
parser_version VARCHAR(50) NULL,
chunker_version VARCHAR(50) NULL,
metadata_json LONGTEXT NULL,
created_at DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uq_rag_chunks_chunk_id (chunk_id),
INDEX idx_rag_chunks_document_level (document_id, chunk_level),
INDEX idx_rag_chunks_parent (parent_chunk_id),
INDEX idx_rag_chunks_status (status),
INDEX idx_rag_chunks_content_kind (content_kind),
INDEX idx_rag_chunks_business (business_category, sub_business),
INDEX idx_rag_chunks_brand (brand, brand_series),
INDEX idx_rag_chunks_source_loc (page_start, page_end, sheet_name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE rag_index_runs (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
document_id VARCHAR(36) NOT NULL,
status VARCHAR(50) NOT NULL,
parser_version VARCHAR(50) NULL,
chunker_version VARCHAR(50) NULL,
block_count INT NOT NULL DEFAULT 0,
parent_chunk_count INT NOT NULL DEFAULT 0,
child_chunk_count INT NOT NULL DEFAULT 0,
vector_count INT NOT NULL DEFAULT 0,
duration_ms INT NOT NULL DEFAULT 0,
error_message LONGTEXT NULL,
created_at DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_rag_index_runs_document (document_id),
INDEX idx_rag_index_runs_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE rag_query_logs (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
session_id VARCHAR(100) NULL,
query_text LONGTEXT NOT NULL,
rewritten_query LONGTEXT NULL,
intent_result_json LONGTEXT NULL,
retrieval_plan_json LONGTEXT NULL,
query_plan_json LONGTEXT NULL,
filters_json LONGTEXT NULL,
ranked_json LONGTEXT NULL,
sources_json LONGTEXT NULL,
adopted_chunk_ids_json LONGTEXT NULL,
citation_map_json LONGTEXT NULL,
answer_text LONGTEXT NULL,
model_name VARCHAR(100) NULL,
total_tokens INT NOT NULL DEFAULT 0,
duration_ms INT NOT NULL DEFAULT 0,
status VARCHAR(50) NOT NULL DEFAULT 'Success',
error_message LONGTEXT NULL,
created_at DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_rag_query_logs_session (session_id),
INDEX idx_rag_query_logs_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
import uuid
from datetime import datetime
from sqlalchemy import Column, Integer, String, BigInteger, Text, DateTime, Numeric, ForeignKey
from sqlalchemy import Column, Integer, String, BigInteger, Text, DateTime, Numeric, ForeignKey, Index, UniqueConstraint
from sqlalchemy.orm import relationship
from src.database.session import Base
......@@ -68,16 +68,24 @@ class WikiQueryLog(Base):
class RagFile(Base):
__tablename__ = "rag_files"
__tablename__ = "rag_documents"
__table_args__ = (
Index("idx_rag_documents_status", "status"),
Index("idx_rag_documents_hash", "content_hash"),
)
id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
name = Column(String(255), nullable=False)
format = Column(String(50), nullable=False)
format = Column("file_type", String(50), nullable=False)
size = Column(BigInteger, nullable=False, default=0)
word_count = Column(Integer, nullable=False, default=0)
status = Column(String(50), nullable=False, default="Pending")
source_path = Column(String(1024), nullable=False)
content_hash = Column(String(128), nullable=True)
metadata_json = Column(Text, nullable=True)
parser_version = Column(String(50), nullable=True)
chunker_version = Column(String(50), nullable=True)
block_count = Column(Integer, nullable=False, default=0)
chunk_count = Column(Integer, nullable=False, default=0)
parent_chunk_count = Column(Integer, nullable=False, default=0)
child_chunk_count = Column(Integer, nullable=False, default=0)
......@@ -85,17 +93,29 @@ class RagFile(Base):
error_message = Column(Text, nullable=True)
created_at = Column(DateTime, default=datetime.now)
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
index_started_at = Column(DateTime, nullable=True)
indexed_at = Column(DateTime, nullable=True)
chunks = relationship("RagChunk", back_populates="file", cascade="all, delete-orphan", lazy="noload", primaryjoin="RagFile.id == RagChunk.file_id", foreign_keys="[RagChunk.file_id]")
index_runs = relationship("RagIndexRun", back_populates="file", cascade="all, delete-orphan", lazy="noload", primaryjoin="RagFile.id == RagIndexRun.file_id", foreign_keys="[RagIndexRun.file_id]")
class RagChunk(Base):
__tablename__ = "rag_chunks"
__table_args__ = (
UniqueConstraint("chunk_id", name="uq_rag_chunks_chunk_id"),
Index("idx_rag_chunks_document_level", "document_id", "chunk_level"),
Index("idx_rag_chunks_parent", "parent_chunk_id"),
Index("idx_rag_chunks_status", "status"),
Index("idx_rag_chunks_content_kind", "content_kind"),
Index("idx_rag_chunks_business", "business_category", "sub_business"),
Index("idx_rag_chunks_brand", "brand", "brand_series"),
Index("idx_rag_chunks_source_loc", "page_start", "page_end", "sheet_name"),
)
id = Column(Integer, primary_key=True, autoincrement=True)
chunk_id = Column(String(64), nullable=False)
file_id = Column(String(36), nullable=False)
file_id = Column("document_id", String(36), nullable=False)
parent_chunk_id = Column(String(64), nullable=True)
chunk_level = Column(String(20), nullable=False) # parent / child
chunk_index = Column(Integer, nullable=False, default=0)
......@@ -107,25 +127,67 @@ class RagChunk(Base):
source_path = Column(String(1024), nullable=False)
file_type = Column(String(50), nullable=False)
page_number = Column(Integer, nullable=True)
page_start = Column(Integer, nullable=True)
page_end = Column(Integer, nullable=True)
slide_number = Column(Integer, nullable=True)
sheet_name = Column(String(255), nullable=True)
row_start = Column(Integer, nullable=True)
row_end = Column(Integer, nullable=True)
char_start = Column(Integer, nullable=True)
char_end = Column(Integer, nullable=True)
prev_chunk_id = Column(String(64), nullable=True)
next_chunk_id = Column(String(64), nullable=True)
status = Column(String(50), nullable=False, default="active")
intent_type = Column(String(50), nullable=True)
page_type = Column(String(50), nullable=True)
brand = Column(String(100), nullable=True)
brand_series = Column(String(100), nullable=True)
business_category = Column(String(100), nullable=True)
sub_business = Column(String(100), nullable=True)
content_kind = Column(String(50), nullable=True)
section_title = Column(String(255), nullable=True)
section_path_json = Column(Text, nullable=True)
parse_status = Column(String(50), nullable=True)
parse_quality = Column(String(50), nullable=True)
table_header_json = Column(Text, nullable=True)
qdrant_point_id = Column(String(64), nullable=True)
parser_version = Column(String(50), nullable=True)
chunker_version = Column(String(50), nullable=True)
metadata_json = Column(Text, nullable=True)
created_at = Column(DateTime, default=datetime.now)
file = relationship("RagFile", back_populates="chunks", primaryjoin="RagChunk.file_id == RagFile.id", foreign_keys=[file_id])
class RagIndexRun(Base):
__tablename__ = "rag_index_runs"
__table_args__ = (
Index("idx_rag_index_runs_document", "document_id"),
Index("idx_rag_index_runs_status", "status"),
)
id = Column(Integer, primary_key=True, autoincrement=True)
file_id = Column("document_id", String(36), nullable=False)
status = Column(String(50), nullable=False)
parser_version = Column(String(50), nullable=True)
chunker_version = Column(String(50), nullable=True)
block_count = Column(Integer, nullable=False, default=0)
parent_chunk_count = Column(Integer, nullable=False, default=0)
child_chunk_count = Column(Integer, nullable=False, default=0)
vector_count = Column(Integer, nullable=False, default=0)
duration_ms = Column(Integer, nullable=False, default=0)
error_message = Column(Text, nullable=True)
created_at = Column(DateTime, default=datetime.now)
file = relationship("RagFile", back_populates="index_runs", primaryjoin="RagIndexRun.file_id == RagFile.id", foreign_keys=[file_id])
class RagQueryLog(Base):
__tablename__ = "rag_query_logs"
__table_args__ = (
Index("idx_rag_query_logs_session", "session_id"),
Index("idx_rag_query_logs_status", "status"),
)
id = Column(Integer, primary_key=True, autoincrement=True)
session_id = Column(String(100), nullable=True)
......@@ -133,6 +195,10 @@ class RagQueryLog(Base):
rewritten_query = Column(Text, nullable=True)
intent_result_json = Column(Text, nullable=True)
retrieval_plan_json = Column(Text, nullable=True)
query_plan_json = Column(Text, nullable=True)
filters_json = Column(Text, nullable=True)
ranked_json = Column(Text, nullable=True)
sources_json = Column(Text, nullable=True)
adopted_chunk_ids_json = Column(Text, nullable=True)
citation_map_json = Column(Text, nullable=True)
answer_text = Column(Text, nullable=True)
......
"""Integrated RAG subsystem for the wiki backend."""
"""
Wiki 知识库后端的综合 RAG (Retrieval-Augmented Generation,检索增强生成) 子系统。
该包提供了文档的切块、向量化索引、检索以及调用大模型生成回答的核心功能。
"""
......@@ -22,7 +22,7 @@ QDRANT_COLLECTION = os.environ.get("QDRANT_COLLECTION", "rag_chunks")
# RAG 链路使用的模型:回答、意图识别、查询改写、向量化。
# 用于最终基于检索到的上下文生成回答的大语言模型
# RAG_ANSWER_MODEL = os.environ.get("RAG_ANSWER_MODEL", "qwen3.7-plus")
RAG_ANSWER_MODEL = os.environ.get("RAG_ANSWER_MODEL", "qwen-plus")
RAG_ANSWER_MODEL = os.environ.get("RAG_ANSWER_MODEL", "qwen-flash")
# 用于判断用户查询意图(如闲聊、查知识等)的大语言模型
RAG_INTENT_MODEL = os.environ.get("RAG_INTENT_MODEL", "qwen-flash")
# 用于改写用户查询(如补充代词、提取关键词)以提升检索效果的大模型
......@@ -60,11 +60,9 @@ RAG_QDRANT_HYBRID = os.environ.get("RAG_QDRANT_HYBRID", "true").lower() == "true
# ---------------------------------------------------------
# 精排 (Rerank) 配置
# ---------------------------------------------------------
# 精排开关和模型配置。
# 是否在粗排后启用独立的 Reranker 模型进行二次精确重排打分,默认为 true
RAG_RERANKER_ENABLED = os.environ.get("RAG_RERANKER_ENABLED", "true").lower() == "true"
# 调用的 Reranker 模型名称,通常比普通的 Embedding 拥有更深层的语义匹配能力,默认 BAAI/bge-reranker-v2-m3
RAG_RERANKER_MODEL = os.environ.get("RAG_RERANKER_MODEL", "BAAI/bge-reranker-v2-m3")
# 精排模型配置。
# 调用的 Reranker 模型名称,通常比普通的 Embedding 拥有更深层的语义匹配能力,默认 qwen3-vl-rerank
RAG_RERANKER_MODEL = os.environ.get("RAG_RERANKER_MODEL", "qwen3-vl-rerank")
# 提交给 Reranker 模型进行重新打分的最大候选片段数量,控制 API 开销,默认 20 个
RAG_RERANKER_TOP_K = int(os.environ.get("RAG_RERANKER_TOP_K", "20"))
......
"""
数据摄取(Ingest)模块的统一导出文件。
该模块集中导出了文档解析、分块以及元数据提取相关的核心类和函数,
方便其他模块统一从 src.rag.ingest 进行导入使用。
"""
from src.rag.chunking import RagChunkData, build_chunks
from src.rag.loaders import DocumentBlock, parse_document
from src.rag.metadata import BUSINESS_KEYWORDS, KNOWN_BRANDS, BusinessMetadata, extract_metadata
# 定义该模块公开暴露的接口
__all__ = [
"BUSINESS_KEYWORDS",
"KNOWN_BRANDS",
"BusinessMetadata",
"DocumentBlock",
"RagChunkData",
"build_chunks",
"extract_metadata",
"parse_document",
"BUSINESS_KEYWORDS", # 业务相关的核心关键词表
"KNOWN_BRANDS", # 已知的汽车品牌列表
"BusinessMetadata", # 业务元数据数据类
"DocumentBlock", # 文档基础块(从解析器输出的最小单位)
"RagChunkData", # RAG 切块数据(包含向量化及检索所需信息的片段)
"build_chunks", # 构建父子级片段的核心函数
"extract_metadata", # 从文本中提取业务元数据的函数
"parse_document", # 解析原始文档(如 PDF、Word)的函数
]
"""
大语言模型(LLM)与词向量(Embedding)调用模块。
对大语言模型进行统一封装,提供了流式与非流式对话接口,
以及支持批量处理与内存缓存的 Embedding 向量化功能。
"""
import logging
import threading
import time
......@@ -16,13 +21,24 @@ from src.utils.llm_tracker import get_llm_model
logger = logging.getLogger(__name__)
# 用于缓存 Query 文本对应的 Embedding 向量结果,以降低 API 成本和加速重复检索
_embedding_cache: OrderedDict[str, tuple[float, list[float]]] = OrderedDict()
# 读写缓存时的线程锁,保证并发安全
_cache_lock = threading.RLock()
async def chat_once(model_name: str, prompt: str) -> str:
"""
进行单次(非流式)的大语言模型对话请求。
:param model_name: 调用的模型名称
:param prompt: 构建好的完整提示词
:return: 模型生成的纯文本字符串结果
"""
model = get_llm_model(model_name)
res = await model([{"role": "user", "content": prompt}])
# 兼容处理某些模型可能返回异步迭代器(流)的情况
if hasattr(res, "__aiter__"):
final_chunk = None
async for chunk in res:
......@@ -30,15 +46,25 @@ async def chat_once(model_name: str, prompt: str) -> str:
res = final_chunk
content = getattr(res, "content", "")
# 针对多模态或者包含其他对象结构的返回内容,提取其中类型为 'text' 的部分
if isinstance(content, list):
return "".join(str(x.get("text", "")) for x in content if isinstance(x, dict) and x.get("type") == "text")
return str(content)
async def chat_stream(model_name: str, prompt: str, *, include_thinking: bool = False):
"""
进行流式大语言模型对话请求,按块(Chunk)不断产出生成结果。
:param model_name: 调用的模型名称
:param prompt: 构建好的完整提示词
:param include_thinking: 是否需要返回模型“思考”过程的文本(如某些带有深度思考机制的模型)
:yield: 不断吐出格式如 {"type": "answer_delta", "content": "..."} 的字典
"""
model = get_llm_model(model_name)
res = await model([{"role": "user", "content": prompt}])
# 若模型返回的是异步生成器(正常流式表现)
if hasattr(res, "__aiter__"):
last_text_len = 0
last_thinking_len = 0
......@@ -51,6 +77,7 @@ async def chat_stream(model_name: str, prompt: str, *, include_thinking: bool =
text = str(content)
thinking = ""
# 提取每次迭代新增的部分文本
text_delta = text[last_text_len:]
thinking_delta = thinking[last_thinking_len:]
......@@ -62,6 +89,7 @@ async def chat_stream(model_name: str, prompt: str, *, include_thinking: bool =
last_text_len = len(text)
last_thinking_len = len(thinking)
else:
# 兼容处理未开启流式时,直接一次性返回了结果的情况
content = getattr(res, "content", "")
if isinstance(content, list):
text = "".join(str(x.get("text", "")) for x in content if isinstance(x, dict) and x.get("type") == "text")
......@@ -77,23 +105,34 @@ async def chat_stream(model_name: str, prompt: str, *, include_thinking: bool =
def embed_texts(texts: list[str], *, allow_cache: bool = False) -> list[list[float]]:
"""调用 DashScope embedding。"""
"""
调用阿里云 DashScope 的文本向量化(Embedding)接口,将字符串数组批量转换为高维浮点数向量。
:param texts: 需要向量化的字符串列表
:param allow_cache: 是否允许从本地内存缓存中直接返回(通常仅在查询阶段且单个输入时开启)
:return: 对应的二维向量数组
"""
if not texts:
return []
# 如果允许缓存且只有一个文本(通常是用户搜索的 Query),优先检查缓存
if allow_cache and len(texts) == 1:
cached = _get_cached_embedding(texts[0])
if cached is not None:
return [cached]
try:
import dashscope
start = time.time()
vectors = []
# 按批量 10 个一组请求 Embedding 接口,避免请求超载
for i in range(0, len(texts), 10):
batch_texts = texts[i : i + 10]
max_retries = 3
resp = None
# 添加重试机制
for attempt in range(max_retries):
try:
resp = dashscope.TextEmbedding.call(model=RAG_EMBEDDING_MODEL, input=batch_texts, api_key=API_KEY)
......@@ -107,12 +146,15 @@ def embed_texts(texts: list[str], *, allow_cache: bool = False) -> list[list[flo
else:
raise
# 解析接口返回的向量结果
output = resp.get("output") if isinstance(resp, dict) else getattr(resp, "output", None)
embeddings = output.get("embeddings", []) if isinstance(output, dict) else []
batch_vectors = [item["embedding"] for item in embeddings]
vectors.extend(batch_vectors)
if len(vectors) != len(texts):
raise RuntimeError(f"DashScope embedding count mismatch: expected={len(texts)} actual={len(vectors)}")
logger.info(
"[RAG] Embedding 完成: model=%s texts=%s dim=%s duration_ms=%s",
RAG_EMBEDDING_MODEL,
......@@ -120,8 +162,11 @@ def embed_texts(texts: list[str], *, allow_cache: bool = False) -> list[list[flo
len(vectors[0]),
int((time.time() - start) * 1000),
)
# 将单个查询成功的结果写入缓存
if allow_cache and len(texts) == 1:
_set_cached_embedding(texts[0], vectors[0])
return vectors
except Exception as exc:
logger.exception("[RAG] Embedding API 不可用")
......@@ -129,14 +174,17 @@ def embed_texts(texts: list[str], *, allow_cache: bool = False) -> list[list[flo
def embedding_model_name() -> str:
"""返回当前系统正在使用的 Embedding 模型名称。"""
return RAG_EMBEDDING_MODEL
def _cache_key(text: str) -> str:
"""构建缓存主键,带上模型名以防模型切换导致向量维度或含义不匹配。"""
return f"{RAG_EMBEDDING_MODEL}:{text}"
def _get_cached_embedding(text: str) -> list[float] | None:
"""尝试从内存 LRU 队列中读取有效的 Embedding 缓存向量。"""
key = _cache_key(text)
now = time.time()
with _cache_lock:
......@@ -144,17 +192,21 @@ def _get_cached_embedding(text: str) -> list[float] | None:
if not cached:
return None
ts, vector = cached
# 判断缓存是否过期
if now - ts > RAG_QUERY_CACHE_TTL_SECONDS:
_embedding_cache.pop(key, None)
return None
# 使用过后移动到有序字典末尾,维持 LRU 机制
_embedding_cache.move_to_end(key)
return vector
def _set_cached_embedding(text: str, vector: list[float]) -> None:
"""将刚刚计算的文本 Embedding 结果保存到 LRU 内存缓存中。"""
key = _cache_key(text)
with _cache_lock:
_embedding_cache[key] = (time.time(), vector)
_embedding_cache.move_to_end(key)
# 容量控制,超出则剔除最早未被使用的缓存项
while len(_embedding_cache) > RAG_QUERY_CACHE_SIZE:
_embedding_cache.popitem(last=False)
from __future__ import annotations
import re
from typing import Any
from src.rag.loaders.base import DocumentBlock
RAG_PARSER_VERSION = "rag-parser-v2"
RAG_CHUNKER_VERSION = "rag-chunker-v2"
def enrich_blocks(
blocks: list[DocumentBlock],
*,
parse_method: str,
source_page_count: int | None = None,
) -> list[DocumentBlock]:
"""Apply the common RAG loader metadata contract in-place."""
for block in blocks:
metadata = block.metadata
metadata.setdefault("parser_version", RAG_PARSER_VERSION)
metadata.setdefault("chunker_version", RAG_CHUNKER_VERSION)
metadata.setdefault("parse_method", parse_method)
metadata.setdefault("parse_status", "ok")
metadata.setdefault("parse_quality", _quality_for_text(block.text))
metadata.setdefault("content_role", "table" if block.block_type == "table" else "body")
metadata.setdefault("content_kind", "table" if block.block_type == "table" else "text")
if source_page_count is not None:
metadata.setdefault("source_page_count", source_page_count)
if block.page_number is not None:
metadata.setdefault("page_start", block.page_number)
metadata.setdefault("page_end", block.page_number)
if block.slide_number is not None:
metadata.setdefault("slide_start", block.slide_number)
metadata.setdefault("slide_end", block.slide_number)
if block.sheet_name:
metadata.setdefault("sheet_name", block.sheet_name)
if block.row_start is not None:
metadata.setdefault("row_start", block.row_start)
if block.row_end is not None:
metadata.setdefault("row_end", block.row_end)
if block.title_path:
section_path = [part.strip() for part in block.title_path.split("/") if part.strip()]
if section_path:
metadata.setdefault("section_path", section_path)
metadata.setdefault("section_title", section_path[-1])
if block.block_type == "table":
metadata.setdefault("table_markdown", True)
metadata.setdefault("table_header", markdown_table_header(block.text))
rows = markdown_table_data_rows(block.text)
if block.row_start is None and rows:
block.row_start = rows[0]
block.row_end = rows[-1]
metadata.setdefault("row_start", block.row_start)
metadata.setdefault("row_end", block.row_end)
metadata.setdefault("table_row_count", len(rows))
return blocks
def markdown_table_header(text: str) -> list[str]:
lines = [line.strip() for line in text.splitlines() if line.strip()]
if not lines or "|" not in lines[0]:
return []
return [cell.strip() for cell in lines[0].strip("|").split("|")]
def markdown_table_data_rows(text: str) -> list[int]:
lines = [line.strip() for line in text.splitlines() if line.strip()]
rows: list[int] = []
for index, line in enumerate(lines, start=1):
if "|" not in line:
continue
cells = [cell.strip() for cell in line.strip("|").split("|")]
if not cells:
continue
if index == 1 or all(re.fullmatch(r":?-{3,}:?", cell or "") for cell in cells):
continue
rows.append(index)
return rows
def _quality_for_text(text: str) -> str:
stripped = (text or "").strip()
if not stripped:
return "empty"
replacement_ratio = stripped.count("\ufffd") / max(len(stripped), 1)
if replacement_ratio > 0.02:
return "garbled"
if len(stripped) < 12:
return "short"
return "normal"
from __future__ import annotations
from src.rag.loaders.base import DocumentBlock, register_loader
from src.rag.loaders.common import enrich_blocks
from src.rag.utils import file_ext
......@@ -37,9 +38,19 @@ class ExcelLoader:
row_start=start + 1,
row_end=start + len(sub),
source_offset=start,
metadata={
"parse_method": "excel_table",
"content_role": "table",
"content_kind": "table",
"section_path": [str(sheet_name)],
"section_title": str(sheet_name),
"table_header": headers,
"table_id": f"{sheet_name}:{start + 1}-{start + len(sub)}",
"table_row_count": len(sub),
},
)
)
return blocks
return enrich_blocks(blocks, parse_method="excel_table")
register_loader(ExcelLoader())
......@@ -4,6 +4,7 @@ import re
from typing import Any
from src.rag.loaders.base import DocumentBlock, register_loader
from src.rag.loaders.common import enrich_blocks
from src.rag.loaders.text_loader import read_text
from src.rag.utils import normalize_text
......@@ -32,7 +33,10 @@ def parse_markdown_text(text: str, inherited: dict[str, Any] | None = None) -> l
block_type=block_type,
title_path=" / ".join(headings),
source_offset=offset,
metadata=dict(inherited),
metadata={
**dict(inherited),
"heading_level": len(headings) if headings else None,
},
)
)
offset += 1
......@@ -48,7 +52,7 @@ def parse_markdown_text(text: str, inherited: dict[str, Any] | None = None) -> l
else:
buffer.append(line)
flush()
return blocks
return enrich_blocks(blocks, parse_method="markdown")
def _looks_like_markdown_table(text: str) -> bool:
......
......@@ -3,6 +3,7 @@ from __future__ import annotations
import re
from src.rag.loaders.base import DocumentBlock, register_loader
from src.rag.loaders.common import enrich_blocks
from src.rag.utils import normalize_text
......@@ -11,39 +12,80 @@ class DocxLoader:
def load(self, path: str) -> list[DocumentBlock]:
import docx
from docx.table import Table
from docx.text.paragraph import Paragraph
doc = docx.Document(path)
blocks: list[DocumentBlock] = []
headings: list[str] = []
offset = 0
for para in doc.paragraphs:
text = para.text.strip()
def iter_body_items():
for child in doc.element.body.iterchildren():
if child.tag.endswith("}p"):
yield Paragraph(child, doc)
elif child.tag.endswith("}tbl"):
yield Table(child, doc)
for item in iter_body_items():
if isinstance(item, Table):
rows = _docx_table_rows(item)
if rows:
blocks.append(
DocumentBlock(
text="\n".join(rows),
block_type="table",
title_path=" / ".join(headings),
source_offset=offset,
metadata={
"parse_method": "docx_table",
"content_role": "table",
"content_kind": "table",
"table_id": f"docx_table_{offset}",
},
)
)
offset += 1
continue
text = item.text.strip()
if not text:
continue
style = (para.style.name or "").lower()
if "heading" in style or "标题" in style:
style = (item.style.name or "").lower()
if "heading" in style or "title" in style or "biaoti" in style:
level_match = re.search(r"(\d+)", style)
level = int(level_match.group(1)) if level_match else 1
headings[:] = headings[: level - 1]
headings.append(text)
continue
blocks.append(DocumentBlock(text=text, title_path=" / ".join(headings), source_offset=offset))
blocks.append(
DocumentBlock(
text=text,
title_path=" / ".join(headings),
source_offset=offset,
metadata={
"parse_method": "docx_paragraph",
"content_role": "body",
"content_kind": "text",
},
)
)
offset += 1
for table_index, table in enumerate(doc.tables):
rows = []
for row in table.rows:
cells = [cell.text.strip().replace("\n", " ") for cell in row.cells]
if any(cells):
rows.append("| " + " | ".join(cells) + " |")
if rows:
if len(rows) == 1:
rows.insert(1, "| --- |")
else:
width = rows[0].count("|") - 1
rows.insert(1, "| " + " | ".join(["---"] * width) + " |")
blocks.append(DocumentBlock(text="\n".join(rows), block_type="table", title_path=" / ".join(headings), source_offset=table_index))
return blocks
return enrich_blocks(blocks, parse_method="docx")
def _docx_table_rows(table) -> list[str]:
rows = []
for row in table.rows:
cells = [cell.text.strip().replace("\n", " ") for cell in row.cells]
if any(cells):
rows.append("| " + " | ".join(cells) + " |")
if not rows:
return []
width = max(rows[0].count("|") - 1, 1)
rows.insert(1, "| " + " | ".join(["---"] * width) + " |")
return rows
class PptxLoader:
......@@ -61,15 +103,29 @@ class PptxLoader:
texts.append(shape.text.strip())
if texts:
title = texts[0].splitlines()[0][:120]
blocks.append(DocumentBlock(text=normalize_text("\n\n".join(texts)), title_path=title, slide_number=slide_index, source_offset=slide_index))
return blocks
blocks.append(
DocumentBlock(
text=normalize_text("\n\n".join(texts)),
title_path=title,
slide_number=slide_index,
source_offset=slide_index,
metadata={
"parse_method": "pptx_slide",
"content_role": "body",
"content_kind": "slide_text",
"section_path": [title],
"section_title": title,
},
)
)
return enrich_blocks(blocks, parse_method="pptx")
class LegacyPptLoader:
extensions = {".ppt"}
def load(self, path: str) -> list[DocumentBlock]:
raise RuntimeError("暂不直接解析 .ppt,请转换为 .pptx 后上传。")
raise RuntimeError("Direct .ppt parsing is not supported. Please convert it to .pptx before uploading.")
register_loader(DocxLoader())
......
......@@ -6,6 +6,7 @@ from typing import Any
from src.rag.config import RAG_PDF_NUMERIC_VERIFY, RAG_SKIP_LOW_CONFIDENCE_CHUNKS
from src.rag.loaders.base import DocumentBlock, register_loader
from src.rag.loaders.common import RAG_CHUNKER_VERSION, RAG_PARSER_VERSION
from src.rag.loaders.markdown_loader import parse_markdown_text
from src.rag.utils import normalize_text
......@@ -27,7 +28,9 @@ class PdfLoader:
blocks = _drop_table_text_duplicates(blocks)
if not blocks:
raise RuntimeError("PDF 未提取到可索引文本。当前 RAG 不再内置 OCR,请先转换为文字版 PDF 后重新索引。")
_attach_loader_metadata(blocks)
# Sort blocks by page_number and vertical position (y0)
blocks.sort(key=lambda b: (b.page_number or 0, b.metadata.get("bbox", (0, 0, 0, 0))[1]))
......@@ -100,7 +103,7 @@ def _tables_with_pdfplumber(path: str) -> list[DocumentBlock]:
page_number=page_number,
source_offset=table_index,
row_start=1,
row_end=max(1, len(_table_rows(markdown)) - 1),
row_end=_table_data_row_count(markdown),
metadata={
"parse_method": "pdfplumber_table",
"table_markdown": True,
......@@ -147,7 +150,7 @@ def _text_with_pymupdf(path: str) -> list[DocumentBlock]:
is_in_table = False
for t_rect in table_bboxes:
intersect = b_rect.intersect(t_rect)
if intersect.get_area() > 0.5 * b_rect.get_area():
if _rect_center_inside(b_rect, t_rect) or intersect.get_area() > 0.2 * b_rect.get_area():
is_in_table = True
break
if not is_in_table:
......@@ -157,16 +160,17 @@ def _text_with_pymupdf(path: str) -> list[DocumentBlock]:
part = _clean_pdf_text(raw_text)
if not part:
continue
blocks.append(
DocumentBlock(
text=part,
block_type="paragraph",
title_path="",
page_number=page_number,
source_offset=part_index,
metadata={"parse_method": "pymupdf_text", "bbox": bbox, "page_start": page_number, "page_end": page_number},
for sub_index, sub_part in enumerate(_split_pdf_text_parts(part)):
blocks.append(
DocumentBlock(
text=sub_part,
block_type="paragraph",
title_path="",
page_number=page_number,
source_offset=part_index * 100 + sub_index,
metadata={"parse_method": "pymupdf_text", "bbox": bbox, "page_start": page_number, "page_end": page_number},
)
)
)
return blocks
......@@ -195,7 +199,7 @@ def _tables_with_pymupdf(path: str) -> list[DocumentBlock]:
page_number=page_number,
source_offset=table_index,
row_start=1,
row_end=max(1, len(_table_rows(markdown)) - 1),
row_end=_table_data_row_count(markdown),
metadata={
"parse_method": "pymupdf_table",
"table_markdown": True,
......@@ -244,18 +248,37 @@ def _clean_pdf_text(text: str) -> str:
return normalize_text("\n\n".join(cleaned_parts))
def _split_pdf_text_parts(text: str) -> list[str]:
parts = [part.strip() for part in re.split(r"\n\s*\n", text) if part.strip()]
if len(parts) <= 1:
return [text]
result: list[str] = []
buffer: list[str] = []
for part in parts:
if buffer and _detect_heading(part):
result.append(normalize_text("\n\n".join(buffer)))
buffer = [part]
else:
buffer.append(part)
if buffer:
result.append(normalize_text("\n\n".join(buffer)))
return result
def _detect_heading(text: str) -> tuple[int, str] | None:
if len(text) > 100 or "\n" in text.strip():
return None
first = text.strip()
if not first or _looks_like_table_residual(first) or first.startswith(("说明:", "注:", "备注:")):
return None
match = re.match(r"^(\d+(?:\.\d+){0,4})\s+(.{2,80})$", first)
if match:
return (match.group(1).count(".") + 1, first)
match = re.match(r"^([一二三四五六七八九十]+)、\s*(.{2,80})$", first)
if match:
return (1, first)
if len(first) <= 50 and re.search(r"(除外责任|保障范围|服务流程|产品介绍|价格|权益|条款|服务|保障|延保|安心包|补充说明)", first):
return (1, first)
if len(first) <= 36 and re.search(r"^(零售类|赠送类.*|补充说明|保障范围|服务流程|产品介绍|除外责任|.*条款)$", first):
return (2, first)
return None
......@@ -273,13 +296,28 @@ def _assign_headings(blocks: list[DocumentBlock]) -> None:
heading = _detect_heading(block.text)
if heading:
headings = _update_headings(headings, heading)
block.metadata["content_role"] = "heading"
block.metadata["heading_level"] = heading[0]
else:
inferred_heading = _infer_business_heading(block.text)
if inferred_heading:
headings = _update_headings(headings, inferred_heading)
block.metadata["inferred_section_title"] = inferred_heading[1]
block.metadata.setdefault("content_role", "body")
elif block.block_type == "table":
inferred_heading = _infer_business_heading(block.text)
if inferred_heading:
headings = _update_headings(headings, inferred_heading)
block.metadata["inferred_section_title"] = inferred_heading[1]
block.title_path = " / ".join(headings)
if headings:
block.metadata["section_title"] = headings[-1]
block.metadata["section_path"] = list(headings)
block.metadata["section_index"] = len(headings)
if block.block_type == "table":
block.metadata["content_role"] = "table"
block.metadata["table_header"] = _table_header(block.text)
block.metadata["table_id"] = f"p{block.page_number}_t{(block.metadata.get('table_index', 0)) + 1}"
if block.title_path:
block.title_path += f" / P{block.page_number} 表{(block.metadata.get('table_index', 0)) + 1}"
else:
......@@ -324,8 +362,6 @@ def _drop_table_text_duplicates(blocks: list[DocumentBlock]) -> list[DocumentBlo
def _is_inside_table_bbox(block: DocumentBlock, table_bboxes: list[Any]) -> bool:
if _detect_heading(block.text):
return False
bbox = block.metadata.get("bbox")
if not bbox:
return False
......@@ -363,11 +399,22 @@ def _table_rows(markdown: str) -> list[str]:
return [line.strip() for line in markdown.splitlines() if line.strip().startswith("|")]
def _table_data_row_count(markdown: str) -> int:
rows = _table_rows(markdown)
if len(rows) > 1 and _is_separator_row(rows[1]):
return max(1, len(rows) - 2)
return max(1, len(rows))
def _table_header(markdown: str) -> str:
rows = _table_rows(markdown)
return rows[0] if rows else ""
def _is_separator_row(row: str) -> bool:
return "---" in row.replace(" ", "").replace("|", "")
def _table_width(markdown: str) -> int:
header = _table_header(markdown)
return max(0, header.count("|") - 1)
......@@ -394,4 +441,63 @@ def _merge_table_markdown(previous: str, current: str) -> str:
return "\n".join([*previous_rows, current_rows[0], *current_rows[2:]])
def _rect_center_inside(rect: Any, container: Any) -> bool:
try:
center_x = (rect.x0 + rect.x1) / 2
center_y = (rect.y0 + rect.y1) / 2
return container.x0 <= center_x <= container.x1 and container.y0 <= center_y <= container.y1
except Exception:
return False
def _looks_like_table_residual(text: str) -> bool:
compact = re.sub(r"\s+", "", text)
if len(compact) <= 2:
return True
header_words = ("产品名称", "对应车型", "建议零售价", "活动价", "保障内容", "包含权益", "车辆类型", "保额档位", "产品价格")
if sum(1 for word in header_words if word in compact) >= 2:
return True
if compact in {"整车延保", "电池延保", "包含权益", "活动价", "保障内容"}:
return True
return False
def _infer_business_heading(text: str) -> tuple[int, str] | None:
sample = text[:800]
if "出险代步服务" in sample or "服务期1年,每年累计最多2次" in sample:
return (1, "五、出险代步服务")
if "辅助驾驶无忧" in sample or ("保额档位" in sample and "保障内容" in sample):
return (1, "七、辅助驾驶无忧服务")
return None
def _attach_loader_metadata(blocks: list[DocumentBlock]) -> None:
page_numbers = [block.page_number for block in blocks if block.page_number is not None]
parse_methods = sorted({str(block.metadata.get("parse_method")) for block in blocks if block.metadata.get("parse_method")})
quality = _text_quality("\n".join(block.text for block in blocks))
page_count = max(page_numbers) if page_numbers else None
for block in blocks:
block.metadata.setdefault("parser_version", RAG_PARSER_VERSION)
block.metadata.setdefault("chunker_version", RAG_CHUNKER_VERSION)
block.metadata.setdefault("parse_status", "ok")
block.metadata.setdefault("parse_quality", "normal" if quality == "ok" else quality)
if page_count:
block.metadata.setdefault("source_page_count", page_count)
if parse_methods:
block.metadata.setdefault("document_parse_methods", parse_methods)
block.metadata.setdefault("text_quality", quality)
def _text_quality(text: str) -> str:
if not text:
return "empty"
bad_chars = text.count("\ufffd")
cjk_chars = len(re.findall(r"[\u4e00-\u9fff]", text))
if bad_chars / max(1, len(text)) > 0.02:
return "suspect_encoding"
if cjk_chars == 0 and re.search(r"[A-Za-z]{20,}", text):
return "low_cjk"
return "ok"
register_loader(PdfLoader())
......@@ -3,6 +3,7 @@ from __future__ import annotations
import re
from src.rag.loaders.base import DocumentBlock, register_loader
from src.rag.loaders.common import enrich_blocks
from src.rag.utils import normalize_text
......@@ -20,7 +21,24 @@ def read_text(path: str) -> str:
def split_plain_blocks(text: str, title_path: str = "") -> list[DocumentBlock]:
text = normalize_text(text)
parts = [p.strip() for p in re.split(r"\n\s*\n", text) if p.strip()]
return [DocumentBlock(text=part, title_path=title_path, source_offset=idx) for idx, part in enumerate(parts)]
blocks: list[DocumentBlock] = []
cursor = 0
for idx, part in enumerate(parts):
start = text.find(part, cursor)
end = start + len(part) if start >= 0 else None
cursor = end or cursor
blocks.append(
DocumentBlock(
text=part,
title_path=title_path,
source_offset=idx,
metadata={
"char_start": start if start >= 0 else None,
"char_end": end,
},
)
)
return enrich_blocks(blocks, parse_method="plain_text")
class TextLoader:
......
"""
业务元数据规则提取模块。
通过配置硬编码的规则(如关键词、品牌名称),为切块后的文本打上领域相关的意图、分类和品牌标签。
这些标签后续会被附加至向量数据库(Payload),并在搜索阶段进行软性或硬性过滤,提升垂直知识库查准率。
"""
from __future__ import annotations
import re
......@@ -5,18 +10,21 @@ from dataclasses import dataclass, field
from typing import Any
# 汽车后市场支持的常见品牌字典,一旦文本内出现这些字符串则会被关联对应品牌
KNOWN_BRANDS = [
"问界", "享界", "智界", "尊界", "尚界", "岚图", "零跑", "理想", "小鹏", "比亚迪",
"奔驰", "宝马", "奥迪", "大众", "本田", "日产", "吉利", "哪吒", "长城", "长安",
"奇瑞", "埃安", "广汽传祺", "极氪", "阿维塔", "深蓝", "腾势", "方程豹", "仰望",
]
# 按售后核心业务场景分类的特征词语
BUSINESS_KEYWORDS = {
"轻改类": ["太阳膜", "漆面保护膜", "车衣", "天窗冰甲", "底盘护板", "电动踏板", "脚垫", "小桌板"],
"权益类": ["延保", "安心包", "轮胎", "电池延保", "会员权益", "原厂权益", "广联权益", "质保", "辅助驾驶无忧", "赔付", "补偿", "享权", "保额"],
"二手车类": ["二手车", "置换", "收车", "评估"],
}
# 文本块所处的内容格式或文档体裁意图分类(如产品介绍、话术指导等)
PAGE_TYPE_KEYWORDS = {
"product": ["产品", "保障范围", "价格", "指导价", "参数", "套餐", "权益", "保额", "限额"],
"script": ["话术", "怎么回", "怎么说", "异议", "客户说", "促单", "嫌贵"],
......@@ -29,24 +37,37 @@ PAGE_TYPE_KEYWORDS = {
@dataclass
class BusinessMetadata:
intent_type: str | None = None
page_type: str | None = None
brand: str | None = None
business_category: str | None = None
metadata_json: dict[str, Any] = field(default_factory=dict)
"""存放通过规则提取出的文本业务元数据结果的数据类。"""
intent_type: str | None = None # 检索意图类型(例如 product,script)
page_type: str | None = None # 页面所属类型(文档类型)
brand: str | None = None # 主要提取到的唯一汽车品牌
business_category: str | None = None # 所属一级业务分类(如轻改、权益)
metadata_json: dict[str, Any] = field(default_factory=dict) # 其他散落附加的字段字典
def extract_metadata(text: str, title_path: str = "", inherited: dict[str, Any] | None = None) -> BusinessMetadata:
"""
通过正则或关键词匹配策略,自动推断并提取给定文本的业务元数据。
:param text: 要分析的纯文本内容。
:param title_path: 该文本所处的层级标题路径(辅助匹配)。
:param inherited: 继承自上层或上游阶段的其他预存元数据信息。
:return: 一个填充好的 BusinessMetadata 对象。
"""
# 合并标题和前2000个字符用于抽样分析(避免段落过长无意义搜索)
sample = f"{title_path}\n{text[:2000]}"
meta = BusinessMetadata(metadata_json=dict(inherited or {}))
# 1. 尝试匹配文档提及的汽车品牌
matched_brands = [brand for brand in KNOWN_BRANDS if brand in sample]
if len(matched_brands) == 1:
meta.brand = matched_brands[0]
if matched_brands:
meta.metadata_json["brands"] = matched_brands
# “界”字辈归类到鸿蒙智行,其他认为是通用品牌
meta.metadata_json["brand_series"] = "鸿蒙智行" if any(brand in {"问界", "享界", "智界", "尊界", "尚界"} for brand in matched_brands) else "通用品牌"
# 2. 尝试从文本命中具体的业务种类(比如太阳膜、延保等)
for category, words in BUSINESS_KEYWORDS.items():
hit = next((word for word in words if word in sample), None)
if hit:
......@@ -54,24 +75,31 @@ def extract_metadata(text: str, title_path: str = "", inherited: dict[str, Any]
meta.metadata_json["sub_business"] = hit
break
# 3. 推断页面所属的主题类型或解答意图
page_types: list[str] = []
for page_type, words in PAGE_TYPE_KEYWORDS.items():
if any(word in sample for word in words):
page_types.append(page_type)
if page_types:
# 如果命中多种,粗略以第一种为准作为最高优先级
meta.page_type = page_types[0]
meta.intent_type = page_types[0]
meta.metadata_json["page_types"] = page_types
# 4. 根据特定关键字进一步精细化覆盖意图
if re.search(r"能不能|可不可以|违规|合规|红线|保险", sample):
# 如询问政策合规红线
meta.intent_type = "compliance"
meta.page_type = "policy"
meta.metadata_json["policy_type"] = "合规红线"
elif "免责" in sample:
# 涉及责任推卸和范围排除的声明
meta.metadata_json["policy_type"] = "免责条款"
elif "价格" in sample or "指导价" in sample:
# 有关购买支出的策略
meta.metadata_json["policy_type"] = "价格政策"
elif "话术" in sample or "异议" in sample:
# 销售或客服的话术引导
meta.metadata_json["script_type"] = "异议处理"
if "嫌贵" in sample or "太贵" in sample:
meta.metadata_json["objection_type"] = "价格异议"
......
"""
重排(Rerank)模块。
在初筛出的若干粗排 Chunk 后,通过调用阿里 DashScope 的 Reranker API,
对(Query + Chunk 文本)进行深层次的语义匹配与再打分,以提升靠前结果的精度。
"""
from __future__ import annotations
import logging
import os
from typing import Any
from src.database.models import RagChunk
from src.rag.config import RAG_RERANKER_ENABLED, RAG_RERANKER_MODEL, RAG_RERANKER_TOP_K
from dotenv import load_dotenv
from src.database.models import RagChunk
from src.rag.config import RAG_RERANKER_MODEL, RAG_RERANKER_TOP_K
logger = logging.getLogger(__name__)
def rerank_chunks(query: str, chunks: list[RagChunk]) -> list[RagChunk]:
if not RAG_RERANKER_ENABLED or len(chunks) <= 1:
"""
利用重排大模型重新评估给定片段与查询的相关性。
1. 只对传入候选序列中的前 RAG_RERANKER_TOP_K 个(默认如 20 个)进行重新打分;
2. 后续未送入 Reranker 的分片保持原有的排名相对位置,或直接得分置底。
:param query: 用户的查询问题
:param chunks: 粗排挑选出的备选 RagChunk 对象列表
:return: 按 Reranker 重打分结果降序排列的新 Chunk 列表
"""
# 如果候选结果少于等于 1 个,无需耗费资源重排,直接返回
if len(chunks) <= 1:
return chunks
try:
load_dotenv()
import dashscope
# 初始化阿里云 API Key
dashscope.api_key = os.getenv("DASHSCOPE_API_KEY")
# 截取头部列表以减小 Reranker API 消耗,其它排在后面的直接视为低相关度
head = chunks[:RAG_RERANKER_TOP_K]
# 拼接片段的层级标题和文本内容,供模型评估
documents = [f"{chunk.title_path or ''}\n{chunk.content}" for chunk in head]
# 同步调用 DashScope 的 Reranker 模型
resp = dashscope.TextReRank.call(
model=RAG_RERANKER_MODEL,
query=query,
documents=documents,
return_documents=False
return_documents=False,
)
if resp.status_code != 200:
logger.warning(f"[RAG] 阿里云百炼 Reranker 返回错误 (status={resp.status_code}): {resp.message}")
# 校验请求结果
if getattr(resp, "status_code", None) != 200:
logger.warning(
"[RAG] reranker returned error: model=%s status=%s message=%s",
RAG_RERANKER_MODEL,
getattr(resp, "status_code", None),
getattr(resp, "message", ""),
)
return chunks
results = resp.output.results
scored = []
scored_indices = set()
# 解析模型返回的结果列表
results = getattr(getattr(resp, "output", None), "results", []) or []
scored: list[tuple[RagChunk, float]] = []
scored_indices: set[int] = set()
for res in results:
if res.index < 0 or res.index >= len(head):
continue
chunk = head[res.index]
# 从模型返回中取出相关度分数,通常介于 0 到 1 或更大的连续空间
chunk.rerank_score = float(res.relevance_score)
scored.append((chunk, chunk.rerank_score))
scored_indices.add(res.index)
# 补充模型由于某些原因没有返回打分的那些 head 内 Chunk(给最低分 -1.0)
for idx, chunk in enumerate(head):
if idx not in scored_indices:
chunk.rerank_score = -1.0
scored.append((chunk, -1.0))
# 补充没有被送入 Reranker 的后续 Chunk(给最低分 -1.0)
for chunk in chunks[RAG_RERANKER_TOP_K:]:
chunk.rerank_score = -1.0
scored.append((chunk, -1.0))
# 按 Rerank 后的得分重新降序排列并返回
return [chunk for chunk, _ in sorted(scored, key=lambda item: item[1], reverse=True)]
except Exception as exc:
logger.warning("[RAG] reranker 不可用,保留 Qdrant 排序: %s", exc)
logger.warning(
"[RAG] reranker unavailable, keeping original retrieval order: model=%s error=%s",
RAG_RERANKER_MODEL,
exc,
exc_info=True,
)
return chunks
from __future__ import annotations
"""
RAG 检索与回答生成核心逻辑模块。
包含用户意图分类、查询改写(Query Rewrite)、多路召回(Hybrid Retrieval)、
精排(Rerank)策略,以及调用 LLM 结合上下文生成最终回答。
"""
from __future__ import annotations
import asyncio
import json
......@@ -20,11 +25,13 @@ from src.utils.llm_tracker import get_llm_model
logger = logging.getLogger(__name__)
# 当召回片段为空或根据模型判断资料确实不足时的标准兜底回复
FALLBACK_ANSWER = "我还没有学到相关知识,或资料不足以支持准确回答。请补充相关文档后再试。"
@dataclass
class IntentResult:
"""保存 LLM 识别出的用户查询意图与相关业务标签结果。"""
intent: str
confidence: float = 0.8
brand: str | None = None
......@@ -37,10 +44,17 @@ class IntentResult:
async def classify_intent(query: str, history: list[dict[str, Any]] | None = None) -> IntentResult:
prompt = f"""浣犳槸姹借溅鍚庡競鍦虹煡璇嗗簱鐨勬剰鍥捐瘑鍒櫒銆傚彧杈撳嚭 JSON锛屼笉瑕佽В閲娿€?鍙€?intent: product, script, policy, compliance, procedure, troubleshooting, comparison, unsupported, general_knowledge, chitchat銆?鍏佽澶嶅悎鎰忓浘锛宨ntents 鏄暟缁勩€備緥濡傗€滀环鏍煎拰鍏嶈矗鈥濆簲涓?["product", "policy"]銆?涓嶈鍚戠敤鎴疯拷闂緞娓咃紝need_clarification 蹇呴』涓?false锛涗俊鎭笉瓒虫椂鍚庣画闂瓟閾捐矾浼氭牴鎹彫鍥炶祫鏂欏洖绛旀垨鍏滃簳銆?
闂: {query}
鍘嗗彶: {json.dumps(history or [], ensure_ascii=False)[:1200]}
杈撳嚭瀛楁: intent, intents, confidence, brand, business_category, sub_business, need_clarification, clarification_question, unsupported_reason
"""
通过大模型对用户当前 Query 及其对话历史进行意图分类,
提取出诸如:提问意图、汽车品牌、业务分类等信息,以此决定后续的检索方向和过滤条件。
"""
prompt = f"""你是汽车后市场知识库的意图识别器。只输出 JSON,不要解释。
可选 intent: product, script, policy, compliance, procedure, troubleshooting, comparison, unsupported, general_knowledge, chitchat。
允许复合意图,intents 是数组。例如“价格和免责”应为 ["product", "policy"]。
不要向用户追问澄清,need_clarification 必须为 false;信息不足时后续问答链路会根据召回资料回答或兜底。
问题: {query}
历史: {json.dumps(history or [], ensure_ascii=False)[:1200]}
输出字段: intent, intents, confidence, brand, business_category, sub_business, need_clarification, clarification_question, unsupported_reason
"""
content = await chat_once(RAG_INTENT_MODEL, prompt)
......@@ -72,6 +86,10 @@ async def classify_intent(query: str, history: list[dict[str, Any]] | None = Non
@dataclass
class QueryPlan:
"""
封装了针对单次查询所衍生出的多种“改写”形式的查询计划,
用于执行多路并发的独立查询,尽可能全面地召回相关数据块。
"""
direct_query: str
retrospective_query: str | None = None
sub_queries: list[str] = field(default_factory=list)
......@@ -107,6 +125,11 @@ class QueryPlan:
async def build_query_plan(query: str, intent: IntentResult, history: list[dict[str, Any]] | None) -> QueryPlan:
"""
构造检索查询计划。
会先利用规则进行预处理(如切割、补充历史指代词);如果规则无法满足特定场景,则请求 LLM
进行复杂的指代消解或同义重写(Query Rewrite)。
"""
plan = _rule_plan(query, intent, history)
if not _should_call_rewrite_model(query, history, plan):
logger.info("[RAG] 采用规则改写,未调用 LLM: %s", plan.to_dict())
......@@ -168,6 +191,9 @@ def _clean_list(value: Any) -> list[str]:
@dataclass
class Candidate:
"""
从向量库初次召回的单一候选分块(未经过详细展开与精排的原始 Hit)。
"""
child_chunk_id: str
parent_chunk_id: str | None
file_id: str
......@@ -182,6 +208,11 @@ class Candidate:
def rerank(candidates: list[Candidate]) -> list[Candidate]:
"""
基于多个召回支路(如 direct、sub_query)返回的 Candidates 进行初步去重合并打分:
按所属的父块或自身进行分组,并通过对向量相似度、稀疏检索分数以及各种业务权重
进行线性加权,得出初排综合得分 final_score,然后进行降序排列。
"""
grouped: dict[str, Candidate] = {}
for candidate in candidates:
key = candidate.parent_chunk_id or candidate.child_chunk_id
......@@ -214,6 +245,9 @@ def rerank(candidates: list[Candidate]) -> list[Candidate]:
from src.rag.llm import chat_once, chat_stream
async def generate_answer(query: str, intent: IntentResult, chunks: list[RagChunk], history: list[dict[str, Any]] | None = None) -> str:
"""
结合召回且已精排截断的上下片段资料,组装提示词并调用大语言模型,生成一次性完整的回答(非流式)。
"""
if not chunks:
return FALLBACK_ANSWER
context = "\n\n".join(_format_chunk(i + 1, chunk) for i, chunk in enumerate(chunks))
......@@ -236,6 +270,9 @@ async def generate_answer(query: str, intent: IntentResult, chunks: list[RagChun
async def generate_answer_stream(query: str, intent: IntentResult, chunks: list[RagChunk], history: list[dict[str, Any]] | None = None):
"""
同 generate_answer,但调用的是流式生成接口,产生逐步输出的 yield(供 SSE 接口推送前端)。
"""
if not chunks:
yield {"type": "answer_delta", "content": FALLBACK_ANSWER}
return
......@@ -300,6 +337,15 @@ def build_filters(intent: IntentResult, user_context: dict[str, Any] | None = No
async def retrieve(query: str, intent: IntentResult, history: list[dict[str, Any]] | None = None, user_context: dict[str, Any] | None = None) -> dict[str, Any]:
"""
执行 RAG 完整的检索管道 (Retrieval Pipeline):
1. 构建改写和扩展计划
2. 多路并发在向量数据库中进行 Hybrid 检索
3. 合并打分去重(粗排)
4. 提取对应的完整父级分段,并做邻居拼接补齐上下文
5. 调用深度 Reranker 模型进行最终精排
6. 根据 Token 预算截断最后送入 LLM 的文本序列
"""
query_plan = await build_query_plan(query, intent, history)
filters, soft_boosts = build_filters(intent, user_context)
logger.info("[RAG] 最终检索过滤条件: filters=%s, soft_boosts=%s", filters, soft_boosts)
......
"""
RAG HTTP 路由配置与接口暴露模块。
向外部系统或者前端提供了诸如:文件上传、解析预览、建库索引、数据检索(包括 SSE 流式输出)等能力的 API 接口。
"""
import asyncio
import json
import logging
......@@ -16,27 +20,41 @@ router = APIRouter()
@router.get("/rag/health")
async def rag_health():
"""探针接口:用于检查 RAG 子系统及底层向量数据库的健康状态和基础统计信息。"""
data = await service.stats()
return {"status": "ok", **data}
@router.get("/rag/files")
async def rag_files(page: int = 1, page_size: int = 20, search: str = ""):
"""分页获取知识库中已经上传或构建索引的文档列表。"""
return await service.list_files(page, page_size, search)
@router.post("/rag/upload/init")
async def rag_upload_init(payload: RagUploadInitRequest):
"""
文件上传初始化步骤:
客户端发送准备上传的文件信息,服务端在数据库生成待传记录 ID,并做重复判断校验。
"""
return await service.init_upload([f.name for f in payload.files])
@router.post("/rag/upload/{file_id}")
async def rag_upload(file_id: str, file: UploadFile = File(...)):
"""
执行文件流的实体上传操作:
将上传的文件字节流保存至本地磁盘,更新对应的数据记录状态。
"""
return await service.save_upload(file_id, file)
@router.post("/rag/preview_parse")
async def rag_preview_parse(data: dict = Body(...)):
"""
后台调试及预览接口:
输入本地文件路径,模拟文档解析及切块的执行过程,并直接返回切分效果给前端预览,并不存入数据库。
"""
path = data.get("path")
if not path:
raise HTTPException(status_code=400, detail="path is required")
......@@ -45,6 +63,10 @@ async def rag_preview_parse(data: dict = Body(...)):
@router.delete("/rag/files/{file_id}")
async def rag_delete_file(file_id: str):
"""
删除知识库指定的单个文件及关联物理存储:
必须处于非索引中状态;物理删除文件并调用底层销毁相关向量。
"""
from src.database.models import RagFile
from src.database.session import AsyncSessionLocal
......@@ -55,6 +77,7 @@ async def rag_delete_file(file_id: str):
if db_file.status in ["Indexed", "Indexing"]:
raise HTTPException(status_code=400, detail="请先删除索引再删除文件")
# 物理删除原始文档文件
if os.path.exists(db_file.source_path):
os.remove(db_file.source_path)
db_file.status = "Deleted"
......@@ -66,6 +89,7 @@ async def rag_delete_file(file_id: str):
@router.post("/rag/files/batch_delete")
async def rag_batch_delete(data: dict = Body(...)):
"""批量删除知识库文件。"""
ids = data.get("ids", [])
errors = []
for file_id in ids:
......@@ -77,7 +101,11 @@ async def rag_batch_delete(data: dict = Body(...)):
@router.post("/rag/index/{file_id}")
async def rag_index(file_id: str, background_tasks: BackgroundTasks):
async def rag_index(file_id: str):
"""
发起单文件的索引构建任务:
将实际费时的解析、切块、向量化写入等放入 asyncio task 异步执行。
"""
from src.database.models import RagFile
from src.database.session import AsyncSessionLocal
async with AsyncSessionLocal() as session:
......@@ -87,52 +115,65 @@ async def rag_index(file_id: str, background_tasks: BackgroundTasks):
if db_file.status == "Indexing":
return {"status": "already indexing", "file_id": file_id}
background_tasks.add_task(service.index_file, file_id)
asyncio.create_task(service.index_file(file_id))
return {"status": "index started", "file_id": file_id}
@router.post("/rag/batch_index")
async def rag_batch_index(background_tasks: BackgroundTasks, data: dict = Body(...)):
async def rag_batch_index(data: dict = Body(...)):
"""批量对未进行或已失效的文件触发索引构建任务。"""
ids = data.get("ids", [])
from src.database.models import RagFile
from src.database.session import AsyncSessionLocal
count = 0
async with AsyncSessionLocal() as session:
for file_id in ids:
db_file = await session.get(RagFile, file_id)
if db_file and db_file.status != "Indexing":
background_tasks.add_task(service.index_file, file_id)
return {"status": "batch index started", "count": len(ids)}
asyncio.create_task(service.index_file(file_id))
count += 1
return {"status": "batch index started", "count": count}
@router.delete("/rag/index/{file_id}")
async def rag_delete_index(file_id: str, force: bool = False):
"""单独删除某文件的索引数据及向量库关联(但保留文件实体不变)。"""
return await service.delete_index(file_id, force=force)
@router.post("/rag/rebuild_bm25")
async def rag_rebuild_bm25():
"""重建 Sparse Vector(BM25类似效果)的独立管理接口(当算法变更或库迁移时使用)。"""
count = await service.rebuild_bm25_from_db()
return {"status": "success", "bm25_docs": count}
@router.get("/rag/chunks/{file_id}")
async def rag_chunks(file_id: str):
"""后台工具接口:读取并展示某个文件切分产生的所有子区块。"""
return await service.get_chunks(file_id)
@router.get("/rag/chunk/{chunk_id}")
async def rag_chunk(chunk_id: str):
"""后台工具接口:直接查看特定分块片段详情。"""
return await service.get_chunk(chunk_id)
@router.post("/rag/query/json")
async def rag_query_json(payload: RagQueryRequest):
"""
发起单次知识检索与生成请求(非流式接口)。
返回一个完整的 JSON 响应(包含生成的回答、引用来源等),适用于不需要流式打印的场景。
"""
return await service.query_json(payload)
@router.post("/rag/query")
async def rag_query(payload: RagQueryRequest):
"""
发起知识库检索以及大模型作答请求,这是 RAG 前端主要的问答聊天接口。
结果基于 Server-Sent Events (SSE) 方式实现流式输出(逐字吐出)。
"""
async def events():
yield "data: [INIT]\n\n"
try:
......@@ -157,9 +198,60 @@ async def rag_query(payload: RagQueryRequest):
@router.post("/rag/clear_history")
async def rag_clear_history(data: dict = Body(default={})):
"""清除给定 Session 相关的 RAG 系统对话历史。"""
return await service.clear_history(data.get("sessionId"))
@router.get("/rag/stats")
async def rag_stats():
"""返回 RAG 知识库大盘统计概况(文件数、索引数、片段数)。"""
return await service.stats()
@router.post("/rag/files/batch_download")
async def rag_batch_download(data: dict = Body(...)):
"""批量下载文件。如果是单个文件直接返回,多个文件打包为zip。"""
ids = data.get("ids", [])
if not ids:
raise HTTPException(status_code=400, detail="未提供文件ID")
from src.database.models import RagFile
from src.database.session import AsyncSessionLocal
files = []
async with AsyncSessionLocal() as session:
for file_id in ids:
db_file = await session.get(RagFile, file_id)
if db_file and os.path.exists(db_file.source_path):
files.append(db_file)
if not files:
raise HTTPException(status_code=404, detail="未找到可下载的文件")
import urllib.parse
if len(files) == 1:
# 单个文件直接下载
from fastapi.responses import FileResponse
file = files[0]
filename = urllib.parse.quote(file.name)
return FileResponse(
path=file.source_path,
filename=file.name,
headers={"Content-Disposition": f"attachment; filename*=utf-8''{filename}"}
)
else:
# 多个文件打包成zip
import io
import zipfile
from fastapi.responses import StreamingResponse
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:
for file in files:
zip_file.write(file.source_path, arcname=file.name)
zip_buffer.seek(0)
return StreamingResponse(
zip_buffer,
media_type="application/zip",
headers={"Content-Disposition": "attachment; filename*=utf-8''batch_download.zip"}
)
"""
RAG 数据库模式(Schema)同步工具模块。
用于管理 RAG 系统在数据库建表时的逻辑控制。
"""
import logging
logger = logging.getLogger(__name__)
# 全局标记,标识是否已经执行过同步逻辑
_synced = False
async def ensure_rag_schema() -> None:
"""RAG 轻量版不再在启动时自动扩表。
当前项目没有 migration 框架,Base.metadata.create_all 负责新库建表;
旧库的删表/删字段通过 scripts/rag_slim/drop_legacy_rag_tables.sql 手动执行。
当前项目没有 migration(数据库迁移)框架,Base.metadata.create_all 仅负责新库建表;
旧库的删表或删除字段等操作,需通过 scripts/rag_slim/drop_legacy_rag_tables.sql 手动执行。
该函数会在首次调用时打印提示,并保证不会重复打印。
"""
global _synced
if not _synced:
......
"""
RAG 模块中所有与外部接口通信的 Pydantic 数据模型(Schemas)定义。
这些模型主要用于 FastAPI 路由中的请求体验证和参数接收。
"""
from typing import Any
from pydantic import BaseModel, Field
class RagUploadInitItem(BaseModel):
name: str
"""
RAG 上传初始化请求中的单个文件项
"""
name: str # 待上传的文件名称
class RagUploadInitRequest(BaseModel):
files: list[RagUploadInitItem]
"""
RAG 上传初始化请求参数
"""
files: list[RagUploadInitItem] # 准备上传的文件列表
class RagQueryRequest(BaseModel):
query: str
history: list[dict[str, Any]] = Field(default_factory=list)
sessionId: str | None = None
userId: str | None = None
userContext: dict[str, Any] = Field(default_factory=dict)
"""
RAG 问答查询的请求参数
"""
query: str # 用户输入的查询问题文本
history: list[dict[str, Any]] = Field(default_factory=list) # 历史对话记录,格式为 {"role": "user/assistant", "content": "..."}
sessionId: str | None = None # 会话 ID,用于关联上下文和保存聊天记录
userId: str | None = None # 用户 ID(可选)
userContext: dict[str, Any] = Field(default_factory=dict) # 用户的额外业务上下文(如当前品牌、车型等)
class RagImportReferenceRequest(BaseModel):
paths: list[str] = Field(default_factory=list)
index: bool = True
rebuild: bool = True
"""
后台导入参考资料的请求参数(用于自动化导入目录下的文件)
"""
paths: list[str] = Field(default_factory=list) # 指定需要导入的相对或绝对路径列表
index: bool = True # 导入后是否立刻触发向量化索引任务
rebuild: bool = True # 如果索引已存在,是否强制重新构建
"""
稀疏向量计算模块 (Sparse Embedding)
利用本地词频统计与 TF-IDF/BM25 相似的思路,将文本转为高维稀疏向量,
用于在使用 Qdrant 时支持基于词汇的精确关键词匹配检索 (Hybrid Search)。
"""
from __future__ import annotations
import hashlib
......@@ -9,34 +14,60 @@ from dataclasses import dataclass
@dataclass(frozen=True)
class SparseTextVector:
indices: list[int]
values: list[float]
"""表示稀疏文本向量的数据类,保存非零元素的索引和权重。"""
indices: list[int] # 非零特征维度的索引
values: list[float] # 对应的特征权重
def build_sparse_vector(text: str, dims: int = 2_000_000) -> SparseTextVector:
"""
构建文本的稀疏向量。
通过对文本分词并统计词频,结合哈希技巧映射到高维空间,
然后通过对数缩放词频并执行 L2 归一化计算每个词的特征值。
"""
tokens = _tokenize(text)
counts = Counter(tokens)
weighted: dict[int, float] = {}
# 将每个词的特征根据其哈希值映射到 0~dims 的固定空间
for token, count in counts.items():
idx = _stable_hash(token) % dims
# 简单采用 TF 的对数变形: 1.0 + ln(count),以抑制高频词占据绝对权重
weighted[idx] = weighted.get(idx, 0.0) + 1.0 + math.log(count)
# 计算归一化常数 (L2 Norm)
norm = math.sqrt(sum(value * value for value in weighted.values())) or 1.0
# 过滤零值,并返回归一化后的按索引排序的稀疏向量
items = sorted((idx, value / norm) for idx, value in weighted.items() if value)
return SparseTextVector(indices=[idx for idx, _ in items], values=[value for _, value in items])
def _tokenize(text: str) -> list[str]:
"""
对输入文本进行多种方式混合分词:
1. 尝试使用 jieba 进行中文分词;
2. 生成无空格字符串的所有相邻字母/数字 2-gram(增加子字符串命中率);
3. 提取其中包含的连续英文字符和数字序列(增强型号/代码查询的稳定性)。
"""
try:
import jieba
tokens = [token.strip().lower() for token in jieba.cut(text) if token.strip()]
except Exception:
tokens = []
# 移去空白符并转换为小写
compact = re.sub(r"\s+", "", text.lower())
# 增加 2-gram 组合
tokens.extend(compact[i : i + 2] for i in range(max(0, len(compact) - 1)))
# 提取英文字母、数字及其相连的常见分隔符串,增强英文检索鲁棒性
tokens.extend(re.findall(r"[A-Za-z0-9][A-Za-z0-9._-]*", text.lower()))
return [token for token in tokens if token]
def _stable_hash(text: str) -> int:
"""采用 blake2b 算法对字符串生成稳定的哈希整数。"""
return int.from_bytes(hashlib.blake2b(text.encode("utf-8", errors="ignore"), digest_size=8).digest(), "big")
......@@ -13,6 +13,12 @@ logger = logging.getLogger(__name__)
class QdrantHybridStore:
"""
Qdrant 混合检索库的封装实现。
支持稠密向量(Dense Vector,通过 Embedding 模型生成)和稀疏向量
(Sparse Vector,通过基于词汇的统计生成)的混合检索 (Hybrid Search)。
"""
def __init__(self) -> None:
self.client = None
self.available = False
......@@ -26,6 +32,7 @@ class QdrantHybridStore:
logger.warning("[RAG] Qdrant client 初始化失败,检索不可用: %s", exc)
def health(self) -> dict[str, Any]:
"""获取 Qdrant 数据库当前的健康状态及集合配置。"""
return {
"qdrant_available": self.available,
"qdrant_url": QDRANT_URL,
......@@ -36,6 +43,12 @@ class QdrantHybridStore:
}
def ensure_collection(self, vector_size: int) -> None:
"""
确保对应的 Qdrant Collection 已创建。
如果目标集合不存在,则自动创建一个同时支持 Dense 和 Sparse 两种 Vector 检索的集合,
并为关键属性建立 Payload(载荷)关键词索引以加速条件过滤。
"""
if not self.available or self.client is None:
raise RuntimeError("Qdrant 不可用,无法写入检索索引")
from qdrant_client.models import Distance, PayloadSchemaType, SparseVectorParams, VectorParams
......@@ -52,13 +65,37 @@ class QdrantHybridStore:
else:
self.collection_dim = self._read_collection_dim() or vector_size
for field in ["status", "file_id", "brand", "business_category", "page_type", "intent_type", "parse_status"]:
keyword_fields = [
"status",
"file_id",
"document_id",
"brand",
"brands",
"brand_series",
"business_category",
"sub_business",
"page_type",
"intent_type",
"content_kind",
"section_title",
"parse_status",
"parse_quality",
"parser_version",
"chunker_version",
]
for field in keyword_fields:
try:
self.client.create_payload_index(QDRANT_COLLECTION, field_name=field, field_schema=PayloadSchemaType.KEYWORD)
except Exception:
pass
def upsert_children(self, chunks: list[RagChunkData], batch_size: int = 128) -> int:
"""
将文本分块及其元数据批量插入/更新至 Qdrant。
会在写入前先调用 Embedding 接口生成 Dense Vector,
并基于词频构建 Sparse Vector,最后封装备用。
"""
if not chunks:
return 0
embeddings = embed_texts([c.content for c in chunks])
......@@ -87,6 +124,11 @@ class QdrantHybridStore:
return total
def search(self, query: str, filters: dict[str, Any], limit: int | None = None) -> list[dict[str, Any]]:
"""
根据给定的查询和过滤条件搜索匹配的文本分块。
会根据配置决定调用纯 Dense 的相似度搜索,还是调用 Hybrid 混合检索。
"""
if not self.available or self.client is None:
return []
limit = limit or max(RAG_VECTOR_TOP_K, RAG_SPARSE_TOP_K)
......@@ -126,17 +168,20 @@ class QdrantHybridStore:
return _points_to_hits(getattr(response, "points", response), score_name="vector_score")
def set_file_status(self, file_id: str, status: str) -> None:
"""更新给定文件对应所有分块的可用状态(如:active/disabled)。"""
if not self.available or self.client is None:
return
self._set_payload({"status": status}, {"file_id": file_id})
def delete_file(self, file_id: str) -> None:
"""将 Qdrant 中属于特定 file_id 的所有分块数据永久删除。"""
if not self.available or self.client is None:
return
self.client.delete(collection_name=QDRANT_COLLECTION, points_selector=_qdrant_filter({"file_id": file_id}))
logger.info("[RAG] Qdrant 删除文件索引完成: file_id=%s", file_id)
def count_file(self, file_id: str) -> int | None:
"""统计 Qdrant 中属于某个 file_id 的分块数量,常用于中断恢复或数据一致性校验。"""
if not self.available or self.client is None:
return None
try:
......@@ -147,6 +192,7 @@ class QdrantHybridStore:
return None
def delete_chunk_ids(self, chunk_ids: list[str]) -> None:
"""批量删除指定的 chunk 向量数据,常用于重新索引时清理旧的残留切块。"""
if not self.available or self.client is None or not chunk_ids:
return
from qdrant_client.models import PointIdsList
......@@ -154,6 +200,9 @@ class QdrantHybridStore:
self.client.delete(collection_name=QDRANT_COLLECTION, points_selector=PointIdsList(points=[_point_id(chunk_id) for chunk_id in chunk_ids]))
logger.info("[RAG] Qdrant 删除旧 chunk points 完成: chunks=%s", len(chunk_ids))
def point_id(self, chunk_id: str) -> str:
return _point_id(chunk_id)
def _set_payload(self, payload: dict[str, Any], filters: dict[str, Any]) -> None:
self.client.set_payload(collection_name=QDRANT_COLLECTION, payload=payload, points=_qdrant_filter(filters))
......@@ -207,13 +256,27 @@ def _payload(chunk: RagChunkData) -> dict[str, Any]:
"chunk_id": chunk.chunk_id,
"parent_chunk_id": chunk.parent_chunk_id,
"file_id": chunk.file_id,
"document_id": chunk.file_id,
"status": chunk.status,
"brand": chunk.brand,
"brands": metadata.get("brands"),
"brand_series": metadata.get("brand_series"),
"business_category": chunk.business_category,
"sub_business": metadata.get("sub_business"),
"page_type": chunk.page_type,
"intent_type": chunk.intent_type,
"content_kind": metadata.get("content_kind"),
"section_title": metadata.get("section_title"),
"section_path": metadata.get("section_path"),
"parse_status": metadata.get("parse_status", "ok"),
"parse_quality": metadata.get("parse_quality") or metadata.get("text_quality"),
"page_start": metadata.get("page_start") or chunk.page_number,
"page_end": metadata.get("page_end") or chunk.page_number,
"row_start": metadata.get("row_start") or chunk.row_start,
"row_end": metadata.get("row_end") or chunk.row_end,
"table_header": metadata.get("table_header"),
"parser_version": metadata.get("parser_version"),
"chunker_version": metadata.get("chunker_version"),
"source_name": chunk.source_name,
"chunk_index": chunk.chunk_index,
}
......
"""
RAG 相关的通用工具函数集合。
包含了哈希计算、文本规范化、Token估算以及 JSON 和文件相关的辅助工具。
"""
import hashlib
import json
import re
......@@ -6,18 +10,27 @@ from typing import Any
def sha256_text(text: str) -> str:
"""计算文本的 SHA-256 哈希值,常用于比对文件内容是否发生变更。"""
return hashlib.sha256(text.encode("utf-8", errors="ignore")).hexdigest()
def sha256_file(path: str) -> str:
"""计算本地文件的 SHA-256 哈希值,采用分块读取以支持大文件。"""
h = hashlib.sha256()
with open(path, "rb") as f:
# 每次读取 1MB 块进行哈希更新
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def normalize_text(text: str) -> str:
"""
对提取到的文本进行标准化清理:
1. 统一换行符;
2. 将连续空格或制表符替换为单个空格;
3. 将过多(3次以上)的换行符缩减为两行。
"""
text = text.replace("\r\n", "\n").replace("\r", "\n")
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n{3,}", "\n\n", text)
......@@ -25,15 +38,21 @@ def normalize_text(text: str) -> str:
def estimate_tokens(text: str) -> int:
# 中文业务文档用字符粗估即可,避免把 tiktoken 放到切块热路径里。
"""
粗略估算字符串所占的 Token 数量。
中文业务文档用字符数粗估即可(平均每 1.8 个字符约合 1 个 Token),
这可以避免把昂贵且缓慢的 tiktoken 库放到文档切块的热点执行路径里。
"""
return max(1, int(len(text) / 1.8))
def safe_json_dumps(data: Any) -> str:
"""安全地将数据对象序列化为 JSON 字符串,保留非 ASCII 字符并默认转为字符串。"""
return json.dumps(data, ensure_ascii=False, default=str)
def safe_json_loads(text: str | None, default: Any = None) -> Any:
"""安全地解析 JSON 字符串。如果解析失败或输入为空,返回给定的默认值。"""
if not text:
return default
try:
......@@ -43,5 +62,6 @@ def safe_json_loads(text: str | None, default: Any = None) -> Any:
def file_ext(name: str) -> str:
"""获取文件名的扩展名,并统一转换为小写形式。"""
return Path(name).suffix.lower()
import asyncio
import sys
import os
import functools
import contextlib
......@@ -7,6 +6,7 @@ import contextvars
import agentscope
from agentscope.model import DashScopeChatModel
from config import SKILLS_DIR, API_KEY, is_multimodal, is_thinking
from src.utils.logger import StreamTranscript
# ==================================================================================
# 核心组件:Token 消耗跟踪器 (Token Tracker)
......@@ -43,6 +43,7 @@ class TrackingDashScopeChatModel(DashScopeChatModel):
last_input = 0
last_output = 0
last_reasoning_len = 0
transcript = StreamTranscript(f"{getattr(self, 'model_name', 'model')} thinking")
# 逐块(Chunk)读取大模型流式响应
async for chunk in res:
# 并非所有的 Chunk 都会携带 usage 字段,通常只有最后一个 Chunk 包含总计 Token
......@@ -59,16 +60,15 @@ class TrackingDashScopeChatModel(DashScopeChatModel):
if len(current_thinking) > last_reasoning_len:
delta = current_thinking[last_reasoning_len:]
if print_thinking.get():
sys.stdout.write(delta)
sys.stdout.flush()
transcript.write(delta)
last_reasoning_len = len(current_thinking)
# 将当前 Chunk 原封不动 yield 给上层业务
yield chunk
if last_reasoning_len > 0 and print_thinking.get():
sys.stdout.write("\n")
sys.stdout.flush()
transcript.write("\n")
transcript.close()
# 流式输出全部结束后,计算总 Token 并累加到当前任务的 ContextVar 计数器中
counter = current_task_tokens.get(None)
......
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
try:
async with session.get("https://dashscope.aliyuncs.com") as resp:
print(resp.status)
except Exception as e:
print(repr(e))
asyncio.run(main())
import asyncio
import importlib
import json
import sys
import types
from types import SimpleNamespace
def load_query_module(monkeypatch):
config_mod = types.ModuleType("config")
config_mod.QUERY_MODEL_NAME = "fake-model"
monkeypatch.setitem(sys.modules, "config", config_mod)
class FakeRouter:
def post(self, *_args, **_kwargs):
def decorator(func):
return func
return decorator
class FakeHTTPException(Exception):
def __init__(self, status_code=500, detail=""):
super().__init__(detail)
self.status_code = status_code
self.detail = detail
fastapi = types.ModuleType("fastapi")
fastapi.APIRouter = lambda: FakeRouter()
fastapi.Body = lambda default=None, **_kwargs: default
fastapi.HTTPException = FakeHTTPException
responses = types.ModuleType("fastapi.responses")
responses.StreamingResponse = lambda generator, **kwargs: SimpleNamespace(generator=generator, kwargs=kwargs)
monkeypatch.setitem(sys.modules, "fastapi", fastapi)
monkeypatch.setitem(sys.modules, "fastapi.responses", responses)
class FakeMsg:
def __init__(self, name, content, role=None):
self.name = name
self.content = content
self.role = role
self.id = f"{name}-id"
agent_mod = types.ModuleType("agentscope.agent")
agent_mod.ReActAgent = object
formatter_mod = types.ModuleType("agentscope.formatter")
formatter_mod.DashScopeChatFormatter = object
message_mod = types.ModuleType("agentscope.message")
message_mod.Msg = FakeMsg
tool_mod = types.ModuleType("agentscope.tool")
tool_mod.Toolkit = object
monkeypatch.setitem(sys.modules, "agentscope", types.ModuleType("agentscope"))
monkeypatch.setitem(sys.modules, "agentscope.agent", agent_mod)
monkeypatch.setitem(sys.modules, "agentscope.formatter", formatter_mod)
monkeypatch.setitem(sys.modules, "agentscope.message", message_mod)
monkeypatch.setitem(sys.modules, "agentscope.tool", tool_mod)
models_mod = types.ModuleType("src.database.models")
models_mod.WikiQueryLog = object
session_mod = types.ModuleType("src.database.session")
session_mod.AsyncSessionLocal = object
monkeypatch.setitem(sys.modules, "src.database.models", models_mod)
monkeypatch.setitem(sys.modules, "src.database.session", session_mod)
tracker_mod = types.ModuleType("src.utils.llm_tracker")
tracker_mod.get_llm_model = lambda *_args, **_kwargs: object()
tracker_mod.load_skill_prompt = lambda *_args, **_kwargs: ""
class FakePrintThinking:
def set(self, value):
return value
def reset(self, token):
return None
tracker_mod.print_thinking = FakePrintThinking()
class TokenCounter:
async def __aenter__(self):
return lambda: 7
async def __aexit__(self, *_args):
return False
tracker_mod.token_counter_context = lambda: TokenCounter()
monkeypatch.setitem(sys.modules, "src.utils.llm_tracker", tracker_mod)
tools_mod = types.ModuleType("src.tools.wiki_tools")
tools_mod.glob_wiki_files = lambda *args, **kwargs: None
tools_mod.grep_wiki_files = lambda *args, **kwargs: None
tools_mod.read_local_file = lambda *args, **kwargs: None
monkeypatch.setitem(sys.modules, "src.tools.wiki_tools", tools_mod)
sys.modules.pop("src.api.routes.query", None)
return importlib.import_module("src.api.routes.query")
def decode_sse(events):
payloads = []
for event in events:
data = event.removeprefix("data: ").strip()
if data in {"[INIT]", "[DONE]"}:
payloads.append(data)
else:
payloads.append(json.loads(data))
return payloads
def test_stream_query_splits_reasoning_and_final_answer(monkeypatch):
query = load_query_module(monkeypatch)
async def noop_save(*_args, **_kwargs):
return None
monkeypatch.setattr(query, "save_query_log_to_db", noop_save)
class FakeAgent:
def set_console_output_enabled(self, _enabled):
return None
async def __call__(self, msg):
await self.print(query.Msg("WikiAssistant", [{"type": "tool_use", "name": "grep", "input": "x"}], role="assistant"))
await self.print(query.Msg("WikiAssistant", "Final Answer: should not be reasoning", role="assistant"))
return SimpleNamespace(content="Final Answer: final answer")
monkeypatch.setattr(query, "build_query_agent", lambda _history: FakeAgent())
async def collect():
return [event async for event in query.run_wiki_query_stream("q", [], "s1")]
payloads = decode_sse(asyncio.run(collect()))
assert payloads[0] == "[INIT]"
assert payloads[-1] == "[DONE]"
assert any(isinstance(item, dict) and item.get("type") == "call" for item in payloads)
assert not any(
isinstance(item, dict)
and item.get("type") == "thought"
and "should not be reasoning" in item.get("content", "")
for item in payloads
)
assert "".join(item["content"] for item in payloads if isinstance(item, dict) and item.get("type") == "stream") == "final answer"
assert sum(1 for item in payloads if isinstance(item, dict) and item.get("type") == "done") == 1
def test_json_query_uses_empty_answer_fallback(monkeypatch):
query = load_query_module(monkeypatch)
async def noop_save(*_args, **_kwargs):
return None
monkeypatch.setattr(query, "save_query_log_to_db", noop_save)
class FakeAgent:
def set_console_output_enabled(self, _enabled):
return None
async def __call__(self, msg):
return SimpleNamespace(content="")
monkeypatch.setattr(query, "build_query_agent", lambda _history: FakeAgent())
result = asyncio.run(query.run_wiki_query_json("q", [], "s1"))
assert result.status == "EmptyAnswer"
assert result.answer == query.EMPTY_ANSWER_FALLBACK
assert result.tokens == 7
def test_stream_query_emits_error_on_agent_failure(monkeypatch):
query = load_query_module(monkeypatch)
async def noop_save(*_args, **_kwargs):
return None
monkeypatch.setattr(query, "save_query_log_to_db", noop_save)
class FakeAgent:
def set_console_output_enabled(self, _enabled):
return None
async def __call__(self, msg):
raise RuntimeError("boom")
monkeypatch.setattr(query, "build_query_agent", lambda _history: FakeAgent())
async def collect():
return [event async for event in query.run_wiki_query_stream("q", [], "s1")]
payloads = decode_sse(asyncio.run(collect()))
assert any(isinstance(item, dict) and item.get("type") == "error" and "boom" in item.get("content", "") for item in payloads)
assert payloads[-1] == "[DONE]"
def test_stream_query_done_is_not_blocked_by_slow_log_save(monkeypatch):
query = load_query_module(monkeypatch)
async def never_finishes_save(*_args, **_kwargs):
await asyncio.Event().wait()
monkeypatch.setattr(query, "save_query_log_to_db", never_finishes_save)
class FakeAgent:
def set_console_output_enabled(self, _enabled):
return None
async def __call__(self, msg):
return SimpleNamespace(content="Final Answer: quick answer")
monkeypatch.setattr(query, "build_query_agent", lambda _history: FakeAgent())
async def collect():
return await asyncio.wait_for(
_collect_stream(query.run_wiki_query_stream("q", [], "s1")),
timeout=1,
)
payloads = decode_sse(asyncio.run(collect()))
assert "".join(item["content"] for item in payloads if isinstance(item, dict) and item.get("type") == "stream") == "quick answer"
assert any(isinstance(item, dict) and item.get("type") == "done" for item in payloads)
assert payloads[-1] == "[DONE]"
async def _collect_stream(stream):
return [event async for event in stream]
from src.rag.loaders.markdown_loader import parse_markdown_text
from src.rag.loaders.text_loader import split_plain_blocks
def test_plain_text_loader_adds_common_metadata():
blocks = split_plain_blocks("第一段内容\n\n第二段内容", title_path="测试文档")
assert len(blocks) == 2
assert blocks[0].metadata["parse_method"] == "plain_text"
assert blocks[0].metadata["content_kind"] == "text"
assert blocks[0].metadata["section_path"] == ["测试文档"]
assert blocks[0].metadata["parse_status"] == "ok"
assert blocks[0].metadata["parser_version"]
assert blocks[0].metadata["chunker_version"]
assert blocks[0].metadata["char_start"] == 0
def test_markdown_loader_adds_table_semantics():
blocks = parse_markdown_text(
"# 服务价格\n\n| 项目 | 价格 |\n| --- | --- |\n| 延保 | 1000 |\n"
)
assert len(blocks) == 1
table = blocks[0]
assert table.block_type == "table"
assert table.metadata["parse_method"] == "markdown"
assert table.metadata["content_kind"] == "table"
assert table.metadata["section_path"] == ["服务价格"]
assert table.metadata["section_title"] == "服务价格"
assert table.metadata["table_header"] == ["项目", "价格"]
assert table.metadata["table_row_count"] == 1
......@@ -49,6 +49,8 @@ def test_table_child_chunks_keep_title_context_and_header():
assert children[0].metadata_json["overlap_next_rows"] == 1
assert children[1].metadata_json["overlap_prev_rows"] == 1
assert children[1].row_start == 6
assert "rows=6-" in children[1].content
assert children[1].metadata_json["overlap_source_rows"]["prev"] == [6, 6]
def test_text_child_chunks_keep_context_and_overlap_metadata(monkeypatch):
......@@ -102,6 +104,51 @@ def test_pdf_price_overview_keeps_battery_intro_with_table_context():
assert all(child.row_start is not None and child.row_end is not None for child in battery_table_children)
assert any(child.metadata_json.get("overlap_next_rows", 0) > 0 for child in battery_table_children)
assert not any("5,7885,325" in parent.content for parent in parents if not parent.metadata_json.get("table_markdown"))
assert not any(parent.title_path == "整车延保" for parent in parents)
assert any("五、出险代步服务" in parent.title_path for parent in parents)
assert any("七、辅助驾驶无忧服务" in parent.title_path for parent in parents)
assert sum(1 for parent in parents if len(parent.content) < 80) <= 5
def test_heading_and_intro_attach_to_following_table_parent():
blocks = [
DocumentBlock(
text="二、电池延保服务",
block_type="paragraph",
title_path="二、电池延保服务",
page_number=1,
metadata={"parse_method": "pymupdf_text", "content_role": "heading", "section_path": ["二、电池延保服务"]},
),
DocumentBlock(
text='说明:新车享有"提车礼惠"92折活动价。',
block_type="paragraph",
title_path="二、电池延保服务",
page_number=1,
metadata={"parse_method": "pymupdf_text", "content_role": "body", "section_path": ["二、电池延保服务"]},
),
DocumentBlock(
text="\n".join(
[
"| 车系 | 产品名称 | 价格 |",
"| --- | --- | --- |",
"| 智界S7 | 电池延保 | 5,788 |",
]
),
block_type="table",
title_path="二、电池延保服务 / P1 表1",
page_number=1,
row_start=1,
row_end=1,
metadata={"parse_method": "pymupdf_table", "table_markdown": True, "content_role": "table", "section_path": ["二、电池延保服务"]},
),
]
parents, children = build_chunks("file-1", "price.pdf", "price.pdf", "PDF", blocks)
assert len(parents) == 1
assert parents[0].metadata_json["content_kind"] == "mixed_table"
assert "说明:新车享有" in parents[0].content
assert "| 智界S7 | 电池延保 | 5,788 |" in children[0].content
def test_rerank_uses_configurable_sparse_weight(monkeypatch):
......
......@@ -207,6 +207,31 @@ def test_reranker_uses_configured_model_and_records_scores(monkeypatch):
assert ranked[1].rerank_score == 0.32
def test_reranker_defaults_to_qwen3_vl_rerank():
assert reranker.RAG_RERANKER_MODEL == "qwen3-vl-rerank"
def test_reranker_logs_model_status_and_message_on_error(monkeypatch, caplog):
class TextReRank:
@staticmethod
def call(**kwargs):
return SimpleNamespace(status_code=400, message="Model not exist.")
monkeypatch.setitem(sys.modules, "dashscope", SimpleNamespace(TextReRank=TextReRank))
monkeypatch.setattr(reranker, "RAG_RERANKER_MODEL", "qwen3-vl-rerank", raising=False)
first = _chunk("first", content="first")
second = _chunk("second", content="second")
with caplog.at_level("WARNING"):
ranked = reranker.rerank_chunks("query", [first, second])
assert ranked == [first, second]
assert "model=qwen3-vl-rerank" in caplog.text
assert "status=400" in caplog.text
assert "Model not exist." in caplog.text
def test_apply_context_budget_prefers_direct_high_score_chunks(monkeypatch):
monkeypatch.setattr(retrieval, "RAG_MAX_CONTEXT_CHARS", 16)
neighbor = _chunk("neighbor", content="neighbor text")
......@@ -292,7 +317,7 @@ def test_clear_history_deletes_only_requested_session(monkeypatch):
assert "commit" in calls
def test_stream_query_emits_reasoning_steps_and_logs_answer_delta(monkeypatch, caplog):
def test_stream_query_emits_reasoning_steps_and_logs_complete_answer(monkeypatch, caplog):
async def noop_schema():
return None
......@@ -344,5 +369,54 @@ def test_stream_query_emits_reasoning_steps_and_logs_answer_delta(monkeypatch, c
assert "retrieval" in reasoning_phases
assert "sources" in reasoning_phases
assert "answer" in reasoning_phases
assert "answer_delta: 流式" in caplog.text
assert "answer_delta: 回答" in caplog.text
assert "answer_delta:" not in caplog.text
assert "answer complete:" in caplog.text
assert "流式回答" in caplog.text
def test_stream_query_done_survives_query_log_save_failure(monkeypatch, caplog):
async def noop_schema():
return None
async def fake_build_effective_history(payload):
return []
async def fake_classify(query, history):
return IntentResult(intent="general_knowledge", intents=["general_knowledge"])
async def fake_retrieve(query, intent, history, user_context):
return {
"chunks": [_chunk("chunk-1")],
"ranked": [],
"query_plan": {"direct_query": query},
"queries": [{"type": "direct", "query": query}],
"filters": {},
"soft_boosts": {},
}
async def fake_generate_answer_stream(query, intent, chunks, history):
yield {"type": "answer_delta", "content": "answer"}
async def fake_save_query(payload, intent, retrieval_data, answer, tokens, start, status):
raise RuntimeError("db unavailable")
monkeypatch.setattr(service, "ensure_rag_schema", noop_schema)
monkeypatch.setattr(service, "_build_effective_history", fake_build_effective_history)
monkeypatch.setattr(service, "classify_intent", fake_classify)
monkeypatch.setattr(service, "retrieve", fake_retrieve)
monkeypatch.setattr(retrieval, "generate_answer_stream", fake_generate_answer_stream)
monkeypatch.setattr(service, "_save_query", fake_save_query)
payload = SimpleNamespace(query="question", history=[], userContext={}, sessionId="s1")
async def collect():
return [event async for event in service.stream_query(payload)]
with caplog.at_level("ERROR"):
events = asyncio.run(collect())
done = [event for event in events if event.get("type") == "done"]
assert done
assert done[-1]["data"]["answer"] == "answer"
assert done[-1]["data"]["queryLogId"] is None
assert "failed to save query log" in caplog.text
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!