-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy pathdocuments_router.py
2152 lines (1943 loc) · 83.8 KB
/
documents_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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import json
import logging
import mimetypes
import textwrap
from datetime import datetime
from io import BytesIO
from typing import Any, Optional
from urllib.parse import quote
from uuid import UUID
from fastapi import Body, Depends, File, Form, Path, Query, UploadFile
from fastapi.background import BackgroundTasks
from fastapi.responses import FileResponse, StreamingResponse
from pydantic import Json
from core.base import (
IngestionConfig,
IngestionMode,
R2RException,
SearchMode,
SearchSettings,
UnprocessedChunk,
Workflow,
generate_document_id,
generate_id,
select_search_filters,
)
from core.base.abstractions import KGCreationSettings, KGRunType, StoreType
from core.base.api.models import (
GenericBooleanResponse,
WrappedBooleanResponse,
WrappedChunksResponse,
WrappedCollectionsResponse,
WrappedDocumentResponse,
WrappedDocumentsResponse,
WrappedEntitiesResponse,
WrappedGenericMessageResponse,
WrappedIngestionResponse,
WrappedRelationshipsResponse,
)
from core.utils import update_settings_from_dict
from ...abstractions import R2RProviders, R2RServices
from .base_router import BaseRouterV3
logger = logging.getLogger()
MAX_CHUNKS_PER_REQUEST = 1024 * 100
def merge_search_settings(
base: SearchSettings, overrides: SearchSettings
) -> SearchSettings:
# Convert both to dict
base_dict = base.model_dump()
overrides_dict = overrides.model_dump(exclude_unset=True)
# Update base_dict with values from overrides_dict
# This ensures that any field set in overrides takes precedence
for k, v in overrides_dict.items():
base_dict[k] = v
# Construct a new SearchSettings from the merged dict
return SearchSettings(**base_dict)
def merge_ingestion_config(
base: IngestionConfig, overrides: IngestionConfig
) -> IngestionConfig:
base_dict = base.model_dump()
overrides_dict = overrides.model_dump(exclude_unset=True)
for k, v in overrides_dict.items():
base_dict[k] = v
return IngestionConfig(**base_dict)
class DocumentsRouter(BaseRouterV3):
def __init__(
self,
providers: R2RProviders,
services: R2RServices,
):
super().__init__(providers, services)
self._register_workflows()
def _prepare_search_settings(
self,
auth_user: Any,
search_mode: SearchMode,
search_settings: Optional[SearchSettings],
) -> SearchSettings:
"""
Prepare the effective search settings based on the provided search_mode,
optional user-overrides in search_settings, and applied filters.
"""
if search_mode != SearchMode.custom:
# Start from mode defaults
effective_settings = SearchSettings.get_default(search_mode.value)
if search_settings:
# Merge user-provided overrides
effective_settings = merge_search_settings(
effective_settings, search_settings
)
else:
# Custom mode: use provided settings or defaults
effective_settings = search_settings or SearchSettings()
# Apply user-specific filters
effective_settings.filters = select_search_filters(
auth_user, effective_settings
)
return effective_settings
# TODO - Remove this legacy method
def _register_workflows(self):
self.providers.orchestration.register_workflows(
Workflow.INGESTION,
self.services.ingestion,
{
"ingest-files": (
"Ingest files task queued successfully."
if self.providers.orchestration.config.provider != "simple"
else "Document created and ingested successfully."
),
"ingest-chunks": (
"Ingest chunks task queued successfully."
if self.providers.orchestration.config.provider != "simple"
else "Document created and ingested successfully."
),
"update-files": (
"Update file task queued successfully."
if self.providers.orchestration.config.provider != "simple"
else "Update task queued successfully."
),
"update-chunk": (
"Update chunk task queued successfully."
if self.providers.orchestration.config.provider != "simple"
else "Chunk update completed successfully."
),
"update-document-metadata": (
"Update document metadata task queued successfully."
if self.providers.orchestration.config.provider != "simple"
else "Document metadata update completed successfully."
),
"create-vector-index": (
"Vector index creation task queued successfully."
if self.providers.orchestration.config.provider != "simple"
else "Vector index creation task completed successfully."
),
"delete-vector-index": (
"Vector index deletion task queued successfully."
if self.providers.orchestration.config.provider != "simple"
else "Vector index deletion task completed successfully."
),
"select-vector-index": (
"Vector index selection task queued successfully."
if self.providers.orchestration.config.provider != "simple"
else "Vector index selection task completed successfully."
),
},
)
def _prepare_ingestion_config(
self,
ingestion_mode: IngestionMode,
ingestion_config: Optional[IngestionConfig],
) -> IngestionConfig:
# If not custom, start from defaults
if ingestion_mode != IngestionMode.custom:
effective_config = IngestionConfig.get_default(
ingestion_mode.value, app=self.providers.auth.config.app
)
if ingestion_config:
effective_config = merge_ingestion_config(
effective_config, ingestion_config
)
else:
# custom mode
effective_config = ingestion_config or IngestionConfig(
app=self.providers.auth.config.app
)
effective_config.validate_config()
return effective_config
def _setup_routes(self):
@self.router.post(
"/documents",
dependencies=[Depends(self.rate_limit_dependency)],
status_code=202,
summary="Create a new document",
openapi_extra={
"x-codeSamples": [
{
"lang": "Python",
"source": textwrap.dedent(
"""
from r2r import R2RClient
client = R2RClient()
# when using auth, do client.login(...)
response = client.documents.create(
file_path="pg_essay_1.html",
metadata={"metadata_1":"some random metadata"},
id=None
)
"""
),
},
{
"lang": "JavaScript",
"source": textwrap.dedent(
"""
const { r2rClient } = require("r2r-js");
const client = new r2rClient();
function main() {
const response = await client.documents.create({
file: { path: "examples/data/marmeladov.txt", name: "marmeladov.txt" },
metadata: { title: "marmeladov.txt" },
});
}
main();
"""
),
},
{
"lang": "CLI",
"source": textwrap.dedent(
"""
r2r documents create /path/to/file.txt
"""
),
},
{
"lang": "cURL",
"source": textwrap.dedent(
"""
curl -X POST "https://api.example.com/v3/documents" \\
-H "Content-Type: multipart/form-data" \\
-H "Authorization: Bearer YOUR_API_KEY" \\
-F "file=@pg_essay_1.html;type=text/html" \\
-F 'metadata={}' \\
-F 'id=null'
"""
),
},
]
},
)
@self.base_endpoint
async def create_document(
file: Optional[UploadFile] = File(
None,
description="The file to ingest. Exactly one of file, raw_text, or chunks must be provided.",
),
raw_text: Optional[str] = Form(
None,
description="Raw text content to ingest. Exactly one of file, raw_text, or chunks must be provided.",
),
chunks: Optional[Json[list[str]]] = Form(
None,
description="Pre-processed text chunks to ingest. Exactly one of file, raw_text, or chunks must be provided.",
),
id: Optional[UUID] = Form(
None,
description="The ID of the document. If not provided, a new ID will be generated.",
),
collection_ids: Optional[Json[list[UUID]]] = Form(
None,
description="Collection IDs to associate with the document. If none are provided, the document will be assigned to the user's default collection.",
),
metadata: Optional[Json[dict]] = Form(
None,
description="Metadata to associate with the document, such as title, description, or custom fields.",
),
ingestion_mode: IngestionMode = Form(
default=IngestionMode.custom,
description=(
"Ingestion modes:\n"
"- `hi-res`: Thorough ingestion with full summaries and enrichment.\n"
"- `fast`: Quick ingestion with minimal enrichment and no summaries.\n"
"- `custom`: Full control via `ingestion_config`.\n\n"
"If `filters` or `limit` (in `ingestion_config`) are provided alongside `hi-res` or `fast`, "
"they will override the default settings for that mode."
),
),
ingestion_config: Optional[Json[IngestionConfig]] = Form(
None,
description="An optional dictionary to override the default chunking configuration for the ingestion process. If not provided, the system will use the default server-side chunking configuration.",
),
run_with_orchestration: Optional[bool] = Form(
True,
description="Whether or not ingestion runs with orchestration, default is `True`. When set to `False`, the ingestion process will run synchronous and directly return the result.",
),
auth_user=Depends(self.providers.auth.auth_wrapper()),
) -> WrappedIngestionResponse:
"""
Creates a new Document object from an input file, text content, or chunks. The chosen `ingestion_mode` determines
how the ingestion process is configured:
**Ingestion Modes:**
- `hi-res`: Comprehensive parsing and enrichment, including summaries and possibly more thorough parsing.
- `fast`: Speed-focused ingestion that skips certain enrichment steps like summaries.
- `custom`: Provide a full `ingestion_config` to customize the entire ingestion process.
Either a file or text content must be provided, but not both. Documents are shared through `Collections` which allow for tightly specified cross-user interactions.
The ingestion process runs asynchronously and its progress can be tracked using the returned
task_id.
"""
if not auth_user.is_superuser:
user_document_count = (
await self.services.management.documents_overview(
user_ids=[auth_user.id],
offset=0,
limit=1,
)
)["total_entries"]
user_max_documents = (
await self.services.management.get_user_max_documents(
auth_user.id
)
)
if user_document_count >= user_max_documents:
raise R2RException(
status_code=403,
message=f"User has reached the maximum number of documents allowed ({user_max_documents}).",
)
# Get chunks using the vector handler's list_chunks method
user_chunk_count = (
await self.services.ingestion.list_chunks(
filters={"owner_id": {"$eq": str(auth_user.id)}},
offset=0,
limit=1,
)
)["page_info"]["total_entries"]
user_max_chunks = (
await self.services.management.get_user_max_chunks(
auth_user.id
)
)
if user_chunk_count >= user_max_chunks:
raise R2RException(
status_code=403,
message=f"User has reached the maximum number of chunks allowed ({user_max_chunks}).",
)
user_collections_count = (
await self.services.management.collections_overview(
user_ids=[auth_user.id],
offset=0,
limit=1,
)
)["total_entries"]
user_max_collections = (
await self.services.management.get_user_max_collections(
auth_user.id
)
)
if user_collections_count >= user_max_collections:
raise R2RException(
status_code=403,
message=f"User has reached the maximum number of collections allowed ({user_max_collections}).",
)
effective_ingestion_config = self._prepare_ingestion_config(
ingestion_mode=ingestion_mode,
ingestion_config=ingestion_config,
)
if not file and not raw_text and not chunks:
raise R2RException(
status_code=422,
message="Either a `file`, `raw_text`, or `chunks` must be provided.",
)
if (
(file and raw_text)
or (file and chunks)
or (raw_text and chunks)
):
raise R2RException(
status_code=422,
message="Only one of `file`, `raw_text`, or `chunks` may be provided.",
)
# Check if the user is a superuser
metadata = metadata or {}
if chunks:
if len(chunks) == 0:
raise R2RException("Empty list of chunks provided", 400)
if len(chunks) > MAX_CHUNKS_PER_REQUEST:
raise R2RException(
f"Maximum of {MAX_CHUNKS_PER_REQUEST} chunks per request",
400,
)
document_id = generate_document_id(
json.dumps(chunks), auth_user.id
)
# FIXME: Metadata doesn't seem to be getting passed through
raw_chunks_for_doc = [
UnprocessedChunk(
text=chunk,
metadata=metadata,
id=generate_id(),
)
for chunk in chunks
]
# Prepare workflow input
workflow_input = {
"document_id": str(document_id),
"chunks": [
chunk.model_dump(mode="json")
for chunk in raw_chunks_for_doc
],
"metadata": metadata, # Base metadata for the document
"user": auth_user.model_dump_json(),
"ingestion_config": effective_ingestion_config.model_dump(
mode="json"
),
}
# TODO - Modify create_chunks so that we can add chunks to existing document
if run_with_orchestration:
# Run ingestion with orchestration
raw_message = (
await self.providers.orchestration.run_workflow(
"ingest-chunks",
{"request": workflow_input},
options={
"additional_metadata": {
"document_id": str(document_id),
}
},
)
)
raw_message["document_id"] = str(document_id)
return raw_message # type: ignore
else:
logger.info(
"Running chunk ingestion without orchestration."
)
from core.main.orchestration import (
simple_ingestion_factory,
)
simple_ingestor = simple_ingestion_factory(
self.services.ingestion
)
await simple_ingestor["ingest-chunks"](workflow_input)
return { # type: ignore
"message": "Document created and ingested successfully.",
"document_id": str(document_id),
"task_id": None,
}
else:
if file:
file_data = await self._process_file(file)
content_length = len(file_data["content"])
file_ext = file.filename.split(".")[
-1
] # e.g. "pdf", "txt"
max_allowed_size = await self.services.management.get_max_upload_size_by_type(
user_id=auth_user.id, file_type_or_ext=file_ext
)
if content_length > max_allowed_size:
raise R2RException(
status_code=413, # HTTP 413: Payload Too Large
message=(
f"File size exceeds maximum of {max_allowed_size} bytes "
f"for extension '{file_ext}'."
),
)
file_content = BytesIO(
base64.b64decode(file_data["content"])
)
file_data.pop("content", None)
document_id = id or generate_document_id(
file_data["filename"], auth_user.id
)
elif raw_text:
content_length = len(raw_text)
file_content = BytesIO(raw_text.encode("utf-8"))
document_id = id or generate_document_id(
raw_text, auth_user.id
)
file_data = {
"filename": "N/A",
"content_type": "text/plain",
}
else:
raise R2RException(
status_code=422,
message="Either a file or content must be provided.",
)
workflow_input = {
"file_data": file_data,
"document_id": str(document_id),
"collection_ids": (
[str(cid) for cid in collection_ids]
if collection_ids
else None
),
"metadata": metadata,
"ingestion_config": effective_ingestion_config.model_dump(
mode="json"
),
"user": auth_user.model_dump_json(),
"size_in_bytes": content_length,
}
file_name = file_data["filename"]
await self.providers.database.files_handler.store_file(
document_id,
file_name,
file_content,
file_data["content_type"],
)
if run_with_orchestration:
raw_message: dict[str, str | None] = await self.providers.orchestration.run_workflow( # type: ignore
"ingest-files",
{"request": workflow_input},
options={
"additional_metadata": {
"document_id": str(document_id),
}
},
)
raw_message["document_id"] = str(document_id)
return raw_message # type: ignore
else:
logger.info(
f"Running ingestion without orchestration for file {file_name} and document_id {document_id}."
)
# TODO - Clean up implementation logic here to be more explicitly `synchronous`
from core.main.orchestration import simple_ingestion_factory
simple_ingestor = simple_ingestion_factory(
self.services.ingestion
)
await simple_ingestor["ingest-files"](workflow_input)
return { # type: ignore
"message": "Document created and ingested successfully.",
"document_id": str(document_id),
"task_id": None,
}
@self.router.post(
"/documents/export",
summary="Export documents to CSV",
dependencies=[Depends(self.rate_limit_dependency)],
openapi_extra={
"x-codeSamples": [
{
"lang": "Python",
"source": textwrap.dedent(
"""
from r2r import R2RClient
client = R2RClient("http://localhost:7272")
# when using auth, do client.login(...)
response = client.documents.export(
output_path="export.csv",
columns=["id", "title", "created_at"],
include_header=True,
)
"""
),
},
{
"lang": "JavaScript",
"source": textwrap.dedent(
"""
const { r2rClient } = require("r2r-js");
const client = new r2rClient("http://localhost:7272");
function main() {
await client.documents.export({
outputPath: "export.csv",
columns: ["id", "title", "created_at"],
includeHeader: true,
});
}
main();
"""
),
},
{
"lang": "CLI",
"source": textwrap.dedent(
"""
"""
),
},
{
"lang": "cURL",
"source": textwrap.dedent(
"""
curl -X POST "http://127.0.0.1:7272/v3/documents/export" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Accept: text/csv" \
-d '{ "columns": ["id", "title", "created_at"], "include_header": true }' \
--output export.csv
"""
),
},
]
},
)
@self.base_endpoint
async def export_documents(
background_tasks: BackgroundTasks,
columns: Optional[list[str]] = Body(
None, description="Specific columns to export"
),
filters: Optional[dict] = Body(
None, description="Filters to apply to the export"
),
include_header: Optional[bool] = Body(
True, description="Whether to include column headers"
),
auth_user=Depends(self.providers.auth.auth_wrapper()),
) -> FileResponse:
"""
Export documents as a downloadable CSV file.
"""
if not auth_user.is_superuser:
raise R2RException(
"Only a superuser can export data.",
403,
)
csv_file_path, temp_file = (
await self.services.management.export_documents(
columns=columns,
filters=filters,
include_header=include_header,
)
)
background_tasks.add_task(temp_file.close)
return FileResponse(
path=csv_file_path,
media_type="text/csv",
filename="documents_export.csv",
)
@self.router.get(
"/documents/download_zip",
dependencies=[Depends(self.rate_limit_dependency)],
response_class=StreamingResponse,
summary="Export multiple documents as zip",
openapi_extra={
"x-codeSamples": [
{
"lang": "Python",
"source": textwrap.dedent(
"""
client.documents.download_zip(
document_ids=["uuid1", "uuid2"],
start_date="2024-01-01",
end_date="2024-12-31"
)
"""
),
},
{
"lang": "cURL",
"source": textwrap.dedent(
"""
curl -X GET "https://api.example.com/v3/documents/download_zip?document_ids=uuid1,uuid2&start_date=2024-01-01&end_date=2024-12-31" \\
-H "Authorization: Bearer YOUR_API_KEY"
"""
),
},
]
},
)
@self.base_endpoint
async def export_files(
document_ids: Optional[list[UUID]] = Query(
None,
description="List of document IDs to include in the export. If not provided, all accessible documents will be included.",
),
start_date: Optional[datetime] = Query(
None,
description="Filter documents created on or after this date.",
),
end_date: Optional[datetime] = Query(
None,
description="Filter documents created before this date.",
),
auth_user=Depends(self.providers.auth.auth_wrapper()),
) -> StreamingResponse:
"""
Export multiple documents as a zip file. Documents can be filtered by IDs and/or date range.
The endpoint allows downloading:
- Specific documents by providing their IDs
- Documents within a date range
- All accessible documents if no filters are provided
Files are streamed as a zip archive to handle potentially large downloads efficiently.
"""
if not auth_user.is_superuser:
# For non-superusers, verify access to requested documents
if document_ids:
documents_overview = (
await self.services.management.documents_overview(
user_ids=[auth_user.id],
document_ids=document_ids,
offset=0,
limit=len(document_ids),
)
)
if len(documents_overview["results"]) != len(document_ids):
raise R2RException(
status_code=403,
message="You don't have access to one or more requested documents.",
)
if not document_ids:
raise R2RException(
status_code=403,
message="Non-superusers must provide document IDs to export.",
)
zip_name, zip_content, zip_size = (
await self.services.management.export_files(
document_ids=document_ids,
start_date=start_date,
end_date=end_date,
)
)
encoded_filename = quote(zip_name)
async def stream_file():
yield zip_content.getvalue()
return StreamingResponse(
stream_file(),
media_type="application/zip",
headers={
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}",
"Content-Length": str(zip_size),
},
)
@self.router.get(
"/documents",
dependencies=[Depends(self.rate_limit_dependency)],
summary="List documents",
openapi_extra={
"x-codeSamples": [
{
"lang": "Python",
"source": textwrap.dedent(
"""
from r2r import R2RClient
client = R2RClient()
# when using auth, do client.login(...)
response = client.documents.list(
limit=10,
offset=0
)
"""
),
},
{
"lang": "JavaScript",
"source": textwrap.dedent(
"""
const { r2rClient } = require("r2r-js");
const client = new r2rClient();
function main() {
const response = await client.documents.list({
limit: 10,
offset: 0,
});
}
main();
"""
),
},
{
"lang": "CLI",
"source": textwrap.dedent(
"""
r2r documents create /path/to/file.txt
"""
),
},
{
"lang": "cURL",
"source": textwrap.dedent(
"""
curl -X GET "https://api.example.com/v3/documents" \\
-H "Authorization: Bearer YOUR_API_KEY"
"""
),
},
]
},
)
@self.base_endpoint
async def get_documents(
ids: list[str] = Query(
[],
description="A list of document IDs to retrieve. If not provided, all documents will be returned.",
),
offset: int = Query(
0,
ge=0,
description="Specifies the number of objects to skip. Defaults to 0.",
),
limit: int = Query(
100,
ge=1,
le=1000,
description="Specifies a limit on the number of objects to return, ranging between 1 and 100. Defaults to 100.",
),
include_summary_embeddings: int = Query(
False,
description="Specifies whether or not to include embeddings of each document summary.",
),
auth_user=Depends(self.providers.auth.auth_wrapper()),
) -> WrappedDocumentsResponse:
"""
Returns a paginated list of documents the authenticated user has access to.
Results can be filtered by providing specific document IDs. Regular users will only see
documents they own or have access to through collections. Superusers can see all documents.
The documents are returned in order of last modification, with most recent first.
"""
requesting_user_id = (
None if auth_user.is_superuser else [auth_user.id]
)
filter_collection_ids = (
None if auth_user.is_superuser else auth_user.collection_ids
)
document_uuids = [UUID(document_id) for document_id in ids]
documents_overview_response = (
await self.services.management.documents_overview(
user_ids=requesting_user_id,
collection_ids=filter_collection_ids,
document_ids=document_uuids,
offset=offset,
limit=limit,
)
)
if not include_summary_embeddings:
for document in documents_overview_response["results"]:
document.summary_embedding = None
return ( # type: ignore
documents_overview_response["results"],
{
"total_entries": documents_overview_response[
"total_entries"
]
},
)
@self.router.get(
"/documents/{id}",
dependencies=[Depends(self.rate_limit_dependency)],
summary="Retrieve a document",
openapi_extra={
"x-codeSamples": [
{
"lang": "Python",
"source": textwrap.dedent(
"""
from r2r import R2RClient
client = R2RClient()
# when using auth, do client.login(...)
response = client.documents.retrieve(
id="b4ac4dd6-5f27-596e-a55b-7cf242ca30aa"
)
"""
),
},
{
"lang": "JavaScript",
"source": textwrap.dedent(
"""
const { r2rClient } = require("r2r-js");
const client = new r2rClient();
function main() {
const response = await client.documents.retrieve({
id: "b4ac4dd6-5f27-596e-a55b-7cf242ca30aa",
});
}
main();
"""
),
},
{
"lang": "CLI",
"source": textwrap.dedent(
"""
r2r documents retrieve b4ac4dd6-5f27-596e-a55b-7cf242ca30aa
"""
),
},
{
"lang": "cURL",
"source": textwrap.dedent(
"""
curl -X GET "https://api.example.com/v3/documents/b4ac4dd6-5f27-596e-a55b-7cf242ca30aa" \\
-H "Authorization: Bearer YOUR_API_KEY"
"""
),
},
]
},
)
@self.base_endpoint
async def get_document(
id: UUID = Path(
...,
description="The ID of the document to retrieve.",
),
auth_user=Depends(self.providers.auth.auth_wrapper()),
) -> WrappedDocumentResponse:
"""
Retrieves detailed information about a specific document by its ID.
This endpoint returns the document's metadata, status, and system information. It does not
return the document's content - use the `/documents/{id}/download` endpoint for that.
Users can only retrieve documents they own or have access to through collections.
Superusers can retrieve any document.
"""
request_user_ids = (
None if auth_user.is_superuser else [auth_user.id]
)
filter_collection_ids = (
None if auth_user.is_superuser else auth_user.collection_ids
)
documents_overview_response = await self.services.management.documents_overview( # FIXME: This was using the pagination defaults from before... We need to review if this is as intended.
user_ids=request_user_ids,
collection_ids=filter_collection_ids,
document_ids=[id],
offset=0,
limit=100,
)
results = documents_overview_response["results"]
if len(results) == 0:
raise R2RException("Document not found.", 404)
return results[0]
@self.router.get(
"/documents/{id}/chunks",
dependencies=[Depends(self.rate_limit_dependency)],
summary="List document chunks",
openapi_extra={
"x-codeSamples": [
{
"lang": "Python",
"source": textwrap.dedent(