yangdx commited on
Commit
028ff3b
·
1 Parent(s): ba7b5d4

feat(api): Add Pydantic models for all endpoints in document_routes.py

Browse files
lightrag/api/routers/document_routes.py CHANGED
@@ -10,7 +10,7 @@ import traceback
10
  import pipmaster as pm
11
  from datetime import datetime
12
  from pathlib import Path
13
- from typing import Dict, List, Optional, Any
14
  from fastapi import APIRouter, BackgroundTasks, Depends, File, HTTPException, UploadFile
15
  from pydantic import BaseModel, Field, field_validator
16
 
@@ -30,7 +30,37 @@ router = APIRouter(
30
  temp_prefix = "__tmp__"
31
 
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  class InsertTextRequest(BaseModel):
 
 
 
 
 
 
34
  text: str = Field(
35
  min_length=1,
36
  description="The text to insert",
@@ -41,8 +71,21 @@ class InsertTextRequest(BaseModel):
41
  def strip_after(cls, text: str) -> str:
42
  return text.strip()
43
 
 
 
 
 
 
 
 
44
 
45
  class InsertTextsRequest(BaseModel):
 
 
 
 
 
 
46
  texts: list[str] = Field(
47
  min_length=1,
48
  description="The texts to insert",
@@ -53,30 +96,116 @@ class InsertTextsRequest(BaseModel):
53
  def strip_after(cls, texts: list[str]) -> list[str]:
54
  return [text.strip() for text in texts]
55
 
 
 
 
 
 
 
 
 
 
 
56
 
57
  class InsertResponse(BaseModel):
58
- status: str = Field(description="Status of the operation")
 
 
 
 
 
 
 
 
 
59
  message: str = Field(description="Message describing the operation result")
60
 
 
 
 
 
 
 
 
 
61
 
62
  class ClearDocumentsResponse(BaseModel):
63
- status: str = Field(
64
- description="Status of the clear operation: success/partial_success/busy/fail"
 
 
 
 
 
 
 
65
  )
66
  message: str = Field(description="Message describing the operation result")
67
 
 
 
 
 
 
 
 
 
68
 
69
  class ClearCacheRequest(BaseModel):
70
- modes: Optional[List[str]] = Field(
 
 
 
 
 
 
 
 
71
  default=None,
72
- description="Modes of cache to clear. Options: ['default', 'naive', 'local', 'global', 'hybrid', 'mix']. If None, clears all cache.",
73
  )
74
 
 
 
 
75
 
76
  class ClearCacheResponse(BaseModel):
77
- status: str = Field(description="Status of the clear operation: success/fail")
 
 
 
 
 
 
 
 
 
78
  message: str = Field(description="Message describing the operation result")
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  class DocStatusResponse(BaseModel):
82
  @staticmethod
@@ -87,34 +216,82 @@ class DocStatusResponse(BaseModel):
87
  return dt
88
  return dt.isoformat()
89
 
90
- """Response model for document status
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
  Attributes:
93
- id: Document identifier
94
- content_summary: Summary of document content
95
- content_length: Length of document content
96
- status: Current processing status
97
- created_at: Creation timestamp (ISO format string)
98
- updated_at: Last update timestamp (ISO format string)
99
- chunks_count: Number of chunks (optional)
100
- error: Error message if any (optional)
101
- metadata: Additional metadata (optional)
102
  """
103
 
104
- id: str
105
- content_summary: str
106
- content_length: int
107
- status: DocStatus
108
- created_at: str
109
- updated_at: str
110
- chunks_count: Optional[int] = None
111
- error: Optional[str] = None
112
- metadata: Optional[dict[str, Any]] = None
113
- file_path: str
114
-
115
 
116
- class DocsStatusesResponse(BaseModel):
117
- statuses: Dict[DocStatus, List[DocStatusResponse]] = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
 
120
  class PipelineStatusResponse(BaseModel):
@@ -529,7 +706,9 @@ def create_document_routes(
529
  # Create combined auth dependency for document routes
530
  combined_auth = get_combined_auth_dependency(api_key)
531
 
532
- @router.post("/scan", dependencies=[Depends(combined_auth)])
 
 
533
  async def scan_for_new_documents(background_tasks: BackgroundTasks):
534
  """
535
  Trigger the scanning process for new documents.
@@ -539,13 +718,18 @@ def create_document_routes(
539
  that fact.
540
 
541
  Returns:
542
- dict: A dictionary containing the scanning status
543
  """
544
  # Start the scanning process in the background
545
  background_tasks.add_task(run_scanning_process, rag, doc_manager)
546
- return {"status": "scanning_started"}
 
 
 
547
 
548
- @router.post("/upload", dependencies=[Depends(combined_auth)])
 
 
549
  async def upload_to_input_dir(
550
  background_tasks: BackgroundTasks, file: UploadFile = File(...)
551
  ):
@@ -1016,7 +1200,9 @@ def create_document_routes(
1016
  logger.error(traceback.format_exc())
1017
  raise HTTPException(status_code=500, detail=str(e))
1018
 
1019
- @router.get("", dependencies=[Depends(combined_auth)])
 
 
1020
  async def documents() -> DocsStatusesResponse:
1021
  """
1022
  Get the status of all documents in the system.
 
10
  import pipmaster as pm
11
  from datetime import datetime
12
  from pathlib import Path
13
+ from typing import Dict, List, Optional, Any, Literal
14
  from fastapi import APIRouter, BackgroundTasks, Depends, File, HTTPException, UploadFile
15
  from pydantic import BaseModel, Field, field_validator
16
 
 
30
  temp_prefix = "__tmp__"
31
 
32
 
33
+ class ScanResponse(BaseModel):
34
+ """Response model for document scanning operation
35
+
36
+ Attributes:
37
+ status: Status of the scanning operation
38
+ message: Optional message with additional details
39
+ """
40
+
41
+ status: Literal["scanning_started"] = Field(
42
+ description="Status of the scanning operation"
43
+ )
44
+ message: Optional[str] = Field(
45
+ default=None, description="Additional details about the scanning operation"
46
+ )
47
+
48
+ class Config:
49
+ json_schema_extra = {
50
+ "example": {
51
+ "status": "scanning_started",
52
+ "message": "Scanning process has been initiated in the background",
53
+ }
54
+ }
55
+
56
+
57
  class InsertTextRequest(BaseModel):
58
+ """Request model for inserting a single text document
59
+
60
+ Attributes:
61
+ text: The text content to be inserted into the RAG system
62
+ """
63
+
64
  text: str = Field(
65
  min_length=1,
66
  description="The text to insert",
 
71
  def strip_after(cls, text: str) -> str:
72
  return text.strip()
73
 
74
+ class Config:
75
+ json_schema_extra = {
76
+ "example": {
77
+ "text": "This is a sample text to be inserted into the RAG system."
78
+ }
79
+ }
80
+
81
 
82
  class InsertTextsRequest(BaseModel):
83
+ """Request model for inserting multiple text documents
84
+
85
+ Attributes:
86
+ texts: List of text contents to be inserted into the RAG system
87
+ """
88
+
89
  texts: list[str] = Field(
90
  min_length=1,
91
  description="The texts to insert",
 
96
  def strip_after(cls, texts: list[str]) -> list[str]:
97
  return [text.strip() for text in texts]
98
 
99
+ class Config:
100
+ json_schema_extra = {
101
+ "example": {
102
+ "texts": [
103
+ "This is the first text to be inserted.",
104
+ "This is the second text to be inserted.",
105
+ ]
106
+ }
107
+ }
108
+
109
 
110
  class InsertResponse(BaseModel):
111
+ """Response model for document insertion operations
112
+
113
+ Attributes:
114
+ status: Status of the operation (success, duplicated, partial_success, failure)
115
+ message: Detailed message describing the operation result
116
+ """
117
+
118
+ status: Literal["success", "duplicated", "partial_success", "failure"] = Field(
119
+ description="Status of the operation"
120
+ )
121
  message: str = Field(description="Message describing the operation result")
122
 
123
+ class Config:
124
+ json_schema_extra = {
125
+ "example": {
126
+ "status": "success",
127
+ "message": "File 'document.pdf' uploaded successfully. Processing will continue in background.",
128
+ }
129
+ }
130
+
131
 
132
  class ClearDocumentsResponse(BaseModel):
133
+ """Response model for document clearing operation
134
+
135
+ Attributes:
136
+ status: Status of the clear operation
137
+ message: Detailed message describing the operation result
138
+ """
139
+
140
+ status: Literal["success", "partial_success", "busy", "fail"] = Field(
141
+ description="Status of the clear operation"
142
  )
143
  message: str = Field(description="Message describing the operation result")
144
 
145
+ class Config:
146
+ json_schema_extra = {
147
+ "example": {
148
+ "status": "success",
149
+ "message": "All documents cleared successfully. Deleted 15 files.",
150
+ }
151
+ }
152
+
153
 
154
  class ClearCacheRequest(BaseModel):
155
+ """Request model for clearing cache
156
+
157
+ Attributes:
158
+ modes: Optional list of cache modes to clear
159
+ """
160
+
161
+ modes: Optional[
162
+ List[Literal["default", "naive", "local", "global", "hybrid", "mix"]]
163
+ ] = Field(
164
  default=None,
165
+ description="Modes of cache to clear. If None, clears all cache.",
166
  )
167
 
168
+ class Config:
169
+ json_schema_extra = {"example": {"modes": ["default", "naive"]}}
170
+
171
 
172
  class ClearCacheResponse(BaseModel):
173
+ """Response model for cache clearing operation
174
+
175
+ Attributes:
176
+ status: Status of the clear operation
177
+ message: Detailed message describing the operation result
178
+ """
179
+
180
+ status: Literal["success", "fail"] = Field(
181
+ description="Status of the clear operation"
182
+ )
183
  message: str = Field(description="Message describing the operation result")
184
 
185
+ class Config:
186
+ json_schema_extra = {
187
+ "example": {
188
+ "status": "success",
189
+ "message": "Successfully cleared cache for modes: ['default', 'naive']",
190
+ }
191
+ }
192
+
193
+
194
+ """Response model for document status
195
+
196
+ Attributes:
197
+ id: Document identifier
198
+ content_summary: Summary of document content
199
+ content_length: Length of document content
200
+ status: Current processing status
201
+ created_at: Creation timestamp (ISO format string)
202
+ updated_at: Last update timestamp (ISO format string)
203
+ chunks_count: Number of chunks (optional)
204
+ error: Error message if any (optional)
205
+ metadata: Additional metadata (optional)
206
+ file_path: Path to the document file
207
+ """
208
+
209
 
210
  class DocStatusResponse(BaseModel):
211
  @staticmethod
 
216
  return dt
217
  return dt.isoformat()
218
 
219
+ id: str = Field(description="Document identifier")
220
+ content_summary: str = Field(description="Summary of document content")
221
+ content_length: int = Field(description="Length of document content in characters")
222
+ status: DocStatus = Field(description="Current processing status")
223
+ created_at: str = Field(description="Creation timestamp (ISO format string)")
224
+ updated_at: str = Field(description="Last update timestamp (ISO format string)")
225
+ chunks_count: Optional[int] = Field(
226
+ default=None, description="Number of chunks the document was split into"
227
+ )
228
+ error: Optional[str] = Field(
229
+ default=None, description="Error message if processing failed"
230
+ )
231
+ metadata: Optional[dict[str, Any]] = Field(
232
+ default=None, description="Additional metadata about the document"
233
+ )
234
+ file_path: str = Field(description="Path to the document file")
235
+
236
+ class Config:
237
+ json_schema_extra = {
238
+ "example": {
239
+ "id": "doc_123456",
240
+ "content_summary": "Research paper on machine learning",
241
+ "content_length": 15240,
242
+ "status": "PROCESSED",
243
+ "created_at": "2025-03-31T12:34:56",
244
+ "updated_at": "2025-03-31T12:35:30",
245
+ "chunks_count": 12,
246
+ "error": None,
247
+ "metadata": {"author": "John Doe", "year": 2025},
248
+ "file_path": "research_paper.pdf",
249
+ }
250
+ }
251
+
252
+
253
+ class DocsStatusesResponse(BaseModel):
254
+ """Response model for document statuses
255
 
256
  Attributes:
257
+ statuses: Dictionary mapping document status to lists of document status responses
 
 
 
 
 
 
 
 
258
  """
259
 
260
+ statuses: Dict[DocStatus, List[DocStatusResponse]] = Field(
261
+ default_factory=dict,
262
+ description="Dictionary mapping document status to lists of document status responses",
263
+ )
 
 
 
 
 
 
 
264
 
265
+ class Config:
266
+ json_schema_extra = {
267
+ "example": {
268
+ "statuses": {
269
+ "PENDING": [
270
+ {
271
+ "id": "doc_123",
272
+ "content_summary": "Pending document",
273
+ "content_length": 5000,
274
+ "status": "PENDING",
275
+ "created_at": "2025-03-31T10:00:00",
276
+ "updated_at": "2025-03-31T10:00:00",
277
+ "file_path": "pending_doc.pdf",
278
+ }
279
+ ],
280
+ "PROCESSED": [
281
+ {
282
+ "id": "doc_456",
283
+ "content_summary": "Processed document",
284
+ "content_length": 8000,
285
+ "status": "PROCESSED",
286
+ "created_at": "2025-03-31T09:00:00",
287
+ "updated_at": "2025-03-31T09:05:00",
288
+ "chunks_count": 8,
289
+ "file_path": "processed_doc.pdf",
290
+ }
291
+ ],
292
+ }
293
+ }
294
+ }
295
 
296
 
297
  class PipelineStatusResponse(BaseModel):
 
706
  # Create combined auth dependency for document routes
707
  combined_auth = get_combined_auth_dependency(api_key)
708
 
709
+ @router.post(
710
+ "/scan", response_model=ScanResponse, dependencies=[Depends(combined_auth)]
711
+ )
712
  async def scan_for_new_documents(background_tasks: BackgroundTasks):
713
  """
714
  Trigger the scanning process for new documents.
 
718
  that fact.
719
 
720
  Returns:
721
+ ScanResponse: A response object containing the scanning status
722
  """
723
  # Start the scanning process in the background
724
  background_tasks.add_task(run_scanning_process, rag, doc_manager)
725
+ return ScanResponse(
726
+ status="scanning_started",
727
+ message="Scanning process has been initiated in the background",
728
+ )
729
 
730
+ @router.post(
731
+ "/upload", response_model=InsertResponse, dependencies=[Depends(combined_auth)]
732
+ )
733
  async def upload_to_input_dir(
734
  background_tasks: BackgroundTasks, file: UploadFile = File(...)
735
  ):
 
1200
  logger.error(traceback.format_exc())
1201
  raise HTTPException(status_code=500, detail=str(e))
1202
 
1203
+ @router.get(
1204
+ "", response_model=DocsStatusesResponse, dependencies=[Depends(combined_auth)]
1205
+ )
1206
  async def documents() -> DocsStatusesResponse:
1207
  """
1208
  Get the status of all documents in the system.