RAG/API_USAGE.md

156 lines
3.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# RAG API 使用文档
## 文档上传和检索 API
### 1. 上传文档
**端点**: `POST /documents/upload`
**功能**: 上传各种格式的文档并解析为知识库
**支持的文件格式**:
- 文本文件: `.txt`, `.md`, `.markdown`
- PDF 文件: `.pdf`
- Word 文档: `.docx`, `.doc`
- HTML 文件: `.html`, `.htm`
- CSV 文件: `.csv`
- JSON 文件: `.json`
**请求示例** (使用 curl):
```bash
# 基本上传
curl -X POST "http://localhost:8001/documents/upload" \
-F "file=@document.pdf"
# 指定文档 ID
curl -X POST "http://localhost:8001/documents/upload" \
-F "file=@document.pdf" \
-F "doc_id=my_document_001"
# 添加额外元数据
curl -X POST "http://localhost:8001/documents/upload" \
-F "file=@document.pdf" \
-F "doc_id=my_document_001" \
-F 'metadata={"author": "John Doe", "category": "technical"}'
```
**请求参数**:
- `file` (required): 要上传的文件
- `doc_id` (optional): 自定义文档 ID如果不提供则使用文件名不含扩展名
- `metadata` (optional): JSON 格式的额外元数据
**响应示例**:
```json
{
"doc_id": "my_document_001",
"filename": "document.pdf",
"file_type": "pdf",
"chunks": 5,
"message": "Document uploaded and processed successfully"
}
```
### 2. 根据文档 ID 检索所有内容
**端点**: `GET /documents/{doc_id}`
**功能**: 根据文档 ID 检索文档的所有内容(包括所有分块)
**请求示例**:
```bash
curl -X GET "http://localhost:8001/documents/my_document_001"
```
**响应示例**:
```json
{
"doc_id": "my_document_001",
"chunks": [
{
"id": "my_document_001_chunk_0",
"text": "这是文档的第一部分内容...",
"metadata": {
"doc_id": "my_document_001",
"chunk_id": "my_document_001_chunk_0",
"chunk_index": 0,
"file_name": "document.pdf",
"file_type": "pdf",
"source": "file_upload"
},
"chunk_index": 0
},
{
"id": "my_document_001_chunk_1",
"text": "这是文档的第二部分内容...",
"metadata": {...},
"chunk_index": 1
}
],
"total_chunks": 5,
"full_text": "这是文档的第一部分内容...\n\n这是文档的第二部分内容..."
}
```
**响应字段说明**:
- `doc_id`: 文档 ID
- `chunks`: 文档的所有分块列表(按 chunk_index 排序)
- `total_chunks`: 分块总数
- `full_text`: 所有分块合并后的完整文本
### 3. 其他现有 API
#### 查询 RAG 系统
```bash
POST /query
{
"query": "你的问题",
"top_k": 5,
"stream": true
}
```
#### 检索相关文档
```bash
POST /retrieve
{
"query": "搜索关键词",
"top_k": 5
}
```
#### 手动同步
```bash
POST /sync
{
"full_sync": false,
"force": false
}
```
#### 系统统计
```bash
GET /stats
```
## 工作流程
1. **上传文档**: 使用 `/documents/upload` 上传文档
2. **文档解析**: 系统自动解析文档并分块
3. **向量化**: 自动生成 embeddings 并存储到 ChromaDB
4. **检索使用**:
- 使用 `/query` 进行 RAG 查询(会使用上传的文档)
- 使用 `/retrieve` 进行向量检索
- 使用 `/documents/{doc_id}` 获取完整文档内容
## 注意事项
1. **文档 ID 唯一性**: 如果上传相同 `doc_id` 的文档,会覆盖之前的文档
2. **分块处理**: 大文档会被自动分块,每个分块都有独立的 ID
3. **元数据**: 可以通过 `metadata` 参数添加自定义元数据,用于后续过滤和检索
4. **文件大小**: 建议单个文件不超过 100MB