-
Notifications
You must be signed in to change notification settings - Fork 336
/
Copy pathingestion_router.py
404 lines (360 loc) · 15.6 KB
/
ingestion_router.py
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import base64
import logging
from io import BytesIO
from pathlib import Path
from typing import Optional, Union
from uuid import UUID
import yaml
from fastapi import Body, Depends, File, Form, UploadFile
from pydantic import Json
from core.base import R2RException, RawChunk, generate_document_id
from core.base.api.models import (
CreateVectorIndexResponse,
WrappedCreateVectorIndexResponse,
WrappedIngestionResponse,
WrappedUpdateResponse,
)
from core.base.providers import OrchestrationProvider, Workflow
from shared.abstractions.vector import (
IndexArgsHNSW,
IndexArgsIVFFlat,
IndexMeasure,
IndexMethod,
VectorTableName,
)
from ..services.ingestion_service import IngestionService
from .base_router import BaseRouter, RunType
logger = logging.getLogger()
class IngestionRouter(BaseRouter):
def __init__(
self,
service: IngestionService,
orchestration_provider: OrchestrationProvider,
run_type: RunType = RunType.INGESTION,
):
super().__init__(service, orchestration_provider, run_type)
self.service: IngestionService = service
def _register_workflows(self):
self.orchestration_provider.register_workflows(
Workflow.INGESTION,
self.service,
{
"ingest-files": (
"Ingest files task queued successfully."
if self.orchestration_provider.config.provider != "simple"
else "Ingestion task completed successfully."
),
"ingest-chunks": (
"Ingest chunks task queued successfully."
if self.orchestration_provider.config.provider != "simple"
else "Ingestion task completed successfully."
),
"update-files": (
"Update file task queued successfully."
if self.orchestration_provider.config.provider != "simple"
else "Update task queued successfully."
),
"create-vector-index": (
"Vector index creation task queued successfully."
if self.orchestration_provider.config.provider != "simple"
else "Vector index creation task completed successfully."
),
},
)
def _load_openapi_extras(self):
yaml_path = (
Path(__file__).parent / "data" / "ingestion_router_openapi.yml"
)
with open(yaml_path, "r") as yaml_file:
yaml_content = yaml.safe_load(yaml_file)
return yaml_content
def _setup_routes(self):
# Note, we use the following verbose input parameters because FastAPI struggles to handle `File` input and `Body` inputs
# at the same time. Therefore, we must ues `Form` inputs for the metadata, document_ids
ingest_files_extras = self.openapi_extras.get("ingest_files", {})
ingest_files_descriptions = ingest_files_extras.get(
"input_descriptions", {}
)
@self.router.post(
"/ingest_files",
openapi_extra=ingest_files_extras.get("openapi_extra"),
)
@self.base_endpoint
async def ingest_files_app(
files: list[UploadFile] = File(
..., description=ingest_files_descriptions.get("files")
),
document_ids: Optional[Json[list[UUID]]] = Form(
None,
description=ingest_files_descriptions.get("document_ids"),
),
metadatas: Optional[Json[list[dict]]] = Form(
None, description=ingest_files_descriptions.get("metadatas")
),
ingestion_config: Optional[Json[dict]] = Form(
None,
description=ingest_files_descriptions.get("ingestion_config"),
),
auth_user=Depends(self.service.providers.auth.auth_wrapper),
) -> WrappedIngestionResponse: # type: ignore
"""
Ingest files into the system.
This endpoint supports multipart/form-data requests, enabling you to ingest files and their associated metadatas into R2R.
A valid user authentication token is required to access this endpoint, as regular users can only ingest files for their own access. More expansive collection permissioning is under development.
"""
# Check if the user is a superuser
if not auth_user.is_superuser:
for metadata in metadatas or []:
if "user_id" in metadata and (
not auth_user.is_superuser
and metadata["user_id"] != str(auth_user.id)
):
raise R2RException(
status_code=403,
message="Non-superusers cannot set user_id in metadata.",
)
# If user is not a superuser, set user_id in metadata
metadata["user_id"] = str(auth_user.id)
file_datas = await self._process_files(files)
messages: list[dict[str, Union[str, None]]] = []
for it, file_data in enumerate(file_datas):
content_length = len(file_data["content"])
file_content = BytesIO(base64.b64decode(file_data["content"]))
file_data.pop("content", None)
document_id = (
document_ids[it]
if document_ids
else generate_document_id(
file_data["filename"], auth_user.id
)
)
workflow_input = {
"file_data": file_data,
"document_id": str(document_id),
"metadata": metadatas[it] if metadatas else None,
"ingestion_config": ingestion_config,
"user": auth_user.model_dump_json(),
"size_in_bytes": content_length,
"is_update": False,
}
file_name = file_data["filename"]
await self.service.providers.file.store_file(
document_id,
file_name,
file_content,
file_data["content_type"],
)
raw_message: dict[str, Union[str, None]] = await self.orchestration_provider.run_workflow( # type: ignore
"ingest-files",
{"request": workflow_input},
options={
"additional_metadata": {
"document_id": str(document_id),
}
},
)
raw_message["document_id"] = str(document_id)
messages.append(raw_message)
return messages # type: ignore
update_files_extras = self.openapi_extras.get("update_files", {})
update_files_descriptions = update_files_extras.get(
"input_descriptions", {}
)
@self.router.post(
"/update_files",
openapi_extra=update_files_extras.get("openapi_extra"),
)
@self.base_endpoint
async def update_files_app(
files: list[UploadFile] = File(
..., description=update_files_descriptions.get("files")
),
document_ids: Optional[Json[list[UUID]]] = Form(
None, description=ingest_files_descriptions.get("document_ids")
),
metadatas: Optional[Json[list[dict]]] = Form(
None, description=ingest_files_descriptions.get("metadatas")
),
ingestion_config: Optional[Json[dict]] = Form(
None,
description=ingest_files_descriptions.get("ingestion_config"),
),
auth_user=Depends(self.service.providers.auth.auth_wrapper),
) -> WrappedUpdateResponse:
"""
Update existing files in the system.
This endpoint supports multipart/form-data requests, enabling you to update files and their associated metadatas into R2R.
A valid user authentication token is required to access this endpoint, as regular users can only update their own files. More expansive collection permissioning is under development.
"""
if not auth_user.is_superuser:
for metadata in metadatas or []:
if "user_id" in metadata and metadata["user_id"] != str(
auth_user.id
):
raise R2RException(
status_code=403,
message="Non-superusers cannot set user_id in metadata.",
)
metadata["user_id"] = str(auth_user.id)
file_datas = await self._process_files(files)
processed_data = []
for it, file_data in enumerate(file_datas):
content = base64.b64decode(file_data.pop("content"))
document_id = (
document_ids[it]
if document_ids
else generate_document_id(
file_data["filename"], auth_user.id
)
)
await self.service.providers.file.store_file(
document_id,
file_data["filename"],
BytesIO(content),
file_data["content_type"],
)
processed_data.append(
{
"file_data": file_data,
"file_length": len(content),
"document_id": str(document_id),
}
)
workflow_input = {
"file_datas": [item["file_data"] for item in processed_data],
"file_sizes_in_bytes": [
item["file_length"] for item in processed_data
],
"document_ids": [
item["document_id"] for item in processed_data
],
"metadatas": metadatas,
"ingestion_config": ingestion_config,
"user": auth_user.model_dump_json(),
"is_update": True,
}
raw_message: dict[str, Union[str, None]] = await self.orchestration_provider.run_workflow( # type: ignore
"update-files", {"request": workflow_input}, {}
)
raw_message["message"] = "Update task queued successfully."
raw_message["document_ids"] = workflow_input["document_ids"]
return raw_message # type: ignore
ingest_chunks_extras = self.openapi_extras.get("ingest_chunks", {})
ingest_chunks_descriptions = ingest_chunks_extras.get(
"input_descriptions", {}
)
@self.router.post(
"/ingest_chunks",
openapi_extra=ingest_chunks_extras.get("openapi_extra"),
)
@self.base_endpoint
async def ingest_chunks_app(
chunks: list[RawChunk] = Body(
{}, description=ingest_chunks_descriptions.get("chunks")
),
document_id: Optional[str] = Body(
None, description=ingest_chunks_descriptions.get("document_id")
),
metadata: Optional[dict] = Body(
None, description=ingest_files_descriptions.get("metadata")
),
auth_user=Depends(self.service.providers.auth.auth_wrapper),
) -> WrappedIngestionResponse:
"""
Ingest text chunks into the system.
This endpoint supports multipart/form-data requests, enabling you to ingest pre-parsed text chunks into R2R.
A valid user authentication token is required to access this endpoint, as regular users can only ingest chunks for their own access. More expansive collection permissioning is under development.
"""
if document_id:
try:
document_uuid = UUID(document_id)
except ValueError:
raise R2RException(
status_code=422, message="Invalid document ID format."
)
if not document_id:
document_uuid = generate_document_id(
chunks[0].text[:20], auth_user.id
)
workflow_input = {
"document_id": str(document_uuid),
"chunks": [chunk.model_dump() for chunk in chunks],
"metadata": metadata or {},
"user": auth_user.model_dump_json(),
}
raw_message = await self.orchestration_provider.run_workflow(
"ingest-chunks",
{"request": workflow_input},
options={
"additional_metadata": {
"document_id": str(document_uuid),
}
},
)
raw_message["document_id"] = str(document_uuid)
return [raw_message] # type: ignore
@self.router.post("/create_vector_index")
@self.base_endpoint
async def create_vector_index_app(
table_name: Optional[VectorTableName] = Body(
default=VectorTableName.CHUNKS,
description="The name of the vector table to create.",
),
index_method: IndexMethod = Body(
default=IndexMethod.hnsw,
description="The type of vector index to create.",
),
measure: IndexMeasure = Body(
default=IndexMeasure.cosine_distance,
description="The measure for the index.",
),
index_arguments: Optional[
Union[IndexArgsIVFFlat, IndexArgsHNSW]
] = Body(
None,
description="The arguments for the index method.",
),
replace: bool = Body(
default=True,
description="Whether to replace an existing index.",
),
concurrently: bool = Body(
default=True,
description="Whether to create the index concurrently.",
),
auth_user=Depends(self.service.providers.auth.auth_wrapper),
) -> WrappedCreateVectorIndexResponse:
logger.info(
f"Creating vector index for {table_name} with method {index_method}, measure {measure}, replace {replace}, concurrently {concurrently}"
)
raw_message = await self.orchestration_provider.run_workflow(
"create-vector-index",
{
"request": {
"table_name": table_name,
"index_method": index_method,
"measure": measure,
"index_arguments": index_arguments,
"replace": replace,
"concurrently": concurrently,
},
},
options={
"additional_metadata": {},
},
)
return raw_message # type: ignore
@staticmethod
async def _process_files(files):
import base64
file_datas = []
for file in files:
content = await file.read()
file_datas.append(
{
"filename": file.filename,
"content": base64.b64encode(content).decode("utf-8"),
"content_type": file.content_type,
}
)
return file_datas