Commit 3bb681d4 by 黄南光

Merge remote-tracking branch 'origin/wiki_dev20260624'

# Conflicts:
#	GEMINI.md
#	src/api/routes/query.py
2 parents d3720436 3cb6f887
Showing 59 changed files with 2704 additions and 324 deletions
# LLM Wiki 知识库项目指南
本项是一个基于 LLM 的自动化知识库系统,采用 Karpathy 的 "Raw-Wiki-Schema" 架构,专为特定垂直领域(如汽车后市场)设计的岗位 Agent 业务知识库。
## 项目概述
项目通过将原始文档(PDF, MD, Docx 等)自动化“摄取”并转化为结构化的 Wiki 页面,构建一个支持双链引用(Obsidian 兼容)的知识库。它集成了自动化摄取 (Ingest)、知识问答 (Query) 和质量巡检 (Lint) 三大核心能力。
## 核心架构
项目采用 **Python (FastAPI) + Node.js (Next.js) + Agent (Prompts)** 的三层架构:
### 1. 数据层 (Data Tier)
- `ware/raw/`: 存放原始输入文件。
- `ware/wiki/`: 存放生成的结构化 Markdown 页面。
- `entities/`, `products/`, `concepts/`, `procedures/`, `scripts/`, `policies/`, `comparisons/`, `troubleshooting/`, `sources/`, `synthesis/`:按 10 种类型分类存储。
- `index.md`: 知识库索引。
- `log.md`: 摄取与更新日志。
### 2. 逻辑层 (Logic Tier - Python Backend)
- `src/api/routes/`: FastAPI 路由,处理文件管理、摄取任务、查询和巡检。
- `src/tools/`:
- `document_parser.py`: 文档解析工具。
- `wiki_tools.py`: Wiki 页面读写、搜索和维护工具。
- `src/database/`: SQLAlchemy ORM 模型与数据库会话管理。
- `main.py`: 后端入口(运行在 8104 端口)。
### 3. 技能层 (Skill Tier - Agent Logic)
- `skills/`: 存放 Agent 的 System Prompts 和业务规则。
- `llm-ingest/`: 摄取规划与写作规则(3-Phase 架构)。
- `llm-query/`: 知识检索与问答逻辑。
- `llm-lint/`: 知识库一致性与合规性检查。
### 4. 展示层 (UI Tier - Next.js Frontend)
- `frontend/`: 基于 Next.js 16 的管理后台,提供文件上传、Wiki 预览和 AI 聊天界面。
## 技术栈
- **后端**: Python 3.10+, FastAPI, SQLAlchemy, AgentScope, PyMuPDF.
- **前端**: Next.js (App Router), TypeScript, Tailwind CSS, Lucide React.
- **数据库**: MySQL (主存储), Redis (可选缓存).
- **LLM**: 支持 Qwen (DashScope), OpenAI, Anthropic 等,通过 `config.py` 配置。
## 运行与开发
### 环境配置
1. **Python 环境**:
- 解释器路径: `D:\software_install\anaconda\envs\study_agent_demo`
- 安装依赖: `pip install -r requirements.txt`
2. **Node.js 环境**:
- 进入 `frontend/` 目录,运行 `npm install`。
### 启动命令
- **后端**: `python main.py` (默认端口 8104)
- **前端**: `cd frontend && npm run dev` (默认端口 3001)
### 数据库初始化
后端启动时会自动调用 `src.database.session.init_db()` 初始化 MySQL 表结构。
## 开发规范
### 1. Wiki 页面标准 (Schema v1.3)
所有生成的 Wiki 页面必须包含严格的 YAML frontmatter:
```yaml
---
schema_version: v1.3
type: <type_name>
title: <page_title>
tags: [<brand>, <category>, <sub_category>, <role>]
related: ["[[ware/wiki/path/to/page.md]]"]
sources: ["raw/filename.pdf"]
created: YYYY-MM-DD
updated: YYYY-MM-DD
---
```
### 2. 引用规范
- **Wikilinks**: 必须使用带 `ware/wiki/` 前缀的全路径引用,例如 `[[ware/wiki/products/service_a.md]]`。
- **Slug**: 文件名(不含路径和扩展名)作为唯一标识符。
### 3. Agent 工作流
- **Ingest**: 采用 Planning -> Concurrent Writing -> Sync 的三阶段流程。
- **Lint**: 定期扫描 `ware/wiki/` 检查链接断裂、Schema 缺失或内容矛盾。
## 常用工具命令 TODO
- [ ] 添加自动化测试脚本说明。
- [ ] 完善数据库迁移指南。
...@@ -30,9 +30,14 @@ os.makedirs(METADATA_DIR, exist_ok=True) ...@@ -30,9 +30,14 @@ os.makedirs(METADATA_DIR, exist_ok=True)
API_KEY = os.environ.get("DASHSCOPE_API_KEY") or os.environ.get("OPENAI_API_KEY", "sk-xxx") API_KEY = os.environ.get("DASHSCOPE_API_KEY") or os.environ.get("OPENAI_API_KEY", "sk-xxx")
# 针对不同场景的模型配置 # 针对不同场景的模型配置
INGEST_MODEL_NAME = os.environ.get("INGEST_MODEL_NAME", "qwen3.7-plus") INGEST_MODEL_NAME = os.environ.get("INGEST_MODEL_NAME", "deepseek-v4-flash")
QUERY_MODEL_NAME = os.environ.get("QUERY_MODEL_NAME", "qwen3.7-plus") QUERY_MODEL_NAME = os.environ.get("QUERY_MODEL_NAME", "deepseek-v4-flash")
LINT_MODEL_NAME = os.environ.get("LINT_MODEL_NAME", "qwen-plus") LINT_MODEL_NAME = os.environ.get("LINT_MODEL_NAME", "deepseek-v4-flash")
# INGEST_MODEL_NAME = os.environ.get("INGEST_MODEL_NAME", "deepseek-v4-flash")
# QUERY_MODEL_NAME = os.environ.get("QUERY_MODEL_NAME", "deepseek-v4-flash")
# LINT_MODEL_NAME = os.environ.get("LINT_MODEL_NAME", "deepseek-v4-flash")
def is_multimodal(model_name: str) -> bool: def is_multimodal(model_name: str) -> bool:
return "-vl" in model_name.lower() or model_name.lower().startswith("qvq") or "qwen3.7" in model_name.lower() return "-vl" in model_name.lower() or model_name.lower().startswith("qvq") or "qwen3.7" in model_name.lower()
......
...@@ -14,11 +14,22 @@ services: ...@@ -14,11 +14,22 @@ services:
- DB_NAME=${DB_NAME:-wiki_db} - DB_NAME=${DB_NAME:-wiki_db}
# 需要时在服务器系统环境变量或者 .env 里配置大模型 API Key # 需要时在服务器系统环境变量或者 .env 里配置大模型 API Key
- DASHSCOPE_API_KEY=${DASHSCOPE_API_KEY} - DASHSCOPE_API_KEY=${DASHSCOPE_API_KEY}
- RAG_ENABLED=${RAG_ENABLED:-true}
- RAG_VECTOR_STORE=${RAG_VECTOR_STORE:-qdrant}
- QDRANT_URL=${QDRANT_URL:-http://qdrant:6333}
- QDRANT_COLLECTION=${QDRANT_COLLECTION:-rag_chunks}
- RAG_ANSWER_MODEL=${RAG_ANSWER_MODEL:-qwen3.7-plus}
- RAG_INTENT_MODEL=${RAG_INTENT_MODEL:-qwen-plus}
- RAG_REWRITE_MODEL=${RAG_REWRITE_MODEL:-qwen-plus}
- RAG_EMBEDDING_MODEL=${RAG_EMBEDDING_MODEL:-text-embedding-v4}
- RAG_ALLOW_HASH_EMBEDDING=${RAG_ALLOW_HASH_EMBEDDING:-false}
ports: ports:
- "8104:8104" - "8104:8104"
volumes: volumes:
- ./ware:/app/ware - ./ware:/app/ware
- ./logs:/app/logs - ./logs:/app/logs
depends_on:
- qdrant
frontend: frontend:
build: build:
...@@ -35,4 +46,12 @@ services: ...@@ -35,4 +46,12 @@ services:
ports: ports:
- "3001:3000" - "3001:3000"
qdrant:
image: qdrant/qdrant:latest
container_name: wiki-qdrant
restart: always
ports:
- "6333:6333"
- "6334:6334"
volumes:
- ./ware/rag/qdrant:/qdrant/storage
...@@ -15,21 +15,7 @@ interface TreeNodeData { ...@@ -15,21 +15,7 @@ interface TreeNodeData {
children?: TreeNodeData[]; children?: TreeNodeData[];
} }
export default function WikiRepoPage() { const sortTreeData = (nodes: TreeNodeData[]): TreeNodeData[] => {
const [treeData, setTreeData] = useState<TreeNodeData[]>([]);
const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [fileContent, setFileContent] = useState<string>("");
const [isLoadingTree, setIsLoadingTree] = useState(true);
const [isLoadingFile, setIsLoadingFile] = useState(false);
const [searchQuery, setSearchQuery] = useState("");
const [selectedForDownload, setSelectedForDownload] = useState<Set<string>>(new Set());
useEffect(() => {
fetchTree();
}, []);
const sortTreeData = (nodes: TreeNodeData[]): TreeNodeData[] => {
const sorted = [...nodes].sort((a, b) => { const sorted = [...nodes].sort((a, b) => {
if (a.type !== b.type) return a.type === "dir" ? -1 : 1; if (a.type !== b.type) return a.type === "dir" ? -1 : 1;
const aIsBottom = a.name === "index.md" || a.name === "log.md"; const aIsBottom = a.name === "index.md" || a.name === "log.md";
...@@ -42,7 +28,37 @@ export default function WikiRepoPage() { ...@@ -42,7 +28,37 @@ export default function WikiRepoPage() {
...node, ...node,
children: node.children ? sortTreeData(node.children) : undefined children: node.children ? sortTreeData(node.children) : undefined
})); }));
}; };
const filterTree = (nodes: TreeNodeData[], query: string): TreeNodeData[] => {
if (!query) return nodes;
const lowerQuery = query.toLowerCase();
return nodes.map(node => {
if (node.type === "dir") {
const filteredChildren = filterTree(node.children || [], query);
if (filteredChildren.length > 0 || node.name.toLowerCase().includes(lowerQuery)) {
return { ...node, children: filteredChildren };
}
return null;
} else {
if (node.name.toLowerCase().includes(lowerQuery)) {
return node;
}
return null;
}
}).filter(Boolean) as TreeNodeData[];
};
export default function WikiRepoPage() {
const [treeData, setTreeData] = useState<TreeNodeData[]>([]);
const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [fileContent, setFileContent] = useState<string>("");
const [isLoadingTree, setIsLoadingTree] = useState(true);
const [isLoadingFile, setIsLoadingFile] = useState(false);
const [searchQuery, setSearchQuery] = useState("");
const [selectedForDownload, setSelectedForDownload] = useState<Set<string>>(new Set());
const fetchTree = async () => { const fetchTree = async () => {
setIsLoadingTree(true); setIsLoadingTree(true);
...@@ -50,13 +66,19 @@ export default function WikiRepoPage() { ...@@ -50,13 +66,19 @@ export default function WikiRepoPage() {
const res = await fetch(`${API_BASE}/wiki/tree`); const res = await fetch(`${API_BASE}/wiki/tree`);
const data = await res.json(); const data = await res.json();
setTreeData(sortTreeData(data.tree)); setTreeData(sortTreeData(data.tree));
} catch (e) { } catch {
console.error("Failed to fetch tree", e); console.error("Failed to fetch tree");
} finally { } finally {
setIsLoadingTree(false); setIsLoadingTree(false);
} }
}; };
useEffect(() => {
Promise.resolve().then(() => {
void fetchTree();
});
}, []);
const fetchFile = async (path: string) => { const fetchFile = async (path: string) => {
setIsLoadingFile(true); setIsLoadingFile(true);
setSelectedFile(path); setSelectedFile(path);
...@@ -69,7 +91,7 @@ export default function WikiRepoPage() { ...@@ -69,7 +91,7 @@ export default function WikiRepoPage() {
} else { } else {
setFileContent("无法加载文件内容。"); setFileContent("无法加载文件内容。");
} }
} catch (e) { } catch {
setFileContent("文件加载失败,请检查网络。"); setFileContent("文件加载失败,请检查网络。");
} finally { } finally {
setIsLoadingFile(false); setIsLoadingFile(false);
...@@ -113,7 +135,7 @@ export default function WikiRepoPage() { ...@@ -113,7 +135,7 @@ export default function WikiRepoPage() {
a.click(); a.click();
window.URL.revokeObjectURL(url); window.URL.revokeObjectURL(url);
a.remove(); a.remove();
} catch (e) { } catch {
alert("批量下载失败,请检查网络"); alert("批量下载失败,请检查网络");
} }
}; };
...@@ -122,31 +144,13 @@ export default function WikiRepoPage() { ...@@ -122,31 +144,13 @@ export default function WikiRepoPage() {
window.open(`${API_BASE}/wiki/download?path=${encodeURIComponent(path)}`, "_blank"); window.open(`${API_BASE}/wiki/download?path=${encodeURIComponent(path)}`, "_blank");
}; };
const filterTree = (nodes: TreeNodeData[], query: string): TreeNodeData[] => {
if (!query) return nodes;
const lowerQuery = query.toLowerCase();
return nodes.map(node => {
if (node.type === "dir") {
const filteredChildren = filterTree(node.children || [], query);
if (filteredChildren.length > 0 || node.name.toLowerCase().includes(lowerQuery)) {
return { ...node, children: filteredChildren };
}
return null;
} else {
if (node.name.toLowerCase().includes(lowerQuery)) {
return node;
}
return null;
}
}).filter(Boolean) as TreeNodeData[];
};
const filteredTreeData = useMemo(() => filterTree(treeData, searchQuery), [treeData, searchQuery]); const filteredTreeData = useMemo(() => filterTree(treeData, searchQuery), [treeData, searchQuery]);
// Auto-expand folders when searching const handleSearchChange = (val: string) => {
useEffect(() => { setSearchQuery(val);
if (searchQuery) { if (val) {
const newExpanded = new Set(expandedFolders);
const filtered = filterTree(treeData, val);
const expandAll = (nodes: TreeNodeData[], paths: Set<string>) => { const expandAll = (nodes: TreeNodeData[], paths: Set<string>) => {
nodes.forEach(node => { nodes.forEach(node => {
if (node.type === "dir") { if (node.type === "dir") {
...@@ -155,11 +159,10 @@ export default function WikiRepoPage() { ...@@ -155,11 +159,10 @@ export default function WikiRepoPage() {
} }
}); });
}; };
const newExpanded = new Set(expandedFolders); expandAll(filtered, newExpanded);
expandAll(filteredTreeData, newExpanded);
setExpandedFolders(newExpanded); setExpandedFolders(newExpanded);
} }
}, [searchQuery, filteredTreeData]); };
const renderTree = (nodes: TreeNodeData[], level = 0) => { const renderTree = (nodes: TreeNodeData[], level = 0) => {
return nodes.map((node) => { return nodes.map((node) => {
...@@ -235,7 +238,7 @@ export default function WikiRepoPage() { ...@@ -235,7 +238,7 @@ export default function WikiRepoPage() {
type="text" type="text"
placeholder="搜索目录..." placeholder="搜索目录..."
value={searchQuery} value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)} onChange={(e) => handleSearchChange(e.target.value)}
className="w-full pl-9 pr-3 py-2 bg-slate-100 border border-transparent rounded-xl text-sm outline-none focus:bg-white focus:ring-2 focus:ring-blue-500/20 focus:border-blue-300 transition-all" className="w-full pl-9 pr-3 py-2 bg-slate-100 border border-transparent rounded-xl text-sm outline-none focus:bg-white focus:ring-2 focus:ring-blue-500/20 focus:border-blue-300 transition-all"
/> />
</div> </div>
......
...@@ -3,7 +3,7 @@ import ReactMarkdown from 'react-markdown'; ...@@ -3,7 +3,7 @@ import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm'; import remarkGfm from 'remark-gfm';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { import {
Bot, User, Wrench, ChevronDown, ChevronRight, ChevronDown, ChevronRight,
CheckCircle2, Loader2, Lightbulb, Terminal, CheckCircle2, Loader2, Lightbulb, Terminal,
BookOpen, FileText BookOpen, FileText
} from 'lucide-react'; } from 'lucide-react';
...@@ -42,32 +42,29 @@ export function MessageBubble({ role, content, reasoning, isStreaming, startTime ...@@ -42,32 +42,29 @@ export function MessageBubble({ role, content, reasoning, isStreaming, startTime
}, 100); }, 100);
return () => clearInterval(interval); return () => clearInterval(interval);
} else if (startTime && endTime) { } else if (startTime && endTime) {
Promise.resolve().then(() => {
setElapsedMs(endTime - startTime); setElapsedMs(endTime - startTime);
});
} else if (startTime && !isStreaming) { } else if (startTime && !isStreaming) {
// If it stopped streaming but endTime wasn't set, just freeze it // If it stopped streaming but endTime wasn't set, just freeze it
Promise.resolve().then(() => {
setElapsedMs(Date.now() - startTime); setElapsedMs(Date.now() - startTime);
});
} }
}, [isStreaming, startTime, endTime]); }, [isStreaming, startTime, endTime]);
const displayTime = elapsedMs > 0 ? Math.round(elapsedMs / 1000) + 's' : null; const displayTime = elapsedMs > 0 ? Math.round(elapsedMs / 1000) + 's' : null;
// 提取 interactive json // 提取 interactive json 并剔除
const { displayContent, interactiveData } = useMemo(() => { const displayContent = useMemo(() => {
if (!content) return { displayContent: '', interactiveData: null }; if (!content) return '';
const regex = /```json_interactive\s*(\{[\s\S]*?\})\s*```/; const regex = /```json_interactive\s*(\{[\s\S]*?\})\s*```/;
const match = content.match(regex);
let newContent = content; let newContent = content;
let json = null; if (content.match(regex)) {
if (match) {
try {
json = JSON.parse(match[1]);
newContent = content.replace(regex, ''); newContent = content.replace(regex, '');
} catch (e) {
// parsing failed, keep as is
}
} }
newContent = newContent.replace(/`+$/, '').trim(); newContent = newContent.replace(/`+$/, '').trim();
return { displayContent: newContent, interactiveData: json }; return newContent;
}, [content]); }, [content]);
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
import Link from "next/link"; import Link from "next/link";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import { BookOpen, Network, Files } from "lucide-react"; import { BookOpen, Database, FileText } from "lucide-react";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
export default function Sidebar() { export default function Sidebar() {
...@@ -20,11 +20,11 @@ export default function Sidebar() { ...@@ -20,11 +20,11 @@ export default function Sidebar() {
"p-2 rounded-lg transition relative group", "p-2 rounded-lg transition relative group",
pathname === "/" ? "bg-slate-800 text-white" : "hover:bg-slate-800 hover:text-slate-200" pathname === "/" ? "bg-slate-800 text-white" : "hover:bg-slate-800 hover:text-slate-200"
)} )}
title="原始文件" title="Wiki 原始文件"
> >
<Files className="w-5 h-5" /> <FileText className="w-5 h-5" />
<span className="absolute left-full ml-2 px-2 py-1 bg-slate-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 pointer-events-none whitespace-nowrap z-50"> <span className="absolute left-full ml-2 px-2 py-1 bg-slate-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 pointer-events-none whitespace-nowrap z-50">
原始文件 Wiki 原始文件
</span> </span>
</Link> </Link>
<Link <Link
...@@ -33,11 +33,24 @@ export default function Sidebar() { ...@@ -33,11 +33,24 @@ export default function Sidebar() {
"p-2 rounded-lg transition relative group", "p-2 rounded-lg transition relative group",
pathname === "/wiki-repo" ? "bg-slate-800 text-white" : "hover:bg-slate-800 hover:text-slate-200" pathname === "/wiki-repo" ? "bg-slate-800 text-white" : "hover:bg-slate-800 hover:text-slate-200"
)} )}
title="wiki知识库" title="Wiki 知识库"
> >
<Network className="w-5 h-5" /> <BookOpen className="w-5 h-5" />
<span className="absolute left-full ml-2 px-2 py-1 bg-slate-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 pointer-events-none whitespace-nowrap z-50"> <span className="absolute left-full ml-2 px-2 py-1 bg-slate-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 pointer-events-none whitespace-nowrap z-50">
wiki知识库 Wiki 知识库
</span>
</Link>
<Link
href="/rag"
className={cn(
"p-2 rounded-lg transition relative group",
pathname === "/rag" ? "bg-slate-800 text-white" : "hover:bg-slate-800 hover:text-slate-200"
)}
title="RAG 工作台"
>
<Database className="w-5 h-5" />
<span className="absolute left-full ml-2 px-2 py-1 bg-slate-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 pointer-events-none whitespace-nowrap z-50">
RAG 工作台
</span> </span>
</Link> </Link>
</nav> </nav>
......
import type { RagChunk, RagFile } from "./rag-types";
const API_BASE =
process.env.NEXT_PUBLIC_API_URL ||
(typeof window !== "undefined" ? `http://${window.location.hostname}:8104` : "http://127.0.0.1:8104");
export async function fetchRagFiles(search = ""): Promise<{ files: RagFile[]; total: number }> {
const res = await fetch(`${API_BASE}/rag/files?page=1&page_size=100&search=${encodeURIComponent(search)}`);
if (!res.ok) throw new Error("获取 RAG 文件列表失败");
return res.json();
}
export async function uploadRagFiles(files: File[]) {
const init = await fetch(`${API_BASE}/rag/upload/init`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ files: files.map((file) => ({ name: file.name })) }),
});
const initData = await init.json();
if (!init.ok) throw new Error(initData.detail || "初始化上传失败");
for (const file of files) {
const fileId = initData.mapping[file.name];
if (!fileId) continue;
const form = new FormData();
form.append("file", file);
const res = await fetch(`${API_BASE}/rag/upload/${encodeURIComponent(fileId)}`, { method: "POST", body: form });
if (!res.ok) throw new Error(`${file.name} 上传失败`);
}
return initData;
}
export async function postRagAction(path: string, body?: Record<string, unknown>) {
const options: RequestInit = { method: "POST" };
if (body) {
options.headers = { "Content-Type": "application/json" };
options.body = JSON.stringify(body);
}
const res = await fetch(`${API_BASE}${path}`, options);
if (!res.ok) {
const text = await res.text();
let detail = "操作失败";
try {
const data = JSON.parse(text);
detail = data.detail || data.error || detail;
} catch {}
throw new Error(detail);
}
return res.json();
}
export async function deleteRagAction(path: string) {
const res = await fetch(`${API_BASE}${path}`, { method: "DELETE" });
if (!res.ok) {
const text = await res.text();
let detail = "操作失败";
try {
const data = JSON.parse(text);
detail = data.detail || data.error || detail;
} catch {}
throw new Error(detail);
}
return res.json();
}
export async function fetchRagChunks(fileId: string): Promise<RagChunk[]> {
const res = await fetch(`${API_BASE}/rag/chunks/${encodeURIComponent(fileId)}`);
if (!res.ok) throw new Error("获取切片失败");
const data = await res.json();
return data.chunks || [];
}
export async function fetchRagStats() {
const res = await fetch(`${API_BASE}/rag/stats`);
if (!res.ok) throw new Error("获取统计失败");
return res.json();
}
export function streamRagQuery(
payload: { query: string; history: { role: string; content: string }[]; sessionId: string },
onEvent: (event: { type: string; content?: string; data?: unknown }) => void,
) {
const controller = new AbortController();
fetch(`${API_BASE}/rag/query`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
signal: controller.signal,
})
.then(async (res) => {
if (!res.ok) throw new Error(await res.text());
if (!res.body) throw new Error("浏览器不支持流式响应");
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const events = buffer.split("\n\n");
buffer = events.pop() || "";
for (const raw of events) {
const line = raw.split("\n").find((item) => item.startsWith("data: "));
if (!line) continue;
const data = line.slice(6);
if (data === "[INIT]") continue;
if (data === "[DONE]") continue;
onEvent(JSON.parse(data));
}
}
})
.catch((error) => onEvent({ type: "error", content: error.message }));
return controller;
}
export async function fetchRagChunk(chunkId: string): Promise<RagChunk> {
const res = await fetch(`${API_BASE}/rag/chunk/${encodeURIComponent(chunkId)}`);
if (!res.ok) throw new Error("获取片段详情失败");
const data = await res.json();
return data.chunk;
}
export async function clearRagHistory(sessionId: string) {
return postRagAction("/rag/clear_history", { sessionId });
}
export type RagFile = {
id: string;
name: string;
format: string;
size: number;
word_count: number;
status: "Pending" | "Uploading" | "Indexing" | "Indexed" | "Disabled" | "Failed" | "Deleted";
chunk_count: number;
parent_chunk_count: number;
child_chunk_count: number;
error_code?: string;
error_detail_json?: Record<string, unknown>;
error_message?: string;
created_at?: string;
indexed_at?: string;
};
export type RagChunk = {
source_index?: number;
chunk_id: string;
file_id: string;
parent_chunk_id?: string;
chunk_level: "parent" | "child";
chunk_index: number;
content: string;
title_path?: string;
source_name?: string;
page_number?: number;
slide_number?: number;
sheet_name?: string;
row_start?: number;
row_end?: number;
status: string;
intent_type?: string;
page_type?: string;
brand?: string;
business_category?: string;
metadata_json?: Record<string, unknown>;
score?: {
child_chunk_id?: string;
retrieval_type?: string;
vector_score?: number;
rerank_score?: number;
is_neighbor?: boolean;
};
};
export type RagReasoningStep = {
id: string;
phase: string;
title: string;
status: "running" | "done" | "error";
elapsed_ms?: number;
data?: Record<string, unknown>;
};
export type RagMessage = {
role: "user" | "assistant";
content: string;
thinking?: string;
sources?: RagChunk[];
reasoning?: RagReasoningStep[];
startTime?: number;
endTime?: number;
meta?: Record<string, unknown>;
};
export type RagCitation = {
index: number;
chunk_id?: string;
file_id?: string;
source_name?: string;
title_path?: string;
page_number?: number;
row_start?: number;
row_end?: number;
};
import asyncio import asyncio
import os
import sys import sys
# 修复 Windows 下 aiohttp 容易出现的 SSL ConnectionResetError 问题 # 修复 Windows 下 aiohttp 容易出现的 SSL ConnectionResetError 问题
...@@ -6,7 +7,6 @@ if sys.platform == 'win32': ...@@ -6,7 +7,6 @@ if sys.platform == 'win32':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# 禁用全局代理,防止 Clash/V2Ray 等代理软件拦截 aiohttp 导致 SSL 握手重置 (ConnectionResetError) # 禁用全局代理,防止 Clash/V2Ray 等代理软件拦截 aiohttp 导致 SSL 握手重置 (ConnectionResetError)
import os
os.environ["NO_PROXY"] = "*" os.environ["NO_PROXY"] = "*"
os.environ["no_proxy"] = "*" os.environ["no_proxy"] = "*"
...@@ -24,6 +24,7 @@ from src.api.routes.ingest import router as ingest_router ...@@ -24,6 +24,7 @@ from src.api.routes.ingest import router as ingest_router
from src.api.routes.query import router as query_router from src.api.routes.query import router as query_router
from src.api.routes.wiki import router as wiki_router from src.api.routes.wiki import router as wiki_router
from src.api.routes.lint import router as lint_router from src.api.routes.lint import router as lint_router
from src.rag.routes import router as rag_router
app = FastAPI( app = FastAPI(
title="LLM Wiki API", title="LLM Wiki API",
...@@ -47,6 +48,13 @@ async def startup_event(): ...@@ -47,6 +48,13 @@ async def startup_event():
logger.info("Initializing database...") logger.info("Initializing database...")
await init_db() await init_db()
logger.info("Database initialized.") logger.info("Database initialized.")
try:
from src.rag.service import repair_interrupted_indexes
result = await repair_interrupted_indexes(cleanup_partial=False)
logger.info("RAG recovery check finished: %s", result)
except Exception as exc:
logger.warning("RAG recovery check skipped or failed: %s", exc)
@app.on_event("shutdown") @app.on_event("shutdown")
async def shutdown_event(): async def shutdown_event():
...@@ -62,6 +70,7 @@ app.include_router(ingest_router) ...@@ -62,6 +70,7 @@ app.include_router(ingest_router)
app.include_router(query_router) app.include_router(query_router)
app.include_router(wiki_router) app.include_router(wiki_router)
app.include_router(lint_router) app.include_router(lint_router)
app.include_router(rag_router)
if __name__ == "__main__": if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8104, reload=False) uvicorn.run("main:app", host="0.0.0.0", port=8104, reload=False)
...@@ -24,9 +24,11 @@ aiomysql==0.3.2 ...@@ -24,9 +24,11 @@ aiomysql==0.3.2
PyMySQL==1.2.0 PyMySQL==1.2.0
redis==8.0.0 redis==8.0.0
aiofiles==25.1.0 aiofiles==25.1.0
qdrant-client>=1.12.0
FlagEmbedding>=1.3.4
# Document Processing # Document Processing
pandas<3.0.0 pandas>=2.2.0,<3.0.0
numpy<2.0.0 numpy<2.0.0
python-docx==1.2.0 python-docx==1.2.0
PyMuPDF==1.27.2.3 PyMuPDF==1.27.2.3
...@@ -41,6 +43,9 @@ python-frontmatter==1.3.0 ...@@ -41,6 +43,9 @@ python-frontmatter==1.3.0
lxml==6.1.1 lxml==6.1.1
# Utils & Misc # Utils & Misc
typing_extensions>=4.15.0
Pygments>=2.18.0
pytest>=8.0.0
python-dotenv==1.2.2 python-dotenv==1.2.2
requests==2.34.2 requests==2.34.2
httpx==0.28.1 httpx==0.28.1
...@@ -52,6 +57,7 @@ rich==15.0.0 ...@@ -52,6 +57,7 @@ rich==15.0.0
tqdm==4.67.3 tqdm==4.67.3
pillow==12.2.0 pillow==12.2.0
regex==2026.5.9 regex==2026.5.9
jieba>=0.42.1
shortuuid==1.0.13 shortuuid==1.0.13
APScheduler==3.11.2 APScheduler==3.11.2
python-socketio==5.16.2 python-socketio==5.16.2
......
# RAG 评测脚本
这个目录提供一个轻量评测入口,用于验证 RAG 的召回和回答质量。
运行方式:
```powershell
D:\software_install\anaconda\envs\wiki_knowledge\python.exe scripts/rag_eval/run_rag_eval.py --dataset scripts/rag_eval/demo_dataset.jsonl --api http://localhost:8104 --out logs/rag_eval_result.json
```
评测指标:
- `context_recall`:标准来源是否被召回。
- `context_precision`:召回来源中相关来源占比。
- `answer_relevancy`:答案是否覆盖标准答案要点。
- `faithfulness`:答案是否能被召回上下文支撑。
`demo_dataset.jsonl` 只是模板,请把 `expected_answer`、`expected_source_keywords`、`expected_file_names` 替换成你的真实标注。
{"id":"price-001","question":"智界S7在用车的电池延保价格是多少?","expected_answer":"应命中智界S7、在用车、电池延保的价格,数字必须和资料完全一致。","expected_source_keywords":["智界S7","在用车","电池延保"],"expected_file_names":["鸿蒙智行官方服务产品价格总览.pdf"],"tags":["price","product","numeric"]}
{"id":"price-002","question":"问界M7新车延保产品有哪些价格档位?","expected_answer":"应列出问界M7新车延保相关价格档位,所有金额必须来自资料。","expected_source_keywords":["问界M7","新车","延保"],"expected_file_names":["鸿蒙智行官方服务产品价格总览.pdf"],"tags":["price","product","table"]}
{"id":"manual-001","question":"辅助驾驶无忧服务的除外责任有哪些?","expected_answer":"应回答辅助驾驶无忧服务手册中的除外责任条款。","expected_source_keywords":["除外责任","辅助驾驶无忧"],"expected_file_names":["鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf"],"tags":["policy","manual"]}
{"id":"manual-002","question":"辅助驾驶无忧服务包含什么保障内容?","expected_answer":"应回答服务保障内容,不应因为缺少车型而追问。","expected_source_keywords":["辅助驾驶无忧","保障"],"expected_file_names":["鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf"],"tags":["product","manual"]}
{"id":"hybrid-001","question":"智界S7在用车电池延保价格和免责条款分别是什么?","expected_answer":"应同时召回价格总览和无忧服务手册/条款相关资料,回答中应有内联引用。","expected_source_keywords":["智界S7","在用车","电池延保","免责"],"expected_file_names":["鸿蒙智行官方服务产品价格总览.pdf","鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf"],"tags":["multi_intent","price","policy"]}
import argparse
import json
import math
import time
from pathlib import Path
import requests
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--dataset", required=True)
parser.add_argument("--api", default="http://localhost:8104")
parser.add_argument("--out", default="logs/rag_eval_result.json")
args = parser.parse_args()
items = [json.loads(line) for line in Path(args.dataset).read_text(encoding="utf-8").splitlines() if line.strip()]
results = []
for item in items:
start = time.time()
resp = requests.post(
f"{args.api.rstrip('/')}/rag/query/json",
json={"query": item["question"], "history": item.get("history", []), "sessionId": f"eval-{item['id']}"},
timeout=120,
)
resp.raise_for_status()
data = resp.json()
metrics = score_item(item, data)
metrics["latency_ms"] = int((time.time() - start) * 1000)
results.append({"id": item["id"], "question": item["question"], "answer": data.get("answer", ""), "sources": data.get("sources", []), "metrics": metrics})
print(f"{item['id']} {metrics}")
summary = summarize(results)
output = {"summary": summary, "items": results}
out_path = Path(args.out)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(output, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps(summary, ensure_ascii=False, indent=2))
def score_item(expected: dict, response: dict) -> dict:
answer = response.get("answer", "")
sources = response.get("sources", [])
source_names = [s.get("source_name", "") for s in sources]
source_text = "\n".join(s.get("content", "") for s in sources)
expected_files = [x for x in expected.get("expected_file_names", []) if x and not str(x).startswith("请填写")]
expected_keywords = [x for x in expected.get("expected_source_keywords", []) if x]
expected_answer = expected.get("expected_answer", "")
file_hit_positions = [idx + 1 for idx, source in enumerate(source_names) for f in expected_files if f in source]
file_hits = len(set(file_hit_positions))
keyword_hits = sum(1 for kw in expected_keywords if kw in source_text or kw in answer)
context_recall = safe_div(file_hits + keyword_hits, len(expected_files) + len(expected_keywords))
context_precision = safe_div(file_hits + keyword_hits, max(1, len(source_names) + len(expected_keywords)))
answer_relevancy = keyword_overlap(expected_answer, answer) if expected_answer and not expected_answer.startswith("请填写") else safe_div(keyword_hits, max(1, len(expected_keywords)))
faithfulness = safe_div(sum(1 for sentence in sentences(answer) if sentence[:12] and sentence[:12] in source_text), max(1, len(sentences(answer))))
return {
"context_recall": round(context_recall, 4),
"context_precision": round(context_precision, 4),
"answer_relevancy": round(answer_relevancy, 4),
"faithfulness": round(faithfulness, 4),
"hit_rate": round(1.0 if file_hits or keyword_hits else 0.0, 4),
"mrr": round(1 / min(file_hit_positions) if file_hit_positions else (1.0 if keyword_hits else 0.0), 4),
"ndcg@5": round(ndcg_at_k(source_names, expected_files, 5), 4),
"source_keyword_recall": round(safe_div(keyword_hits, len(expected_keywords)), 4),
"answer_keyword_coverage": round(safe_div(sum(1 for kw in expected_keywords if kw in answer), len(expected_keywords)), 4),
}
def summarize(results: list[dict]) -> dict:
keys = ["context_recall", "context_precision", "answer_relevancy", "faithfulness", "hit_rate", "mrr", "ndcg@5", "source_keyword_recall", "answer_keyword_coverage", "latency_ms"]
return {key: round(sum(item["metrics"].get(key, 0) for item in results) / max(1, len(results)), 4) for key in keys} | {"count": len(results)}
def keyword_overlap(expected: str, actual: str) -> float:
words = [w for w in expected.replace(",", " ").replace("。", " ").replace("、", " ").split() if w]
return safe_div(sum(1 for w in words if w in actual), len(words))
def sentences(text: str) -> list[str]:
return [s.strip() for s in text.replace(";", "。").replace("!", "。").replace("?", "。").split("。") if s.strip()]
def ndcg_at_k(source_names: list[str], expected_files: list[str], k: int) -> float:
if not expected_files:
return 0.0
gains = [1.0 if any(expected in source for expected in expected_files) else 0.0 for source in source_names[:k]]
dcg = sum(gain / math.log(idx + 2, 2) for idx, gain in enumerate(gains))
ideal_hits = min(len(expected_files), k)
ideal = sum(1.0 / math.log(idx + 2, 2) for idx in range(ideal_hits))
return safe_div(dcg, ideal)
def safe_div(a: float, b: float) -> float:
return a / b if b else 0.0
if __name__ == "__main__":
main()
ALTER TABLE rag_query_logs
ADD COLUMN adopted_chunk_ids_json TEXT NULL AFTER retrieval_plan_json,
ADD COLUMN citation_map_json TEXT NULL AFTER adopted_chunk_ids_json;
ALTER TABLE rag_documents
ADD COLUMN error_code VARCHAR(100) NULL AFTER index_duration_ms,
ADD COLUMN error_detail_json LONGTEXT NULL AFTER error_code;
ALTER TABLE rag_index_runs
ADD COLUMN error_code VARCHAR(100) NULL AFTER duration_ms,
ADD COLUMN error_detail_json LONGTEXT NULL AFTER error_code;
-- 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;
DROP TABLE IF EXISTS rag_conversations;
DROP TABLE IF EXISTS rag_index_logs;
DROP TABLE IF EXISTS rag_eval_items;
DROP TABLE IF EXISTS rag_eval_runs;
-- 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,
vlm_page_count INT NOT NULL DEFAULT 0,
vlm_total_tokens INT NOT NULL DEFAULT 0,
vlm_duration_ms INT NOT NULL DEFAULT 0,
error_code VARCHAR(100) NULL,
error_detail_json LONGTEXT NULL,
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),
INDEX idx_rag_documents_name_status (name, status),
INDEX idx_rag_documents_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
COMMENT='RAG 文档表,记录进入独立 RAG 索引的源文件及索引统计信息';
-- 精简切片表:只保留检索/邻居扩展/定位/UI 真正用到的列;
-- 其余结构化标签统一进 metadata_json。检索过滤/打分走 Qdrant payload,不读这些列。
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,
page_start INT NULL,
page_end INT NULL,
row_start INT NULL,
row_end INT NULL,
prev_chunk_id VARCHAR(64) NULL,
next_chunk_id VARCHAR(64) NULL,
status VARCHAR(50) NOT NULL DEFAULT 'active',
brand_series VARCHAR(100) NULL,
business_category VARCHAR(100) NULL,
content_kind VARCHAR(50) NULL,
section_title VARCHAR(255) NULL,
parse_status VARCHAR(50) NULL,
qdrant_point_id VARCHAR(64) 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_document_level_index (document_id, chunk_level, chunk_index),
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),
INDEX idx_rag_chunks_brand (brand_series),
INDEX idx_rag_chunks_source_loc (page_start, page_end)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
COMMENT='RAG 切片表,保存文档切片内容、层级关系、定位信息和轻量检索字段';
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,
vlm_page_count INT NOT NULL DEFAULT 0,
vlm_total_tokens INT NOT NULL DEFAULT 0,
error_code VARCHAR(100) NULL,
error_detail_json LONGTEXT NULL,
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
COMMENT='RAG 索引任务运行记录表,保存每次索引执行的统计和错误信息';
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),
INDEX idx_rag_query_logs_session_status_created (session_id, status, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
COMMENT='RAG 查询日志表,记录用户查询、改写、检索过程、引用和回答结果';
...@@ -4,7 +4,7 @@ description: | ...@@ -4,7 +4,7 @@ description: |
触发场景:用户说"摄入"/"处理来源"/"添加新资料"/"把这个文档加到知识库" 触发场景:用户说"摄入"/"处理来源"/"添加新资料"/"把这个文档加到知识库"
适配岗位 Agent 业务知识库(汽车后市场 × 50+ 品牌),不适用于个人技术知识库。 适配岗位 Agent 业务知识库(汽车后市场 × 50+ 品牌),不适用于个人技术知识库。
一次完整摄入 = 1 个 sources 摘要 + 0..N 个下游页面(按 10 种 type 路由产出)。 一次完整摄入 = 1 个 sources 摘要 + 0..N 个下游页面(按 10 种 type 路由产出)。
关键约束:10 种页面类型、强 schema 校验、10 维标签体系、品牌严格枚举、强制打标、延保话术合规校验。 关键约束:10 种页面类型、强 schema 校验、5 维结构化过滤字段(series/brand/business_category/sub_business/role)+ 自由 tags、slug 全局唯一与规范命名、品牌严格枚举、强制打标、延保话术合规校验。
不做:矛盾扫描(Q7 决策,移交 llm-lint)。 不做:矛盾扫描(Q7 决策,移交 llm-lint)。
--- ---
...@@ -49,28 +49,45 @@ description: | ...@@ -49,28 +49,45 @@ description: |
完成分析后,你(Planner角色)**必须直接输出 JSON 结构**,供下游并发处理,例: 完成分析后,你(Planner角色)**必须直接输出 JSON 结构**,供下游并发处理,例:
```json ```json
{ {
"global_tags": ["鸿蒙智行", "鸿蒙智行", "权益类", "延保", "驻店销售"], "global_dims": {
"series": "鸿蒙智行",
"brand": ["问界", "智界", "享界", "尊界", "尚界"],
"business_category": "权益类",
"sub_business": "售后延保",
"role": ["驻店销售"]
},
"pages": [ "pages": [
{ {
"type": "sources", "type": "sources",
"slug": "产品手册", "slug": "鸿蒙智行官方延保产品手册",
"file_path": "ware/wiki/sources/鸿蒙智行/产品手册.md", "file_path": "ware/wiki/sources/鸿蒙智行/鸿蒙智行官方延保产品手册.md",
"title": "产品手册", "title": "鸿蒙智行官方延保产品手册",
"related_links": ["[[ware/wiki/products/整车延保.md]]"], "related_links": ["[[鸿蒙智行官方延保]]"],
"source_content_range": "全局摘要" "source_content_range": "全局摘要"
}, },
{ {
"type": "products", "type": "products",
"slug": "整车延保", "slug": "鸿蒙智行官方延保",
"file_path": "ware/wiki/products/整车延保.md", "file_path": "ware/wiki/products/鸿蒙智行官方延保.md",
"title": "整车延保", "title": "鸿蒙智行官方延保",
"related_links": ["[[ware/wiki/sources/鸿蒙智行/产品手册.md]]"], "related_links": ["[[鸿蒙智行官方延保产品手册]]"],
"source_content_range": "从第1章到第2章的保修范围" "source_content_range": "从第1章到第2章的保修范围"
} }
] ]
} }
``` ```
**关键约束**:每个页面的 `source_content_range` 必须互斥,不允许分配重叠的原文段落,以彻底杜绝并发生成的页面内容重叠! **关键约束**:
- `global_dims` 是 5 个结构化过滤维度(不再是扁平 5 元数组):`series`(单值)、`brand`(列表)、`business_category`(单值)、`sub_business`(单值)、`role`(列表)。不确定填「未知[待确认]」,基线外品牌附「[待审批]」。
- `source_content_range` **按主题归集,不按物理位置/页码切分**:同一主题/产品的内容(即使跨页、分散、或分成常规价表 + 限时礼惠/赠送/活动等多个子表)必须整体归入同一页;务必覆盖原文每一处,**不要遗漏页边/跨页/表格末尾的零散行**。各页主题尽量不重叠,但**完整性优先**——宁可完整归入最相关页,也不要让内容落空。
**2.3 规范命名规则(杜绝同义碎片化,极重要)**
slug 必须按「**作用域实体 + 产品线/主题**」命名,并保证 **全局唯一**:
- **系列级产品**(一个产品跨多个同系品牌,如鸿蒙智行官方延保覆盖问界/智界/享界/尊界/尚界)→ **按品牌系列建一页**,slug=`{品牌系列}{产品线}`(如 `鸿蒙智行官方延保`),各车型价格/参数在**页内分节**,`brand` 字段列全部适用品牌。
- **单品牌产品** → **按品牌建页**,slug=`{品牌}{产品线}`(如 `岚图整车延保`)。
- 实体/政策/流程/话术同理带作用域前缀,**严禁裸名**(不要 `整车延保`,要 `岚图整车延保` 或 `鸿蒙智行官方延保`)。
- **复用优先**:系统会把现有页面注册表注入你的上下文;若已存在描述同一真实产品/实体的页面,**直接复用其 slug**(系统会自动把本次内容合并入既有页面)。
- **slug 全局唯一**:同一 slug 全库只对应一个页面;同一 slug 再次出现(哪怕来自不同来源文件)会**合并**进既有页面,仅当与**不同 type** 的页面撞名才会被打回。
- **目录结构(扁平)**:`file_path` 一律——**只有 sources 用 `ware/wiki/sources/{品牌系列}/{slug}.md`,其余所有 type 一律 `ware/wiki/{type}/{slug}.md`,不加任何品牌/系列子目录**(系统会强制按此归一化路径)。
## Step 3:页面规范写作 (Phase 2: Concurrent Writing) ## Step 3:页面规范写作 (Phase 2: Concurrent Writing)
...@@ -84,18 +101,17 @@ description: | ...@@ -84,18 +101,17 @@ description: |
**3.1 YAML frontmatter 结构(必须严格遵循)** **3.1 YAML frontmatter 结构(必须严格遵循)**
每个 wiki 页面必须以下列 YAML frontmatter 开头。**缺少任何一个共有字段会被 Python 网关直接打回重试**。 每个 wiki 页面必须以下列 YAML frontmatter 开头。**缺少任何一个共有字段会被 Python 网关直接打回重试**。
共有字段模板(8 个,全部必填): 共有字段模板(12 个,全部必填):
```yaml ```yaml
--- ---
schema_version: v1.3 schema_version: v1.3
type: <entities|products|concepts|procedures|scripts|policies|comparisons|troubleshooting|sources|synthesis> type: <entities|products|concepts|procedures|scripts|policies|comparisons|troubleshooting|sources|synthesis>
title: <页面标题,中文> title: <页面标题,中文>
tags: series: <品牌系列,单值,无系列填 通用品牌>
- <品牌名> brand: [<品牌1>, <品牌2>] # 列表;系列级产品列全部适用品牌
- <品牌系列> business_category: <业务大类,单值:轻改类 | 权益类 | 二手车类>
- <业务大类> sub_business: <子业务,单值>
- <子业务> role: [<岗位>] # 列表;面向所有岗位用 [通用]
- <岗位>
related: related:
- <相关页面slug1> - <相关页面slug1>
- <相关页面slug2> - <相关页面slug2>
...@@ -103,30 +119,35 @@ sources: ...@@ -103,30 +119,35 @@ sources:
- <raw文件相对路径> - <raw文件相对路径>
created: YYYY-MM-DD created: YYYY-MM-DD
updated: YYYY-MM-DD updated: YYYY-MM-DD
tags: [] # 可选,自由检索标注,见 3.2
--- ---
``` ```
⚠️ 各 type 的额外必填字段请严格参照注入到你上下文中的 `schema-summary.md` 和 `golden-examples.md`。 > `series/brand/business_category/sub_business/role` 必须使用规划阶段「全局锁定」的 5 维值。
⚠️ 各 type 的额外必填字段(如 entity 的 `brand`/`entity_type`、product 的额外字段、script 的 `scenario`/`script_type`/`skill_tag` 等)请严格参照注入到你上下文中的 `schema-summary.md` 和 `golden-examples.md`。
**3.2 tags 标注指引(可选、自由标注)**
`tags[]` **不再承载 5 维过滤维度**(那些已是上面的结构化字段)。tags 仅用于**横切检索关键词**,从下列建议词表中挑选合适的,没有就写 `tags: []`:
- 功能场景:`异议处理`、`产品参数`、`质保政策`、`合规红线`、`系统排障`、`促销活动`、`客户分类`、`销售技巧`
- 辅助标签:`FAQ`、`错误码`、`案例研究`、`对比分析`
- 允许在词表基础上自由补充贴切的检索词;**必须去重**;**严禁**把品牌/系列/业务大类/子业务/岗位塞进 tags。
## Step 4:建立交叉引用 ## Step 4:建立交叉引用
- **必须带全路径** wikilink:`[[ware/wiki/路径/xxx.md]]` ✅ - **必须用 slug 简写** wikilink:`[[页面slug]]` ✅(如 `[[岚图整车延保]]`)
- **禁止使用简写** wikilink:`[[页面slug]]` ❌ - **禁止全路径/带后缀** wikilink:`[[ware/wiki/路径/xxx.md]]` ❌
- slug 全局唯一,故简写无歧义;`related` 字段与正文链接均使用 slug。
- **引用范围收紧**(避免过度引用): - **引用范围收紧**(避免过度引用):
- 只能引用在你的 `source_content_range` 内明确提到过的事物。 - 只能引用在你的 `source_content_range` 内明确提到过的事物。
- 所创建的所有双向链接 `[[页面名称]]` 必须限制在分配给你的 `related_links` 列表内。 - 所创建的所有双向链接 `[[页面slug]]` 必须限制在分配给你的 `related_links` 列表内。
## Step 5:系统自动保存与同步 (Phase 3) ## Step 5:系统自动保存与同步 (Phase 3)
**无需你执行!** **无需你执行!**
- Python 脚本会自动将你合格的输出保存到目标路径。 - Python 脚本会自动将你合格的输出保存到目标路径。
- 如果文件已存在,Python 脚本会自动执行内容追加 (Append)。 - 如果目标页已存在:同一来源的 SOURCE 块会被**替换**、不同来源的内容会**合并**(按 `field_sources` 统一溯源)。
- Python 脚本会自动更新 `ware/wiki/index.md` 和 `ware/wiki/log.md`。 - Python 脚本会按 type 分组**确定性全量重建** `ware/wiki/index.md`,并追加 `ware/wiki/log.md`。
**index.md 写入格式**(v2.0,符合 lint 1.5 要求): **index.md 由系统全量重建**(你无需关心格式):按页面 frontmatter 的 `type` 分组、组内按 `series/brand` 排序,每行 `- [[slug]] — 标题`。
```
- [[page-slug]] — 页面标题
```
> 注意:使用 em dash(`—`)而非双横线(`--`),使用 slug(文件名不含路径和 .md)而非路径格式。
**log.md 写入格式**(v2.0,包含 wikilink 数量,供 lint 增量模式使用): **log.md 写入格式**(v2.0,包含 wikilink 数量,供 lint 增量模式使用):
``` ```
...@@ -139,7 +160,7 @@ updated: YYYY-MM-DD ...@@ -139,7 +160,7 @@ updated: YYYY-MM-DD
## 关键约束(再次强调) ## 关键约束(再次强调)
1. **强 schema 校验移交 Python**:缺失字段、带 think 标签会被自动拦截并要求你重写,请一次写对。 1. **强 schema 校验移交 Python**:缺失字段、带 think 标签会被自动拦截并要求你重写,请一次写对。
2. **专属领地(防重叠)**:Writer 只能写自己被分配到的 `source_content_range`,即使原文有其他丰富内容,只要不属于你,**绝不触碰**。 2. **按主题完整归集(防跨页丢失)**:Writer 以**主题归属**判断内容归属,**不以原文物理位置/页码判断**。凡属于本页主题的内容,无论跨页、分散、还是分成常规价表 + 限时礼惠/赠送/活动等多个子表,**全部纳入**(页边/跨页/表末零散行最易遗漏,务必收齐);不属于本主题的不写,避免重复展开同一事实。完整性优先于不重叠。
3. **单一信息源原则**(Wiki 核心理念): 3. **单一信息源原则**(Wiki 核心理念):
- 每条业务事实**只在一个页面中完整展开**。 - 每条业务事实**只在一个页面中完整展开**。
- 具体规则:除外责任/享权前提在 policies 页展开,理赔流程在 procedures 页展开,产品赔付表格、价格明细和 SKU 清单在 products 页完整展开。**注意:Wiki 数据库对价格、数字和型号极度敏感,绝对不能精简或省略价格表、金额、年限、里程等核心数值,必须在页面中提供全量数据**。 - 具体规则:除外责任/享权前提在 policies 页展开,理赔流程在 procedures 页展开,产品赔付表格、价格明细和 SKU 清单在 products 页完整展开。**注意:Wiki 数据库对价格、数字和型号极度敏感,绝对不能精简或省略价格表、金额、年限、里程等核心数值,必须在页面中提供全量数据**。
......
...@@ -9,31 +9,32 @@ ...@@ -9,31 +9,32 @@
**输入片段**: **输入片段**:
> "鸿蒙智行辅助驾驶无忧服务产品包含整车延保服务。在原厂质保期满后,提供额外1年或3万公里的保修服务。除外责任包括:1. 易损件正常磨损;2. 人为损坏;3. 未在授权中心保养导致的故障... (共17条)。" > "鸿蒙智行辅助驾驶无忧服务产品包含整车延保服务。在原厂质保期满后,提供额外1年或3万公里的保修服务。除外责任包括:1. 易损件正常磨损;2. 人为损坏;3. 未在授权中心保养导致的故障... (共17条)。"
**输出页面** (`ware/wiki/products/整车延保.md`): **输出页面** (`ware/wiki/products/鸿蒙智行辅助驾驶无忧延保.md`):
```markdown ```markdown
--- ---
schema_version: v1.3 schema_version: v1.3
type: products type: products
title: 整车延保 title: 鸿蒙智行辅助驾驶无忧延保
tags: series: 鸿蒙智行
brand:
- 问界 - 问界
- 鸿蒙智行 business_category: 权益类
- 权益类 sub_business: 售前延保
- 售前延保 role:
- 驻店销售 - 驻店销售
related: related:
- 辅助驾驶无忧服务产品手册 - 鸿蒙智行辅助驾驶无忧服务产品手册
- 延保免责条款 - 鸿蒙智行延保免责条款
sources: sources:
- raw/鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf - ware/raw/鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf
created: 2026-06-09 created: 2026-06-09
updated: 2026-06-09 updated: 2026-06-09
business_category: 权益类 tags:
sub_business: 售前延保 - 产品参数
--- ---
# 整车延保 # 鸿蒙智行辅助驾驶无忧延保
整车延保是鸿蒙智行辅助驾驶无忧服务产品之一,旨在原厂质保期满后,为车主提供延长保修服务。 整车延保是鸿蒙智行辅助驾驶无忧服务产品之一,旨在原厂质保期满后,为车主提供延长保修服务。
...@@ -46,9 +47,9 @@ sub_business: 售前延保 ...@@ -46,9 +47,9 @@ sub_business: 售前延保
## 除外责任 ## 除外责任
> 本产品存在 17 条除外责任(如易损件正常磨损、人为损坏等)。 > 本产品存在 17 条除外责任(如易损件正常磨损、人为损坏等)。
> **详细条款请参见:** [[ware/wiki/policies/延保免责条款.md]] > **详细条款请参见:** [[鸿蒙智行延保免责条款]]
``` ```
*(注意:严格遵循单一信息源原则,产品页不铺陈 17 条除外责任,而是使用 wikilink 引用 policy 页面。但在涉及价格明细、年限里程、保费金额等核心数值与表格时,必须 100% 全量保留,绝不可省略。)* *(注意:① 单一信息源——产品页不铺陈 17 条除外责任,而用 slug wikilink 引用 policy 页;价格/年限/里程等核心数值与表格必须 100% 全量保留。② slug 用「作用域+产品线」命名,避免裸名「整车延保」;wikilink 一律 slug 简写。)*
--- ---
...@@ -56,30 +57,32 @@ sub_business: 售前延保 ...@@ -56,30 +57,32 @@ sub_business: 售前延保
**输入片段**:整个《鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf》 **输入片段**:整个《鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf》
**输出页面** (`ware/wiki/sources/鸿蒙智行/辅助驾驶无忧服务产品手册.md`): **输出页面** (`ware/wiki/sources/鸿蒙智行/鸿蒙智行辅助驾驶无忧服务产品手册.md`):
```markdown ```markdown
--- ---
schema_version: v1.3 schema_version: v1.3
type: sources type: sources
title: 辅助驾驶无忧服务产品手册 title: 鸿蒙智行辅助驾驶无忧服务产品手册
tags: series: 鸿蒙智行
brand:
- 问界 - 问界
- 鸿蒙智行 business_category: 权益类
- 权益类 sub_business: 售前延保
- 售前延保 role:
- 通用 - 通用
related: related:
- 整车延保 - 鸿蒙智行辅助驾驶无忧延保
- 延保免责条款 - 鸿蒙智行延保免责条款
- 辅助驾驶功能定义与分类 - 辅助驾驶功能定义与分类
sources: sources:
- raw/鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf - ware/raw/鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf
created: 2026-06-09 created: 2026-06-09
updated: 2026-06-09 updated: 2026-06-09
tags: []
--- ---
# 辅助驾驶无忧服务产品手册 — 来源摘要 # 鸿蒙智行辅助驾驶无忧服务产品手册 — 来源摘要
## 来源基本信息 ## 来源基本信息
- 来源标题:鸿蒙智行辅助驾驶无忧服务产品手册 - 来源标题:鸿蒙智行辅助驾驶无忧服务产品手册
...@@ -93,18 +96,18 @@ updated: 2026-06-09 ...@@ -93,18 +96,18 @@ updated: 2026-06-09
## 下游页面导航 ## 下游页面导航
| type | 页面 | 一句话描述 | | type | 页面 | 一句话描述 |
|------|------|-----------| |------|------|-----------|
| products | [[ware/wiki/products/整车延保.md]] | 介绍延保服务的保障期限与范围 | | products | [[鸿蒙智行辅助驾驶无忧延保]] | 介绍延保服务的保障期限与范围 |
| policies | [[ware/wiki/policies/延保免责条款.md]] | 罗列 17 条延保服务的除外责任与合规红线 | | policies | [[鸿蒙智行延保免责条款]] | 罗列 17 条延保服务的除外责任与合规红线 |
| concepts | [[ware/wiki/concepts/辅助驾驶功能定义与分类.md]] | 梳理辅助驾驶的核心功能定义 | | concepts | [[辅助驾驶功能定义与分类]] | 梳理辅助驾驶的核心功能定义 |
## 关键数据速查 ## 关键数据速查
| 数据项 | 数值 | | 数据项 | 数值 |
|--------|------| |--------|------|
| 延保期限 | 1年/3万公里 | | 延保期限 | 1年/3万公里 |
> 原始依据:`raw/鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf` > 原始依据:`ware/raw/鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf`
``` ```
*(注意:Sources 页仅做极简摘要和导航表,绝不将源文件逐字展开。限制在 80 行以内。)* *(注意:Sources 页仅做极简摘要和导航表,绝不将源文件逐字展开,限制在 80 行以内;导航链接一律 slug 简写。)*
--- ---
...@@ -120,18 +123,21 @@ updated: 2026-06-09 ...@@ -120,18 +123,21 @@ updated: 2026-06-09
schema_version: v1.3 schema_version: v1.3
type: concepts type: concepts
title: 辅助驾驶功能定义与分类 title: 辅助驾驶功能定义与分类
tags: series: 鸿蒙智行
brand:
- 问界 - 问界
- 鸿蒙智行 business_category: 权益类
- 权益类 sub_business: 售前延保
- 售前延保 role:
- 驻店销售 - 驻店销售
related: related:
- 辅助驾驶无忧服务产品手册 - 鸿蒙智行辅助驾驶无忧服务产品手册
sources: sources:
- raw/鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf - ware/raw/鸿蒙智行辅助驾驶无忧服务产品手册260121.pdf
created: 2026-06-09 created: 2026-06-09
updated: 2026-06-09 updated: 2026-06-09
tags:
- 产品参数
--- ---
# 辅助驾驶功能定义与分类 # 辅助驾驶功能定义与分类
......
...@@ -18,7 +18,9 @@ ...@@ -18,7 +18,9 @@
| source | `wiki/sources/<品牌系列>/` | — | 品牌系列 + 来源类型 + 业务大类 | | source | `wiki/sources/<品牌系列>/` | — | 品牌系列 + 来源类型 + 业务大类 |
| synthesis | `wiki/synthesis/` | — | 品牌 + 业务大类 + 案例研究 | | synthesis | `wiki/synthesis/` | — | 品牌 + 业务大类 + 案例研究 |
> 8 个共有字段:`schema_version`, `type`, `title`, `tags`, `related`, `sources`, `created`, `updated` > 12 个共有字段(全部必填):`schema_version`, `type`, `title`, `series`, `brand`, `business_category`, `sub_business`, `role`, `related`, `sources`, `created`, `updated`
> `tags` 为可选自由检索标注(非必填,可为 `[]`)。
> 上表「推荐 tags 前缀」列为历史遗留语义参考;过滤维度现已是上面 5 个结构化字段,**不再塞进 tags**。
## YAML 模板 ## YAML 模板
...@@ -28,11 +30,16 @@ ...@@ -28,11 +30,16 @@
schema_version: v1.3 schema_version: v1.3
type: <10 种之一> type: <10 种之一>
title: "页面标题" title: "页面标题"
tags: [品牌, 品牌系列, 业务大类, 子业务, 岗位, ...] series: 鸿蒙智行 # 品牌系列,单值;无系列填 通用品牌
related: [slug, ...] brand: [问界, 智界] # 适用品牌,列表;系列级产品列全部
sources: [raw/sources/.../file.pdf] business_category: 权益类 # 业务大类,单值:轻改类 | 权益类 | 二手车类
sub_business: 售后延保 # 子业务,单值
role: [驻店销售] # 适用岗位,列表;面向所有岗位用 [通用]
related: [slug, ...] # slug 简写,禁止全路径/.md
sources: [ware/raw/file.pdf]
created: YYYY-MM-DD created: YYYY-MM-DD
updated: YYYY-MM-DD updated: YYYY-MM-DD
tags: [] # 可选自由标注:异议处理/合规红线/FAQ/错误码/案例研究 等
--- ---
``` ```
...@@ -72,12 +79,14 @@ error_code: "AMOUNT_EXCEED" # 可选 ...@@ -72,12 +79,14 @@ error_code: "AMOUNT_EXCEED" # 可选
## 常见错误清单 ## 常见错误清单
- ❌ `type` 与所在目录不一致(product 放进 `wiki/concepts/`) - ❌ `type` 与所在目录不一致(product 放进 `wiki/concepts/`)
- ❌ tags 缺品牌(鸿蒙智行品牌页必须含品牌名 + `鸿蒙智行`) - ❌ 缺少 5 维结构化字段之一(`series`/`brand`/`business_category`/`sub_business`/`role`)
- ❌ `brand`/`role` 写成字符串而非列表;`business_category` 非法值
- ❌ 把品牌/系列/业务/岗位塞进 `tags`(应放结构化字段,tags 仅自由检索标注)
- ❌ script 优秀/违规话术缺 `source_recording` - ❌ script 优秀/违规话术缺 `source_recording`
- ❌ policy 合规红线类缺 `violation_type` - ❌ policy 合规红线类缺 `violation_type`
- ❌ wikilink 简写(应使用全路径 `[[ware/wiki/路径/xxx.md]]`,严禁简写) - ❌ wikilink 用全路径或带 `.md`(应使用 slug 简写 `[[页面slug]]`)
- ❌ 裸名 slug 或撞名(应「作用域+产品线」命名且全局唯一)
- ❌ source 摘要页缺 `related[]` - ❌ source 摘要页缺 `related[]`
- ❌ tags 漏岗位维度(无 `驻店销售`/`通用`,查询无法按权限过滤)
- ❌ `schema_version` 不是 `v1.3` - ❌ `schema_version` 不是 `v1.3`
- ❌ `created` / `updated` 非 `YYYY-MM-DD` - ❌ `created` / `updated` 非 `YYYY-MM-DD`
......
...@@ -35,16 +35,25 @@ ...@@ -35,16 +35,25 @@
```yaml ```yaml
--- ---
schema_version: v1.3 # 生成时的 schema 版本,用于后续迁移 schema_version: v1.3 # 生成时的 schema 版本,用于后续迁移
type: entity | product | concept | procedure | script | policy | comparison | troubleshooting | source | synthesis type: entities | products | concepts | procedures | scripts | policies | comparisons | troubleshooting | sources | synthesis
title: "页面标题" title: "页面标题"
tags: [] # 见下方标签体系 series: 鸿蒙智行 # 【过滤维度】品牌系列,单值;无系列填 通用品牌
related: [] # 关联的其他页面 slug(不含 .md),如 ["问界M7", "整车延保"] brand: [问界, 智界] # 【过滤维度】适用品牌,列表;系列级产品列全部
sources: [] # 来源文档路径,如 ["raw/sources/sales/问界延保产品手册.pdf"] business_category: 权益类 # 【过滤维度】业务大类,单值:轻改类 | 权益类 | 二手车类
sub_business: 售后延保 # 【过滤维度】子业务,单值
role: [驻店销售] # 【过滤维度】适用岗位,列表;面向所有岗位用 [通用]
related: [] # 关联页面 slug(slug 简写,不含路径/.md),如 ["问界M7", "整车延保"]
sources: [] # 来源文档路径,如 ["ware/raw/问界延保产品手册.pdf"]
created: 2026-05-28 created: 2026-05-28
updated: 2026-05-28 updated: 2026-05-28
tags: [] # 可选,自由检索标注(功能场景/FAQ/错误码等),不再承载过滤维度
--- ---
``` ```
> **过滤维度结构化(v1.3)**:品牌/系列/业务大类/子业务/岗位这 5 个权限过滤维度,已从扁平 `tags[]` 升级为上面 5 个**独立结构化字段**(`series`/`brand`/`business_category`/`sub_business`/`role`),全部必填。`tags[]` 仅保留为自由检索标注。
> **type 取值**与目录一致,使用复数形式(`products`/`sources`/`entities` …)。
> **字段级溯源**:多源合并的页面,每个受追踪字段的来源记录在 `field_sources` 中;摄出按来源回收,保证无残留。
当 schema 更新到新版本时,告知 Claude Code: 当 schema 更新到新版本时,告知 Claude Code:
"搜 `schema_version` 不是最新版本的页面,按新 schema.md 重新打标并进行迁移。" "搜 `schema_version` 不是最新版本的页面,按新 schema.md 重新打标并进行迁移。"
...@@ -93,27 +102,29 @@ effective_date: "2026-01-01" # 生效日期(可选) ...@@ -93,27 +102,29 @@ effective_date: "2026-01-01" # 生效日期(可选)
## 标签体系 ## 标签体系
### 标签维度 > **重要(v1.3)**:下表前 5 个维度(品牌/品牌系列/业务大类/子业务/岗位)现已是 frontmatter 的**独立结构化字段** `brand`/`series`/`business_category`/`sub_business`/`role`,**不再写入 `tags[]`**。下表的取值枚举与半受控规则继续适用于这些结构化字段。其余维度(异议场景、话术性质、话术技巧等)按 type 进各自的专属字段,纯横切检索词才进 `tags[]`。
| 维度 | 规则 | 示例值 | ### 维度取值规则
|------|------|--------|
| **品牌** | 半受控:已知品牌用枚举值,LLM 可新增但须在 log.md 标记 `⚠️ 新品牌待确认` | `问界`、`享界`、`智界`、`尊界`、`尚界`、`岚图`、`零跑`、`丰田`、`比亚迪` 等(完整列表见下方) | | 维度 | 对应字段 | 规则 | 示例值 |
| **品牌系列** | 可选,标注品牌归属的系列/厂商 | `鸿蒙智行`(覆盖问界/享界/智界/尊界/尚界)、`通用品牌`(其他所有非鸿蒙品牌) | |------|------|------|--------|
| **业务大类** | 必选其一 | `轻改类`、`权益类`、`二手车类` | | **品牌** | `brand`(列表)| 半受控:已知品牌用枚举值,LLM 可新增但须在 log.md 标记 `⚠️ 新品牌待确认` | `问界`、`享界`、`智界`、`尊界`、`尚界`、`岚图`、`零跑`、`丰田`、`比亚迪` 等(完整列表见下方) |
| **子业务** | 轻改按产品标记;权益按场景标记;二手车按本质标记 | 见下方完整列表 | | **品牌系列** | `series`(单值)| 标注品牌归属的系列/厂商 | `鸿蒙智行`(覆盖问界/享界/智界/尊界/尚界)、`通用品牌`(其他所有非鸿蒙品牌) |
| **岗位/角色** | 按目标用户标记(权限过滤的核心维度) | `驻店销售`、`区域运营`、`区域督导`、`业务经理`、`线上运营`、`产品经理`、`总部管理` | | **业务大类** | `business_category`(单值)| 必选其一 | `轻改类`、`权益类`、`二手车类` |
| **异议场景** | 话术中客户的核心异议类型 | `价格敏感`、`价值怀疑`、`赠品防御`、`积分变现`、`周期焦虑`、`质保够用`、`条款信任`、`拖延观望` | | **子业务** | `sub_business`(单值)| 轻改按产品标记;权益按场景标记;二手车按本质标记 | 见下方完整列表 |
| **话术性质** | 仅 script 类型使用,区分话术合规性 | `优秀话术`(轻改萃取)、`合规话术`(延保过审)、`违规话术`(延保红线) | | **岗位/角色** | `role`(列表)| 按目标用户标记(权限过滤的核心维度) | `驻店销售`、`区域运营`、`区域督导`、`业务经理`、`线上运营`、`产品经理`、`总部管理` |
| **话术技巧** | 优秀/合规话术中运用的方法标签 | `算账法`、`锚点法`、`风险放大`、`框架转换`、`利益同盟`、`坦诚接纳`、`以退为进`、`损失厌恶` | | **异议场景** | script 的 `objection_type` | 话术中客户的核心异议类型 | `价格敏感`、`价值怀疑`、`赠品防御`、`积分变现`、`周期焦虑`、`质保够用`、`条款信任`、`拖延观望` |
| **功能场景** | 按内容标记,可多个 | `异议处理`、`产品参数`、`质保政策`、`合规红线`、`系统排障`、`促销活动`、`客户分类`、`销售技巧` | | **话术性质** | script 的 `script_type` | 仅 script 类型使用,区分话术合规性 | `优秀话术`(轻改萃取)、`合规话术`(延保过审)、`违规话术`(延保红线) |
| **页面类型标签** | 按内容标记,辅助检索 | `对比分析`、`案例研究`、`FAQ`、`错误码` | | **话术技巧** | script 的 `skill_tag` | 优秀/合规话术中运用的方法标签 | `算账法`、`锚点法`、`风险放大`、`框架转换`、`利益同盟`、`坦诚接纳`、`以退为进`、`损失厌恶` |
| **功能场景** | `tags[]` | 按内容标记,可多个 | `异议处理`、`产品参数`、`质保政策`、`合规红线`、`系统排障`、`促销活动`、`客户分类`、`销售技巧` |
| **页面类型标签** | `tags[]` | 按内容标记,辅助检索 | `对比分析`、`案例研究`、`FAQ`、`错误码` |
### 标签规则 ### 标签规则
1. `brand` 字段(entity 专属)与 tags 中的品牌标签必须一致 1. `brand` 字段值必须与文档实际适用品牌一致(entity 页 brand 与正文主体一致)
2. `business_category` 字段(product 专属)与 tags 中的业务大类标签必须一致 2. `business_category` 字段必须取 `轻改类 | 权益类 | 二手车类` 之一
3. 岗位标签可按实际适用范围多选。若内容面向所有岗位,使用 `通用` 标签替代 3. `role` 可按实际适用范围多选。若内容面向所有岗位,使用 `通用`
4. 品牌标签半受控:LLM 遇到文档中的新品牌,可自动新增标签,但同时须在 `ware/wiki/log.md` 中记录 `⚠️ 新品牌待确认:[品牌名]` 4. 品牌半受控:LLM 遇到文档中的新品牌,可自动新增,但同时须在 `ware/wiki/log.md` 中记录 `⚠️ 新品牌待确认:[品牌名]`
### 当前已知品牌列表(受控基线) ### 当前已知品牌列表(受控基线)
......
...@@ -62,38 +62,25 @@ description: | ...@@ -62,38 +62,25 @@ description: |
--- ---
## Step 1:精准定位 ## Step 1:精准定位(务必收敛,尽量少调用工具)
使用提供的文件检索工具进行搜索,注意 `ware/wiki/` 目录结构。 ### 1.1 据「知识库地图」直接定位(不要再读 index.md)
`ware/wiki/index.md` 的完整内容**已由系统注入到你的提示词**(按 type 分组、`- [[slug]] — 标题`)。
**禁止再用 `read_local_file` 读取 index.md**。直接从地图里挑出与意图/品牌最相关的目标 slug。
### 1.1 读取 index.md 了解整体结构 ### 1.2 直接拼路径读取目标页(优先,≤3 个)
据 slug 直接拼出物理路径并读取,避免无谓搜索:
```python ```python
read_local_file(file_path="ware/wiki/index.md") # 一般类型:ware/wiki/<type>/<slug>.md
``` read_local_file(file_path="ware/wiki/scripts/客户嫌贵应对话术.md")
# 来源摘要:ware/wiki/sources/<品牌系列>/<slug>.md(系列不确定时用 glob 定位)
### 1.2 在目标目录内精准搜索(优先) glob_wiki_files(pattern="ware/wiki/sources/**/某来源.md")
基于 Step 0 路由的目录,在目标范围内搜索:
```python
# 列出目标目录下所有文件
glob_wiki_files(pattern="ware/wiki/scripts/*.md")
# 在目标目录内搜索关键词
grep_wiki_files(pattern="关键词", path_prefix="ware/wiki/scripts")
# 附加品牌过滤验证(确认命中页面属于正确品牌)
grep_wiki_files(pattern="品牌名", path_prefix="ware/wiki/scripts")
```
### 1.3 备用:全局关键词搜索(降级策略)
如果目标目录未命中,降级到全库搜索:
```python
grep_wiki_files(pattern="关键词", path_prefix="ware/wiki")
``` ```
### 1.4 反向链接查询(补充关联页面) ### 1.3 兜底:关键词搜索(仅在据图无法定位 / 找正文具体数值时)
查找哪些页面引用了命中的页面(用于二跳扩展):
```python ```python
grep_wiki_files(pattern="页面slug或标题关键词", path_prefix="ware/wiki") grep_wiki_files(pattern="关键词", path_prefix="ware/wiki/scripts") # 限定目录优先
grep_wiki_files(pattern="关键词", path_prefix="ware/wiki") # 再降级全库
``` ```
--- ---
...@@ -106,12 +93,12 @@ read_local_file(file_path="ware/wiki/scripts/客户嫌贵应对话术.md") ...@@ -106,12 +93,12 @@ read_local_file(file_path="ware/wiki/scripts/客户嫌贵应对话术.md")
``` ```
阅读时注意 YAML frontmatter 中的关键字段: 阅读时注意 YAML frontmatter 中的关键字段:
- `tags`:验证品牌/岗位是否与用户上下文匹配 - `brand`(列表) / `series` / `business_category` / `role`:**结构化过滤维度**,核对是否与用户所属品牌/业务/岗位一致,**严禁跨品牌混淆**(不要再用 `tags` 判品牌/岗位,tags 现仅为横切检索标注)。
- `related`:记录需要二跳的关联 slug 列表 - `related`:记录需要二跳的关联 slug 列表
- `type`:确认页面类型,用于 Step 3 选择回答格式 - `type`:确认页面类型,用于 Step 3 选择回答格式
### 2.2 强制二跳扩展规则(按命中 type) ### 2.2 二跳扩展规则(按命中 type,仅在确有必要时)
读完命中页面后,**按以下规则决定是否扩展**,控制在 **最多 5 个页面**以内: 读完命中页面后,**按以下规则决定是否扩展**,全程读取总数控制在 **≤3 个主页面 + 必要二跳**:
| 命中 type | 强制二跳读取 | 说明 | | 命中 type | 强制二跳读取 | 说明 |
|-----------|-------------|------| |-----------|-------------|------|
...@@ -122,10 +109,9 @@ read_local_file(file_path="ware/wiki/scripts/客户嫌贵应对话术.md") ...@@ -122,10 +109,9 @@ read_local_file(file_path="ware/wiki/scripts/客户嫌贵应对话术.md")
| **policies(政策)** | 关联的 `products/` 或 `procedures/` | 补充实际操作场景 | | **policies(政策)** | 关联的 `products/` 或 `procedures/` | 补充实际操作场景 |
| **concepts(概念)** | 关联的 `scripts/` 或 `products/` | 补充实际应用示例 | | **concepts(概念)** | 关联的 `scripts/` 或 `products/` | 补充实际应用示例 |
二跳扩展操作示例: 二跳扩展操作示例(直接据 related slug 拼路径读取,不用 grep):
```python ```python
# 提取 related 字段中的词并在 wiki 中检索定位文件后读取 # related 含 "算账法"(concepts 类)→ 直接读
grep_wiki_files(pattern="算账法", path_prefix="ware/wiki")
read_local_file(file_path="ware/wiki/concepts/算账法.md") read_local_file(file_path="ware/wiki/concepts/算账法.md")
``` ```
......
...@@ -4,7 +4,7 @@ import logging ...@@ -4,7 +4,7 @@ import logging
import os import os
import re import re
import time import time
from dataclasses import dataclass, field from dataclasses import dataclass
from datetime import datetime from datetime import datetime
from typing import Any from typing import Any
...@@ -16,7 +16,7 @@ from agentscope.formatter import DashScopeChatFormatter ...@@ -16,7 +16,7 @@ from agentscope.formatter import DashScopeChatFormatter
from agentscope.message import Msg from agentscope.message import Msg
from agentscope.tool import Toolkit from agentscope.tool import Toolkit
from config import QUERY_MODEL_NAME from config import QUERY_MODEL_NAME, WIKI_DIR
from src.database.models import WikiQueryLog from src.database.models import WikiQueryLog
from src.database.session import AsyncSessionLocal from src.database.session import AsyncSessionLocal
from src.tools.wiki_tools import glob_wiki_files, grep_wiki_files, read_local_file from src.tools.wiki_tools import glob_wiki_files, grep_wiki_files, read_local_file
...@@ -40,7 +40,6 @@ class WikiQueryResult: ...@@ -40,7 +40,6 @@ class WikiQueryResult:
duration_ms: int # 查询总耗时(毫秒) duration_ms: int # 查询总耗时(毫秒)
status: str = "Success" # 执行状态(Success, Error, Timeout, EmptyAnswer) status: str = "Success" # 执行状态(Success, Error, Timeout, EmptyAnswer)
error: str | None = None # 错误信息(如果有) error: str | None = None # 错误信息(如果有)
reasoning: list[dict[str, Any]] = field(default_factory=list) # Agent 的执行推理过程事件流记录
async def save_query_log_to_db( async def save_query_log_to_db(
...@@ -145,19 +144,36 @@ async def wiki_query_json_endpoint(data: dict = Body(...)): ...@@ -145,19 +144,36 @@ async def wiki_query_json_endpoint(data: dict = Body(...)):
} }
def load_index_map() -> str:
"""读取 ware/wiki/index.md 作为「知识库地图」注入系统提示词。
index.md 由摄入/维护流程按 type 分组确定性重建(`- [[slug]] — title`),
提前注入可让 Agent 直接据图定位 slug,省去「读 index / 先盲 grep」的往返。
"""
index_path = os.path.join(WIKI_DIR, "index.md")
if not os.path.exists(index_path):
return "(知识库地图为空:index.md 不存在)"
try:
with open(index_path, "r", encoding="utf-8", errors="replace") as f:
return f.read().strip()
except Exception as exc:
logger.warning("读取 index.md 失败: %s", exc)
return "(知识库地图读取失败)"
def build_query_agent(history: list) -> ReActAgent: def build_query_agent(history: list) -> ReActAgent:
""" """
构建并配置用于检索 Wiki 的 AgentScope ReAct 智能体。 构建并配置用于检索 Wiki 的 AgentScope ReAct 智能体。
为智能体装载本地文件读取和搜索工具,并注入特定业务的 System Prompt。 为智能体装载本地文件读取和搜索工具,注入「知识库地图」与业务 System Prompt。
""" """
toolkit = Toolkit() toolkit = Toolkit()
# 注册智能体可使用的工具 # 注册智能体可使用的工具
toolkit.register_tool_function(grep_wiki_files) # 全文正则搜索 toolkit.register_tool_function(read_local_file) # 读取页面内容(主用)
toolkit.register_tool_function(glob_wiki_files) # 文件名匹配搜索 toolkit.register_tool_function(glob_wiki_files) # 文件名匹配(定位路径)
toolkit.register_tool_function(read_local_file) # 读取文件内容 toolkit.register_tool_function(grep_wiki_files) # 全文正则搜索(兜底)
# 加载针对 llm-query 定制的提示词片段 # 加载针对 llm-query 定制的提示词片段 + 知识库地图
skill_prompt = load_skill_prompt("llm-query") skill_prompt = load_skill_prompt("llm-query")
index_map = load_index_map()
# 注入前置历史会话上下文 # 注入前置历史会话上下文
history_injection = "" history_injection = ""
...@@ -179,17 +195,30 @@ def build_query_agent(history: list) -> ReActAgent: ...@@ -179,17 +195,30 @@ def build_query_agent(history: list) -> ReActAgent:
sys_prompt = f"""你是一名专业的汽车后市场服务知识顾问。你的任务是基于知识库精确回答用户问题。 sys_prompt = f"""你是一名专业的汽车后市场服务知识顾问。你的任务是基于知识库精确回答用户问题。
{history_injection} {history_injection}
【工作流程】 【知识库地图(index.md,已为你注入,禁止再用工具读取 index.md)】
1. 先分析用户问题的意图(产品、话术、政策、流程、排障等)。 下面是全库页面目录,按页面类型分组,每行格式 `- [[slug]] — 标题`。请**直接据此地图定位**目标页面 slug。
2. 使用 grep_wiki_files / glob_wiki_files / read_local_file 工具在 ware/wiki 中检索。 {index_map}
3. 完成检索后,直接基于找到的内容生成专业、准确的最终回答。
【页面物理路径规则】(据 slug 直接拼出路径去读,避免无谓搜索)
- 一般类型:`ware/wiki/<type>/<slug>.md`(type 取地图中所属分组,如 products/policies/scripts/procedures/concepts/comparisons/troubleshooting/entities/synthesis)。
- 来源摘要:`ware/wiki/sources/<品牌系列>/<slug>.md`(系列不确定时用 glob_wiki_files 定位)。
【工作流程(务必收敛,尽量少调用工具)】
1. 判断意图并路由(优先级):系统报错/操作受阻→troubleshooting;"能不能说/违规吗"→policies(合规红线);"怎么回/话术"→scripts;产品参数/价格→products;条款/政策→policies;流程/步骤→procedures;对比→comparisons/synthesis;概念→concepts。
2. 据地图选出最相关的目标 slug,用 read_local_file 直接读 **≤3 个**目标页(路径按上面规则拼)。
3. 仅当页面 frontmatter 的 `related` 中有**确有必要**的关联页时,再二跳读取(如产品页→关联 policy 看免责、话术页→关联 concept 看方法论)。
4. 基于读到的内容生成最终回答。
- 仅当据图无法定位、或需在正文中查具体数值/罕见词时,才用 grep_wiki_files(兜底)。
【上下文与防串味(使用结构化字段,不要用 tags 判品牌)】
- 页面 frontmatter 含结构化字段:`brand`(列表)、`series`、`business_category`、`sub_business`、`role`。
- 读页后用 `brand`/`series` 核对是否与用户所属品牌一致,**严禁跨品牌混淆信息**。
- 若问题涉及产品/价格/政策但无法确定品牌,**先反问确认品牌再检索**,不要臆测。
【严格约束】 【严格约束】
- 只使用知识库中的信息回答,禁止编造或臆测。 - 只使用知识库中的信息回答,禁止编造或臆测;价格、年限、里程等数字必须与原文完全一致,禁止四舍五入。
- 价格、年限、里程等数字必须与知识库原文完全一致,禁止四舍五入。 - 知识库信息不足以回答时,明确告知并建议补充哪类文档(走兜底话术)。
- 如果知识库信息不足以回答,明确告知用户并建议补充哪类文档。 - 引用页面使用 slug 简写 `[[slug]]`。
- 区分不同品牌/车型,不得混淆信息。
- 当用户问题模糊时(如不确定品牌/产品),先反问确认再检索。
- 最终回答只放在最终答案中;思考过程、工具调用和工具返回不要混入最终答案。 - 最终回答只放在最终答案中;思考过程、工具调用和工具返回不要混入最终答案。
{skill_prompt} {skill_prompt}
...@@ -310,7 +339,6 @@ class WikiQueryRunner: ...@@ -310,7 +339,6 @@ class WikiQueryRunner:
duration_ms=int((time.time() - start_time) * 1000), duration_ms=int((time.time() - start_time) * 1000),
status=status, status=status,
error=error_msg, error=error_msg,
reasoning=self.reasoning,
) )
def _configure_agent(self, agent: ReActAgent) -> None: def _configure_agent(self, agent: ReActAgent) -> None:
...@@ -344,11 +372,19 @@ class WikiQueryRunner: ...@@ -344,11 +372,19 @@ class WikiQueryRunner:
if event_id: if event_id:
self._logged_call_events.add(event_id) self._logged_call_events.add(event_id)
# 工具调用附带入参摘要,便于排查检索路径
detail = ""
if event_type == "call":
parsed = parse_json_object(event.get("content"))
tool_input = parsed.get("input") if parsed else None
if tool_input is not None:
detail = " input=" + preview_text(json.dumps(tool_input, ensure_ascii=False), 200)
logger.info( logger.info(
"[Agent %s %s] name=%s", "[Agent %s %s] name=%s%s",
getattr(content, "name", "WikiAssistant"), getattr(content, "name", "WikiAssistant"),
event_type, event_type,
event.get("name"), event.get("name"),
detail,
) )
# 拦截替换 # 拦截替换
...@@ -624,25 +660,6 @@ def parse_json_object(value: Any) -> dict[str, Any]: ...@@ -624,25 +660,6 @@ def parse_json_object(value: Any) -> dict[str, Any]:
return parsed if isinstance(parsed, dict) else {} return parsed if isinstance(parsed, dict) else {}
def extract_tool_output_text(output: Any) -> str:
"""从工具调用返回的混合数据中提取主要文本内容(日志或显示用)"""
if output is None:
return ""
if isinstance(output, str):
return output
if isinstance(output, list):
parts = []
for item in output:
if isinstance(item, dict) and "text" in item:
parts.append(str(item.get("text", "")))
else:
parts.append(extract_tool_output_text(item))
return "\n".join(part for part in parts if part)
if isinstance(output, dict):
if "text" in output:
return str(output.get("text", ""))
return json.dumps(output, ensure_ascii=False)
return str(output)
def is_same_text(left: Any, right: Any) -> bool: def is_same_text(left: Any, right: Any) -> bool:
......
"""
Wiki 知识库后端的综合 RAG (Retrieval-Augmented Generation,检索增强生成) 子系统。
该包提供了文档的切块、向量化索引、检索以及调用大模型生成回答的核心功能。
"""
import os # 导入 os 模块,用于获取环境变量和进行文件路径操作
from config import BASE_DIR # 从根目录的 config 模块导入基础路径 BASE_DIR,用于构建相对路径
# ---------------------------------------------------------
# 存储路径配置
# ---------------------------------------------------------
# 原始上传/导入文件保存目录。
# 通过 os.environ.get 优先读取环境变量 'RAG_RAW_DIR',如果未设置,则默认拼接到项目基础路径下的 ware/rag/raw
RAG_RAW_DIR = os.environ.get("RAG_RAW_DIR", os.path.join(BASE_DIR, "ware", "rag", "raw"))
# ---------------------------------------------------------
# Qdrant 向量数据库配置
# ---------------------------------------------------------
# Qdrant 向量库连接与 collection 名称。
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
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-flash")
# 用于判断用户查询意图(如闲聊、查知识等)的大语言模型
RAG_INTENT_MODEL = os.environ.get("RAG_INTENT_MODEL", "qwen-flash")
# 用于改写用户查询(如补充代词、提取关键词)以提升检索效果的大模型
RAG_REWRITE_MODEL = os.environ.get("RAG_REWRITE_MODEL", "qwen-flash")
# 用于将文本转换为高维向量的 Embedding 模型,默认 text-embedding-v4
RAG_EMBEDDING_MODEL = os.environ.get("RAG_EMBEDDING_MODEL", "text-embedding-v4")
# ---------------------------------------------------------
# 数据摄取与解析质量控制
# ---------------------------------------------------------
# PDF 解析:整篇 PDF 每页都整页渲染送 VLM→Markdown(单一路线,不再区分文本/表格/图片页)。
# 任何转写异常一律 fail-fast 报错,不做降级兜底。
# 是否启用整页 VLM 解析(关闭时 PDF 直接报错,而非静默跳过)
RAG_PDF_VLM_PARSE = os.environ.get("RAG_PDF_VLM_PARSE", "true").lower() == "true"
# 整页渲染为图片送 VLM 时的缩放倍率(越高越清晰但越大),默认 3x
RAG_PDF_PAGE_RENDER_SCALE = float(os.environ.get("RAG_PDF_PAGE_RENDER_SCALE", "3.0"))
# 用于整页转写的多模态视觉模型(qwen-vl-max 对复杂/合并单元格表格的结构还原最稳)
RAG_PDF_VLM_MODEL = os.environ.get("RAG_PDF_VLM_MODEL", "qwen-vl-max")
# 单文件内整页 VLM 调用的最大并发数(每页 1 次调用,最多同时跑这么多页),默认 3
RAG_PDF_VLM_CONCURRENCY = int(os.environ.get("RAG_PDF_VLM_CONCURRENCY", "3"))
# ---------------------------------------------------------
# 粗排 (Recall) 与上下文构建配置
# ---------------------------------------------------------
# Qdrant 粗召回参数:dense/sparse 各取 top-k,之后按父块聚合。
# 密集向量(Dense Vector)检索阶段的召回数量上限,默认召回 50 个相关片段
RAG_VECTOR_TOP_K = int(os.environ.get("RAG_VECTOR_TOP_K", "50"))
# 稀疏向量(Sparse Vector / 关键字检索 / BM25 等)阶段的召回数量上限,默认召回 50 个相关片段
RAG_SPARSE_TOP_K = int(os.environ.get("RAG_SPARSE_TOP_K", "50"))
# 聚合到父级块后,最终保留参与后续精排或送给大模型的父级分块总数量,默认保留 5 个
RAG_PARENT_FINAL_TOP_K = int(os.environ.get("RAG_PARENT_FINAL_TOP_K", "5"))
# 召回片段的邻居窗口大小(即除了命中的 Chunk,还要顺带带上前后相邻的 Chunk 数量以补充完整上下文),默认为 1
RAG_NEIGHBOR_WINDOW = int(os.environ.get("RAG_NEIGHBOR_WINDOW", "1"))
# 是否开启 Qdrant 的 Hybrid Search(密集向量与稀疏向量联合检索)功能,默认为 true
RAG_QDRANT_HYBRID = os.environ.get("RAG_QDRANT_HYBRID", "true").lower() == "true"
# ---------------------------------------------------------
# 精排 (Rerank) 配置
# ---------------------------------------------------------
# 精排模型配置。
# 调用的 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"))
# 精排后保留片段的最低相关度阈值(作用于 reranker 返回的 relevance_score),低于即丢弃,默认 0.15
RAG_MIN_RERANK_SCORE = float(os.environ.get("RAG_MIN_RERANK_SCORE", "0.15"))
# ---------------------------------------------------------
# 并发和批处理性能控制
# ---------------------------------------------------------
# 并发和批处理控制。
# 同一时间允许并行索引的文件数,默认 1:即同一时间只索引一个文件(解析→向量化→入库串行进行)
RAG_INDEX_CONCURRENCY = int(os.environ.get("RAG_INDEX_CONCURRENCY", "1"))
# 处理外部 API 并发查询请求时的处理限制阈值,默认 20
RAG_QUERY_CONCURRENCY = int(os.environ.get("RAG_QUERY_CONCURRENCY", "20"))
# 向大语言模型(LLM)发起改写、提炼、回答时的最大并发数,用于防限流和控制 token 消耗速率,默认 5
RAG_LLM_CONCURRENCY = int(os.environ.get("RAG_LLM_CONCURRENCY", "5"))
# 单次调用 Embedding 服务进行批量文本向量化计算的条目数量上限,默认 32 条
RAG_EMBED_BATCH_SIZE = int(os.environ.get("RAG_EMBED_BATCH_SIZE", "32"))
# ---------------------------------------------------------
# 上下文与缓存配置
# ---------------------------------------------------------
# 送入回答模型的最大上下文字符数。
# 为了防止组装提示词阶段总 Token 溢出,限制最终送入 LLM 作为背景上下文的总字符长度上限,默认 12000 字符
RAG_MAX_CONTEXT_CHARS = int(os.environ.get("RAG_MAX_CONTEXT_CHARS", "12000"))
# 单条 query embedding 的内存缓存配置。
# 相同用户 Query 的 Embedding 计算结果在内存缓存中的保留存活时长,默认 600 秒
RAG_QUERY_CACHE_TTL_SECONDS = int(os.environ.get("RAG_QUERY_CACHE_TTL_SECONDS", "600"))
# 缓存 Query 映射的最大记录容量条目数(可配合 LRU/LFU 淘汰策略使用),默认 2048 条
RAG_QUERY_CACHE_SIZE = int(os.environ.get("RAG_QUERY_CACHE_SIZE", "2048"))
# ---------------------------------------------------------
# 文档切分 (Chunking) 配置
# ---------------------------------------------------------
# 父块切分参数:父块用于送入 LLM 的主上下文。
# 长文档粗切分(父级逻辑块)时的目标期望字符长度,确保该片段能承载相对完整的长逻辑,默认 1800 字符
PARENT_TARGET_CHARS = int(os.environ.get("RAG_PARENT_TARGET_CHARS", "1800"))
# 长文档粗切分时的最大允许字符长度(硬限制),如果段落过长超过此界限则会被强行切断,默认 3000 字符
PARENT_MAX_CHARS = int(os.environ.get("RAG_PARENT_MAX_CHARS", "3000"))
# 子块切分参数:子块用于向量检索,保留少量 overlap 提升召回连续性。
# 文档精细切分(子级文本块)的目标期望字符长度,这是进行向量化的最小粒度单元,默认 400 字符
CHILD_TARGET_CHARS = int(os.environ.get("RAG_CHILD_TARGET_CHARS", "400"))
# 细切分时的最大允许字符数上限,默认 600 字符
CHILD_MAX_CHARS = int(os.environ.get("RAG_CHILD_MAX_CHARS", "600"))
# 相邻切分子块之间保留重叠区域的字符数,防止跨边界的重要语义被生硬割裂,默认 80 字符
CHILD_OVERLAP_CHARS = int(os.environ.get("RAG_CHILD_OVERLAP_CHARS", "80"))
# 表格子块切分参数:按行窗口切分,并保留表头和少量重叠行。
# 遇到 Markdown 或文档表格结构时,每个表格切分块期望涵盖的数据行数,默认 6 行
TABLE_CHILD_TARGET_ROWS = int(os.environ.get("RAG_TABLE_CHILD_TARGET_ROWS", "6"))
# 表格在进行分块处理时,相邻块除了必须带有的表头外,保留内容重叠的行数,默认重叠 1 行
TABLE_CHILD_OVERLAP_ROWS = int(os.environ.get("RAG_TABLE_CHILD_OVERLAP_ROWS", "1"))
# 表格切分块在任何情况下的字符总数物理上限,避免某些表格单行内塞入大段文字导致超长,默认 1200 字符
TABLE_CHILD_MAX_CHARS = int(os.environ.get("RAG_TABLE_CHILD_MAX_CHARS", "1200"))
# ---------------------------------------------------------
# 其他配置
# ---------------------------------------------------------
# 允许导入/解析的文件后缀。
# 定义系统允许上传和自动化解析进行建库的文件扩展名白名单(支持主流文本与 Office 格式)
SUPPORTED_EXTENSIONS = {
".txt", ".md", ".pdf", ".docx", ".pptx", ".ppt", ".xlsx", ".xls", ".xlx"
}
# ---------------------------------------------------------
# 初始化执行
# ---------------------------------------------------------
# 若指定的原始文件暂存目录 RAG_RAW_DIR 不存在,则在此处自动创建该目录树,确保后续写文件正常
os.makedirs(RAG_RAW_DIR, exist_ok=True)
from __future__ import annotations
import json
from typing import Any
class RagStructuredError(RuntimeError):
error_code = "RAG_ERROR"
def __init__(self, message: str, *, detail: dict[str, Any] | None = None) -> None:
super().__init__(message)
self.detail = detail or {}
def to_json(self) -> str:
return json.dumps({"error_code": self.error_code, **self.detail}, ensure_ascii=False)
class PdfVlmParseError(RagStructuredError):
"""整页 VLM 转写失败(模型不可用、超时、返回为空等)。fail-fast,无兜底。"""
error_code = "PDF_VLM_PARSE_FAILED"
"""
数据摄取(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", # RAG 切块数据(包含向量化及检索所需信息的片段)
"build_chunks", # 构建父子级片段的核心函数
"extract_metadata", # 从文本中提取业务元数据的函数
"parse_document", # 解析原始文档(如 PDF、Word)的函数
]
"""
大语言模型(LLM)与词向量(Embedding)调用模块。
对大语言模型进行统一封装,提供了流式与非流式对话接口,
以及支持批量处理与内存缓存的 Embedding 向量化功能。
"""
import logging
import threading
import time
from collections import OrderedDict
from typing import Iterable
from agentscope.message import Msg
from config import API_KEY
from src.rag.config import (
RAG_EMBEDDING_MODEL,
RAG_QUERY_CACHE_SIZE,
RAG_QUERY_CACHE_TTL_SECONDS,
)
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:
final_chunk = chunk
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
async for chunk in res:
content = getattr(chunk, "content", "")
if isinstance(content, list):
text = "".join(str(x.get("text", "")) for x in content if isinstance(x, dict) and x.get("type") == "text")
thinking = "".join(str(x.get("thinking", "")) for x in content if isinstance(x, dict) and x.get("type") == "thinking")
else:
text = str(content)
thinking = ""
# 提取每次迭代新增的部分文本
text_delta = text[last_text_len:]
thinking_delta = thinking[last_thinking_len:]
if include_thinking and thinking_delta:
yield {"type": "thinking_delta", "content": thinking_delta}
if text_delta:
yield {"type": "answer_delta", "content": text_delta}
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")
thinking = "".join(str(x.get("thinking", "")) for x in content if isinstance(x, dict) and x.get("type") == "thinking")
else:
text = str(content)
thinking = ""
if include_thinking and thinking:
yield {"type": "thinking_delta", "content": thinking}
if text:
yield {"type": "answer_delta", "content": text}
def embed_texts(texts: list[str], *, allow_cache: bool = False) -> list[list[float]]:
"""
调用阿里云 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)
if getattr(resp, "status_code", 200) != 200:
raise RuntimeError(f"DashScope embedding failed: {resp}")
break # Success
except Exception as e:
if attempt < max_retries - 1:
logger.warning("[RAG] DashScope API 调用异常,正在重试 (%s/%s): %s", attempt + 1, max_retries - 1, e)
time.sleep(1.0 * (attempt + 1))
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,
len(texts),
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 不可用")
raise RuntimeError("Embedding API 不可用,已停止索引/检索") from exc
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:
cached = _embedding_cache.get(key)
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 src.rag.loaders.base import BaseLoader, DocumentBlock, get_loader, parse_document, register_loader
# Import modules for registration side effects.
from src.rag.loaders import excel_loader as _excel_loader
from src.rag.loaders import markdown_loader as _markdown_loader
from src.rag.loaders import office_loader as _office_loader
from src.rag.loaders import pdf_loader as _pdf_loader
from src.rag.loaders import text_loader as _text_loader
__all__ = ["BaseLoader", "DocumentBlock", "get_loader", "parse_document", "register_loader"]
from __future__ import annotations
import os
from dataclasses import dataclass, field
from typing import Any, Protocol
from src.rag.config import SUPPORTED_EXTENSIONS
from src.rag.utils import file_ext
@dataclass
class DocumentBlock:
text: str
block_type: str = "paragraph"
title_path: str = ""
page_number: int | None = None
slide_number: int | None = None
sheet_name: str | None = None
row_start: int | None = None
row_end: int | None = None
source_offset: int | None = None
metadata: dict[str, Any] = field(default_factory=dict)
class BaseLoader(Protocol):
extensions: set[str]
def load(self, path: str) -> list[DocumentBlock]:
...
_LOADERS: list[BaseLoader] = []
def register_loader(loader: BaseLoader) -> BaseLoader:
_LOADERS.append(loader)
return loader
def get_loader(path: str) -> BaseLoader:
ext = file_ext(path)
if ext not in SUPPORTED_EXTENSIONS:
raise ValueError(f"不支持的文件格式: {ext}")
for loader in _LOADERS:
if ext in loader.extensions:
return loader
raise ValueError(f"未注册的文件格式: {ext}")
def parse_document(path: str) -> list[DocumentBlock]:
if not os.path.exists(path):
raise FileNotFoundError(path)
return get_loader(path).load(path)
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
class ExcelLoader:
extensions = {".xlsx", ".xls", ".xlx"}
def load(self, path: str) -> list[DocumentBlock]:
import pandas as pd
try:
sheets = pd.read_excel(path, sheet_name=None)
except Exception as exc:
if file_ext(path) == ".xlx":
raise RuntimeError(".xlx 解析失败,请确认文件是否应为 .xls 或 .xlsx。") from exc
raise
blocks: list[DocumentBlock] = []
for sheet_name, df in sheets.items():
df = df.dropna(how="all")
if df.empty:
continue
headers = [str(c) for c in df.columns]
batch_size = 35
for start in range(0, len(df), batch_size):
sub = df.iloc[start : start + batch_size]
rows = ["| " + " | ".join(headers) + " |", "| " + " | ".join(["---"] * len(headers)) + " |"]
rows.extend("| " + " | ".join("" if v != v else str(v) for v in row) + " |" for row in sub.values.tolist())
blocks.append(
DocumentBlock(
text="\n".join(rows),
block_type="table",
title_path=str(sheet_name),
sheet_name=str(sheet_name),
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 enrich_blocks(blocks, parse_method="excel_table")
register_loader(ExcelLoader())
from __future__ import annotations
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
def parse_markdown_text(text: str, inherited: dict[str, Any] | None = None) -> list[DocumentBlock]:
inherited = dict(inherited or {})
if text.startswith("---"):
end = text.find("\n---", 3)
if end != -1:
inherited["frontmatter"] = text[3:end].strip()
text = text[end + 4 :]
blocks: list[DocumentBlock] = []
headings: list[str] = []
buffer: list[str] = []
offset = 0
def flush() -> None:
nonlocal buffer, offset
content = normalize_text("\n".join(buffer))
if content:
block_type = "table" if _looks_like_markdown_table(content) else "paragraph"
blocks.append(
DocumentBlock(
text=content,
block_type=block_type,
title_path=" / ".join(headings),
source_offset=offset,
metadata={
**dict(inherited),
"heading_level": len(headings) if headings else None,
},
)
)
offset += 1
buffer = []
for line in text.splitlines():
match = re.match(r"^(#{1,6})\s+(.+)$", line)
if match:
flush()
level = len(match.group(1))
headings[:] = headings[: level - 1]
headings.append(match.group(2).strip())
else:
buffer.append(line)
flush()
return enrich_blocks(blocks, parse_method="markdown")
def _looks_like_markdown_table(text: str) -> bool:
lines = [line.strip() for line in text.splitlines() if line.strip()]
return len(lines) >= 2 and "|" in lines[0] and re.search(r"\|\s*:?-{3,}:?\s*\|", lines[1])
class MarkdownLoader:
extensions = {".md"}
def load(self, path: str) -> list[DocumentBlock]:
return parse_markdown_text(read_text(path))
register_loader(MarkdownLoader())
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
class DocxLoader:
extensions = {".docx"}
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
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 = (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,
metadata={
"parse_method": "docx_paragraph",
"content_role": "body",
"content_kind": "text",
},
)
)
offset += 1
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:
extensions = {".pptx"}
def load(self, path: str) -> list[DocumentBlock]:
import pptx
prs = pptx.Presentation(path)
blocks: list[DocumentBlock] = []
for slide_index, slide in enumerate(prs.slides, start=1):
texts = []
for shape in slide.shapes:
if hasattr(shape, "text") and shape.text.strip():
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,
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("Direct .ppt parsing is not supported. Please convert it to .pptx before uploading.")
register_loader(DocxLoader())
register_loader(PptxLoader())
register_loader(LegacyPptLoader())
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
def read_text(path: str) -> str:
for enc in ["utf-8", "utf-8-sig", "gbk", "latin-1"]:
try:
with open(path, "r", encoding=enc) as f:
return f.read()
except UnicodeDecodeError:
continue
with open(path, "r", encoding="utf-8", errors="replace") as f:
return f.read()
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()]
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:
extensions = {".txt"}
def load(self, path: str) -> list[DocumentBlock]:
return split_plain_blocks(read_text(path))
register_loader(TextLoader())
"""
业务元数据规则提取模块。
通过配置硬编码的规则(如关键词、品牌名称),为切块后的文本打上领域相关的意图、分类和品牌标签。
这些标签后续会被附加至向量数据库(Payload),并在搜索阶段进行软性或硬性过滤,提升垂直知识库查准率。
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import Any
# 汽车后市场支持的常见品牌字典,一旦文本内出现这些字符串则会被关联对应品牌
KNOWN_BRANDS = [
"问界", "享界", "智界", "尊界", "尚界", "岚图", "零跑", "理想", "小鹏", "比亚迪",
"奔驰", "宝马", "奥迪", "大众", "本田", "日产", "吉利", "哪吒", "长城", "长安",
"奇瑞", "埃安", "广汽传祺", "极氪", "阿维塔", "深蓝", "腾势", "方程豹", "仰望",
]
# 按售后核心业务场景分类的特征词语
BUSINESS_KEYWORDS = {
"轻改类": ["太阳膜", "漆面保护膜", "车衣", "天窗冰甲", "底盘护板", "电动踏板", "脚垫", "小桌板"],
"权益类": ["延保", "安心包", "轮胎", "电池延保", "会员权益", "原厂权益", "广联权益", "质保", "辅助驾驶无忧", "赔付", "补偿", "享权", "保额"],
"二手车类": ["二手车", "置换", "收车", "评估"],
}
# 子业务/产品的受控词典(对齐 schema.md 的产品清单),命中即标准化 sub_business。
# 顺序敏感:更具体的产品放前面,避免被泛词(如“延保”)抢先匹配。
SUB_BUSINESS_KEYWORDS = {
"核心零部件延保": ["核心零部件延保", "三电延保"],
"超长期全面延保": ["超长期全面延保", "全面延保"],
"整车延保": ["整车延保", "整车零部件"],
"轮胎保障": ["轮胎保障", "轮胎险", "轮胎服务"],
"驾行安心包": ["驾行安心包"],
"养车安心包": ["养车安心包"],
"安心包": ["安心包"],
"电池延保": ["电池延保", "电池衰减"],
"出险代步服务": ["出险代步", "代步服务"],
"辅助驾驶无忧服务": ["辅助驾驶无忧", "辅助驾驶", "泊车场景", "巡航场景"],
"漆面尊享权益": ["漆面尊享", "漆面保障"],
"原厂权益": ["原厂权益"],
"广联权益": ["广联权益"],
"太阳膜": ["太阳膜"],
"漆面保护膜": ["漆面保护膜", "隐形车衣", "ppf"],
"天窗冰甲": ["天窗冰甲"],
"底盘护板": ["底盘护板"],
"电动踏板": ["电动踏板"],
"脚垫": ["脚垫"],
"后排小桌板": ["小桌板"],
}
# 文本块所处的内容格式或文档体裁意图分类(如产品介绍、话术指导等)
PAGE_TYPE_KEYWORDS = {
"product": ["产品", "保障范围", "价格", "指导价", "参数", "套餐", "权益", "保额", "限额"],
"script": ["话术", "怎么回", "怎么说", "异议", "客户说", "促单", "嫌贵"],
"policy": ["政策", "条款", "免责", "质保", "合规", "红线", "规则"],
"procedure": ["流程", "步骤", "SOP", "操作", "退单", "入单"],
"troubleshooting": ["报错", "失败", "无法", "找不到", "错误码", "入不了单"],
"comparison": ["对比", "区别", "vs", "VS", "哪个好"],
}
@dataclass
class BusinessMetadata:
"""存放通过规则提取出的文本业务元数据结果的数据类。"""
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():
if any(word in sample for word in words):
meta.business_category = category
break
# 2b. 命中标准化子业务/产品名(受控词典,优先具体产品)
sub_business = next(
(name for name, words in SUB_BUSINESS_KEYWORDS.items() if any(word in sample.lower() for word in words)),
None,
)
if sub_business:
meta.metadata_json["sub_business"] = sub_business
# 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"] = "价格异议"
return meta
"""
重排(Rerank)模块。
在初筛出的若干粗排 Chunk 后,通过调用阿里 DashScope 的 Reranker API,
对(Query + Chunk 文本)进行深层次的语义匹配与再打分,以提升靠前结果的精度。
"""
from __future__ import annotations
import logging
import os
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]:
"""
利用重排大模型重新评估给定片段与查询的相关性。
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,
)
# 校验请求结果
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 = 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 unavailable, keeping original retrieval order: model=%s error=%s",
RAG_RERANKER_MODEL,
exc,
exc_info=True,
)
return chunks
"""
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 手动执行。
该函数会在首次调用时打印提示,并保证不会重复打印。
"""
global _synced
if not _synced:
logger.info("[RAG] 轻量 schema 已启用,跳过运行时自动扩表")
_synced = True
"""
RAG 模块中所有与外部接口通信的 Pydantic 数据模型(Schemas)定义。
这些模型主要用于 FastAPI 路由中的请求体验证和参数接收。
"""
from typing import Any
from pydantic import BaseModel, Field
class RagUploadInitItem(BaseModel):
"""
RAG 上传初始化请求中的单个文件项
"""
name: str # 待上传的文件名称
class RagUploadInitRequest(BaseModel):
"""
RAG 上传初始化请求参数
"""
files: list[RagUploadInitItem] # 准备上传的文件列表
class RagQueryRequest(BaseModel):
"""
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 # 如果索引已存在,是否强制重新构建
"""
稀疏向量计算模块 (Sparse Embedding)
利用本地词频统计与 TF-IDF/BM25 相似的思路,将文本转为高维稀疏向量,
用于在使用 Qdrant 时支持基于词汇的精确关键词匹配检索 (Hybrid Search)。
"""
from __future__ import annotations
import hashlib
import math
import re
from collections import Counter
from dataclasses import dataclass
@dataclass(frozen=True)
class SparseTextVector:
"""表示稀疏文本向量的数据类,保存非零元素的索引和权重。"""
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")
"""
RAG 相关的通用工具函数集合。
包含了哈希计算、文本规范化、Token估算以及 JSON 和文件相关的辅助工具。
"""
import hashlib
import json
import re
from pathlib import Path
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)
return text.strip()
def estimate_tokens(text: str) -> int:
"""
粗略估算字符串所占的 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:
return json.loads(text)
except Exception:
return default
def file_ext(name: str) -> str:
"""获取文件名的扩展名,并统一转换为小写形式。"""
return Path(name).suffix.lower()
...@@ -207,6 +207,26 @@ def read_local_file(file_path: str, start_line: int = 1, end_line: int = None) - ...@@ -207,6 +207,26 @@ def read_local_file(file_path: str, start_line: int = 1, end_line: int = None) -
content=[TextBlock(type="text", text=f"❌ 读取错误: {str(e)}")] content=[TextBlock(type="text", text=f"❌ 读取错误: {str(e)}")]
) )
_BR_RE = re.compile(r"\s*<br\s*/?>\s*", re.IGNORECASE)
def normalize_br_tags(text: str) -> str:
"""规范化 <br>/<br/>/<br /> 标签(表格感知):
- 表格行(含 `|`):cell 内换行替换为单个空格,保持列结构不被破坏;
- 普通正文行:<br> 还原为真实换行。
返回 (是否有改动, 规范化后文本) 由调用方按需判断;此处只返回文本。
"""
if "<br" not in text.lower():
return text
out = []
for line in text.split("\n"):
if "|" in line:
out.append(_BR_RE.sub(" ", line))
else:
out.append(_BR_RE.sub("\n", line))
return "\n".join(out)
def batch_write_wiki_files(files: list[dict], source_ref: str = None) -> ToolResponse: def batch_write_wiki_files(files: list[dict], source_ref: str = None) -> ToolResponse:
""" """
批量将多个内容写入知识库目录。 批量将多个内容写入知识库目录。
...@@ -467,6 +487,113 @@ def add_wiki_warning(file_path: str, warning_text: str) -> ToolResponse: ...@@ -467,6 +487,113 @@ def add_wiki_warning(file_path: str, warning_text: str) -> ToolResponse:
except Exception as e: except Exception as e:
return ToolResponse(content=[TextBlock(type="text", text=f"❌ 添加警告失败: {str(e)}")]) return ToolResponse(content=[TextBlock(type="text", text=f"❌ 添加警告失败: {str(e)}")])
# ==================================================================================
# index.md 确定性重建(供 ingest / egress / lint 复用)
# ==================================================================================
# type -> (展示分组标题, 排序权重)。同时兼容单复数两种写法。
_INDEX_TYPE_GROUPS = [
("entities", "实体(entities/)"),
("products", "产品(products/)"),
("concepts", "概念(concepts/)"),
("procedures", "流程(procedures/)"),
("scripts", "话术(scripts/)"),
("policies", "政策(policies/)"),
("comparisons", "对比(comparisons/)"),
("troubleshooting", "系统排障(troubleshooting/)"),
("sources", "资料摘要(sources/)"),
("synthesis", "综合分析(synthesis/)"),
]
# 单数/异体 type 值归一到上面的复数分组键
_INDEX_TYPE_ALIAS = {
"entity": "entities", "product": "products", "concept": "concepts",
"procedure": "procedures", "script": "scripts", "policy": "policies",
"comparison": "comparisons", "source": "sources",
"syntheses": "synthesis", "synthesi": "synthesis",
}
def _normalize_index_type(raw_type) -> str:
t = str(raw_type or "").strip().lower()
return _INDEX_TYPE_ALIAS.get(t, t)
def rebuild_index(wiki_dir: str) -> int:
"""
扫描 wiki_dir 下所有页面的 frontmatter,按 type 分组(组内按 series/brand/slug 排序),
确定性地全量重建 index.md。返回纳入索引的页面数。
供 ingest(Phase3 收尾)、egress(删页后)、lint(Phase1 修复)复用,
取代历史上「只追加、易损坏」的索引维护方式。
"""
from datetime import datetime as _dt
skip_names = {"index.md", "log.md"}
skip_dirs = {os.path.join(wiki_dir, "metadata"), os.path.join(wiki_dir, "lint_reports")}
# 收集页面元信息:group_key -> list of (sort_key, slug, title)
grouped: dict[str, list] = {}
total = 0
for root, dirs, files in os.walk(wiki_dir):
dirs[:] = [d for d in dirs if os.path.join(root, d) not in skip_dirs]
for fname in files:
if not fname.endswith(".md") or fname in skip_names:
continue
fpath = os.path.join(root, fname)
slug = os.path.splitext(fname)[0]
ptype, title, series, brand = "", slug, "", ""
try:
post = frontmatter.load(fpath)
md = post.metadata
ptype = _normalize_index_type(md.get("type"))
title = str(md.get("title") or slug)
series = str(md.get("series") or "")
b = md.get("brand")
brand = (b[0] if isinstance(b, list) and b else str(b or "")) if b else ""
except Exception:
ptype = ""
group_key = ptype if ptype in dict(_INDEX_TYPE_GROUPS) else "_其他"
sort_key = (series, brand, slug)
grouped.setdefault(group_key, []).append((sort_key, slug, title))
total += 1
# 组装 markdown
lines = [
"# 知识索引",
"",
"> 本文件由系统在每次摄入/摄出/Lint 后自动全量重建,请勿手动编辑。",
f"> 最后更新:{_dt.now().strftime('%Y-%m-%d %H:%M:%S')} | 页面总数:{total}",
"",
]
for group_key, heading in _INDEX_TYPE_GROUPS:
entries = grouped.get(group_key)
if not entries:
continue
entries.sort(key=lambda x: x[0])
lines.append(f"## {heading}")
for _sort_key, slug, title in entries:
if title and title != slug:
lines.append(f"- [[{slug}]] — {title}")
else:
lines.append(f"- [[{slug}]]")
lines.append("")
# 未识别 type 的兜底分组
others = grouped.get("_其他")
if others:
others.sort(key=lambda x: x[0])
lines.append("## 未分类")
for _sort_key, slug, title in others:
lines.append(f"- [[{slug}]] — {title}" if title and title != slug else f"- [[{slug}]]")
lines.append("")
index_path = os.path.join(wiki_dir, "index.md")
with open(index_path, "w", encoding="utf-8") as f:
f.write("\n".join(lines).rstrip() + "\n")
return total
def remove_wiki_link(file_path: str, target: str) -> ToolResponse: def remove_wiki_link(file_path: str, target: str) -> ToolResponse:
""" """
将指定的断链转化为纯文本。例如 [[target]] 变为 target,[[target|别名]] 变为 别名。 将指定的断链转化为纯文本。例如 [[target]] 变为 target,[[target|别名]] 变为 别名。
......
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
from src.rag.loaders.base import DocumentBlock, get_loader
from src.rag.loaders.pdf_loader import blocks_from_markdown
from src.rag.sparse import build_sparse_vector
def test_loader_registry_selects_pdf_loader():
loader = get_loader("demo.pdf")
assert loader.__class__.__name__ == "PdfLoader"
def test_blocks_from_markdown_preserves_heading_and_table():
markdown = """# 智界S7
## 在用车
| 产品 | 价格 |
| --- | --- |
| 电池延保 | 1299.50 |
"""
blocks = blocks_from_markdown(markdown, page_number=3, parse_method="unit")
assert len(blocks) == 1
assert blocks[0].block_type == "table"
assert blocks[0].title_path == "智界S7 / 在用车"
assert "| 电池延保 | 1299.50 |" in blocks[0].text
assert blocks[0].page_number == 3
def test_sparse_vector_is_deterministic_and_non_empty():
first = build_sparse_vector("智界S7 在用车 电池延保 1299.50")
second = build_sparse_vector("智界S7 在用车 电池延保 1299.50")
assert first.indices == second.indices
assert first.values == second.values
assert len(first.indices) > 0
assert len(first.indices) == len(first.values)
from pathlib import Path
import pytest
from src.rag import retrieval
from src.rag.chunking import build_chunks
from src.rag.loaders.base import DocumentBlock, get_loader, parse_document
def test_pdf_loader_has_no_paddleocr_path():
loader = get_loader("demo.pdf")
assert not hasattr(loader, "_load_with_paddleocr")
def test_table_child_chunks_keep_title_context_and_header():
table = "\n".join(
[
"| Model | Product | Price |",
"| --- | --- | --- |",
"| M7 | Battery warranty | 1000 |",
"| M7 | Tire warranty | 2000 |",
"| M7 | Paint film | 3000 |",
"| M7 | Service A | 4000 |",
"| M7 | Service B | 5000 |",
"| M7 | Service C | 6000 |",
"| M7 | Service D | 7000 |",
"| M7 | Service E | 8000 |",
]
)
blocks = [
DocumentBlock(
text=table,
block_type="table",
title_path="Price Guide / AITO M7",
page_number=2,
row_start=1,
row_end=8,
metadata={"parse_method": "pdfplumber_table", "table_markdown": True},
)
]
_, children = build_chunks("file-1", "price.pdf", "price.pdf", "PDF", blocks)
assert len(children) > 1
# title_path is stored in the chunk field, not injected into content (no context prefix)
assert all(child.title_path == "Price Guide / AITO M7" for child in children)
assert all("| Model | Product | Price |" in child.content for child in children)
assert children[0].row_start == 1
assert children[0].metadata_json["overlap_next_rows"] == 1
assert children[1].metadata_json["overlap_prev_rows"] == 1
assert children[1].row_start == 6
def test_text_child_chunks_keep_context_and_overlap_metadata(monkeypatch):
monkeypatch.setattr("src.rag.chunking.CHILD_TARGET_CHARS", 120)
monkeypatch.setattr("src.rag.chunking.CHILD_MAX_CHARS", 160)
monkeypatch.setattr("src.rag.chunking.CHILD_OVERLAP_CHARS", 30)
text = "第一段" + "甲" * 140 + "。第二段" + "乙" * 140 + "。"
blocks = [
DocumentBlock(
text=text,
block_type="paragraph",
title_path="二、电池延保服务",
page_number=2,
metadata={"parse_method": "pymupdf_text"},
)
]
_, children = build_chunks("file-1", "price.pdf", "price.pdf", "PDF", blocks)
assert len(children) > 1
# context prefix is no longer injected into content; overlap data is in metadata
assert children[0].metadata_json["overlap_next_chars"] == 30
assert children[1].metadata_json["overlap_prev_chars"] == 30
first_end = children[0].metadata_json["char_end"]
second_start = children[1].metadata_json["char_start"]
assert text[second_start:first_end] in children[0].content
assert text[second_start:first_end] in children[1].content
def test_pdf_price_overview_keeps_battery_intro_with_table_context():
pytest.importorskip("fitz")
pdf_path = Path("src/ref/参考资料/鸿蒙智行官方服务产品价格总览.pdf")
if not pdf_path.exists():
pytest.skip("price overview PDF fixture is not available")
blocks = parse_document(str(pdf_path))
parents, children = build_chunks("file-1", pdf_path.name, str(pdf_path), "PDF", blocks)
battery_table_children = [
child
for child in children
if child.metadata_json.get("table_markdown")
and "二、电池延保服务" in child.title_path
]
assert battery_table_children
assert all(child.metadata_json.get("table_header") for child in battery_table_children)
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)
# Section headings detected via pattern matching (no hardcoded injection)
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_merge_candidates_orders_by_hybrid_score():
low = retrieval.Candidate(
child_chunk_id="low",
parent_chunk_id="low-parent",
file_id="file",
retrieval_type="direct",
hybrid_score=0.2,
)
high = retrieval.Candidate(
child_chunk_id="high",
parent_chunk_id="high-parent",
file_id="file",
retrieval_type="direct",
hybrid_score=0.9,
)
ranked = retrieval._merge_candidates([low, high])
assert [c.child_chunk_id for c in ranked] == ["high", "low"]
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!