routes.py
10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""
RAG HTTP 路由配置与接口暴露模块。
向外部系统或者前端提供了诸如:文件上传、解析预览、建库索引、数据检索(包括 SSE 流式输出)等能力的 API 接口。
"""
import asyncio
import json
import logging
import os
from fastapi import APIRouter, Body, HTTPException, UploadFile, File, BackgroundTasks
from fastapi.responses import StreamingResponse
from src.rag.core.config import RAG_INDEX_CONCURRENCY
from src.rag.api.schemas import RagQueryRequest, RagUploadInitRequest
from src.rag.ingestion import files as ingest_files
from src.rag.ingestion import pipeline as ingest_pipeline
from src.rag.retrieval import pipeline as query_pipeline
logger = logging.getLogger(__name__)
router = APIRouter()
@router.get("/rag/health")
async def rag_health():
"""探针接口:用于检查 RAG 子系统及底层向量数据库的健康状态和基础统计信息。"""
data = await ingest_files.stats()
return {"status": "ok", **data}
@router.get("/rag/files")
async def rag_files(page: int = 1, page_size: int = 20, search: str = ""):
"""分页获取知识库中已经上传或构建索引的文档列表。"""
return await ingest_files.list_files(page, page_size, search)
@router.post("/rag/upload/init")
async def rag_upload_init(payload: RagUploadInitRequest):
"""
文件上传初始化步骤:
客户端发送准备上传的文件信息,服务端在数据库生成待传记录 ID,并做重复判断校验。
"""
return await ingest_files.init_upload([f.name for f in payload.files])
@router.post("/rag/upload/{file_id}")
async def rag_upload(file_id: str, file: UploadFile = File(...)):
"""
执行文件流的实体上传操作:
将上传的文件字节流保存至本地磁盘,更新对应的数据记录状态。
"""
return await ingest_files.save_upload(file_id, file)
@router.post("/rag/preview_parse")
async def rag_preview_parse(data: dict = Body(...)):
"""
后台调试及预览接口:
输入本地文件路径,模拟文档解析及切块的执行过程,并直接返回切分效果给前端预览,并不存入数据库。
"""
path = data.get("path")
if not path:
raise HTTPException(status_code=400, detail="path is required")
return await ingest_files.preview_parse(path)
@router.delete("/rag/files/{file_id}")
async def rag_delete_file(file_id: str):
"""
删除知识库指定的单个文件及关联物理存储:
必须处于非索引中状态;物理删除文件并调用底层销毁相关向量。
"""
from src.database.models import RagFile
from src.database.session import AsyncSessionLocal
async with AsyncSessionLocal() as session:
db_file = await session.get(RagFile, file_id)
if not db_file:
raise HTTPException(status_code=404, detail="RAG file not found")
if db_file.status in ["Indexed", "Indexing"]:
raise HTTPException(status_code=400, detail="请先删除索引再删除文件")
# 物理删除原始文档文件
if os.path.exists(db_file.source_path):
os.remove(db_file.source_path)
db_file.status = "Deleted"
await session.commit()
await ingest_pipeline.delete_index(file_id, keep_status=True, force=True)
return {"status": "success"}
@router.post("/rag/files/batch_delete")
async def rag_batch_delete(data: dict = Body(...)):
"""批量删除知识库文件。"""
ids = data.get("ids", [])
errors = []
for file_id in ids:
try:
await rag_delete_file(file_id)
except Exception as exc:
errors.append({"file_id": file_id, "error": str(exc)})
return {"status": "success", "errors": errors}
@router.post("/rag/index/{file_id}")
async def rag_index(file_id: str):
"""
发起单文件的索引构建任务:
将实际费时的解析、切块、向量化写入等放入 asyncio task 异步执行。
"""
from src.database.models import RagFile
from src.database.session import AsyncSessionLocal
async with AsyncSessionLocal() as session:
db_file = await session.get(RagFile, file_id)
if not db_file:
raise HTTPException(status_code=404, detail="RAG file not found")
if db_file.status == "Indexing":
return {"status": "already indexing", "file_id": file_id}
asyncio.create_task(ingest_pipeline.index_file(file_id))
return {"status": "index started", "file_id": file_id}
@router.post("/rag/batch_index")
async def rag_batch_index(data: dict = Body(...)):
"""批量对未进行或已失效的文件触发索引构建任务。"""
ids = data.get("ids", [])
from src.database.models import RagFile
from src.database.session import AsyncSessionLocal
count = 0
async with AsyncSessionLocal() as session:
for file_id in ids:
db_file = await session.get(RagFile, file_id)
if db_file and db_file.status != "Indexing":
asyncio.create_task(ingest_pipeline.index_file(file_id))
count += 1
return {"status": "batch index started", "count": count}
@router.post("/rag/batch_delete_index")
async def rag_batch_delete_index(data: dict = Body(...)):
"""批量删除文件的索引数据及向量库关联(但保留文件实体不变)。"""
ids = data.get("ids", [])
force = data.get("force", False)
count = 0
errors = []
for file_id in ids:
try:
await ingest_pipeline.delete_index(file_id, force=force)
count += 1
except Exception as exc:
errors.append({"file_id": file_id, "error": str(exc)})
return {"status": "batch delete index completed", "count": count, "errors": errors}
@router.delete("/rag/index/{file_id}")
async def rag_delete_index(file_id: str, force: bool = False):
"""单独删除某文件的索引数据及向量库关联(但保留文件实体不变)。"""
return await ingest_pipeline.delete_index(file_id, force=force)
@router.get("/rag/chunks/{file_id}")
async def rag_chunks(file_id: str):
"""后台工具接口:读取并展示某个文件切分产生的所有子区块。"""
return await ingest_files.get_chunks(file_id)
@router.get("/rag/chunk/{chunk_id}")
async def rag_chunk(chunk_id: str):
"""后台工具接口:直接查看特定分块片段详情。"""
return await ingest_files.get_chunk(chunk_id)
@router.post("/rag/query/json")
async def rag_query_json(payload: RagQueryRequest):
"""
发起单次知识检索与生成请求(非流式接口)。
返回一个完整的 JSON 响应(包含生成的回答、引用来源等),适用于不需要流式打印的场景。
"""
return await query_pipeline.query_json(payload)
@router.post("/rag/query/debug")
async def rag_query_debug(payload: RagQueryRequest):
"""
评测/排障专用接口:跑完整检索问答流程,一次性返回全部中间数据的 JSON
(意图全字段、queries、子查询、融合候选带分数、最终片段、引用、答案、tokens、耗时)。
不用于生产前端,便于用 curl/jq 或脚本批量评估 RAG 整体效果。
"""
return await query_pipeline.query_debug(payload)
@router.post("/rag/query")
async def rag_query(payload: RagQueryRequest):
"""
发起知识库检索以及大模型作答请求,这是 RAG 前端主要的问答聊天接口。
结果基于 Server-Sent Events (SSE) 方式实现流式输出(逐字吐出)。
"""
async def events():
yield "data: [INIT]\n\n"
try:
logger.info(f"[RAG] 收到 SSE 查询请求: query={payload.query}, sessionId={payload.sessionId}, history_len={len(payload.history) if payload.history else 0}")
yield f"data: {json.dumps({'type': 'retrieval_start'}, ensure_ascii=False)}\n\n"
async for event in query_pipeline.stream_query(payload):
yield f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
logger.info("[RAG] SSE 查询流式发送完成")
except Exception as exc:
logger.exception("[RAG] SSE 查询失败")
yield f"data: {json.dumps({'type': 'error', 'content': str(exc)}, ensure_ascii=False)}\n\n"
return StreamingResponse(
events(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
},
)
@router.post("/rag/clear_history")
async def rag_clear_history(data: dict = Body(default={})):
"""清除给定 Session 相关的 RAG 系统对话历史。"""
return await query_pipeline.clear_history(data.get("sessionId"))
@router.get("/rag/stats")
async def rag_stats():
"""返回 RAG 知识库大盘统计概况(文件数、索引数、片段数)。"""
return await ingest_files.stats()
@router.post("/rag/files/batch_download")
async def rag_batch_download(data: dict = Body(...)):
"""批量下载文件。如果是单个文件直接返回,多个文件打包为zip。"""
ids = data.get("ids", [])
if not ids:
raise HTTPException(status_code=400, detail="未提供文件ID")
from src.database.models import RagFile
from src.database.session import AsyncSessionLocal
files = []
async with AsyncSessionLocal() as session:
for file_id in ids:
db_file = await session.get(RagFile, file_id)
if db_file and os.path.exists(db_file.source_path):
files.append(db_file)
if not files:
raise HTTPException(status_code=404, detail="未找到可下载的文件")
import urllib.parse
if len(files) == 1:
# 单个文件直接下载
from fastapi.responses import FileResponse
file = files[0]
filename = urllib.parse.quote(file.name)
return FileResponse(
path=file.source_path,
filename=file.name,
headers={"Content-Disposition": f"attachment; filename*=utf-8''{filename}"}
)
else:
# 多个文件打包成zip
import io
import zipfile
from fastapi.responses import StreamingResponse
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:
for file in files:
zip_file.write(file.source_path, arcname=file.name)
zip_buffer.seek(0)
return StreamingResponse(
zip_buffer,
media_type="application/zip",
headers={"Content-Disposition": "attachment; filename*=utf-8''batch_download.zip"}
)