documents_router.py 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359
  1. import base64
  2. import logging
  3. import mimetypes
  4. import textwrap
  5. from datetime import datetime
  6. from io import BytesIO
  7. from typing import Any, Optional
  8. from urllib.parse import quote
  9. from uuid import UUID
  10. from fastapi import Body, Depends, File, Form, Path, Query, UploadFile
  11. from fastapi.background import BackgroundTasks
  12. from fastapi.responses import FileResponse, StreamingResponse
  13. from pydantic import Json
  14. from core.base import (
  15. IngestionConfig,
  16. R2RException,
  17. SearchMode,
  18. SearchSettings,
  19. UnprocessedChunk,
  20. Workflow,
  21. generate_document_id,
  22. generate_id,
  23. select_search_filters,
  24. )
  25. from core.base.abstractions import GraphCreationSettings, StoreType
  26. from core.base.api.models import (
  27. GenericBooleanResponse,
  28. WrappedBooleanResponse,
  29. WrappedChunksResponse,
  30. WrappedCollectionsResponse,
  31. WrappedDocumentResponse,
  32. WrappedDocumentSearchResponse,
  33. WrappedDocumentsResponse,
  34. WrappedEntitiesResponse,
  35. WrappedGenericMessageResponse,
  36. WrappedIngestionResponse,
  37. WrappedRelationshipsResponse,
  38. )
  39. from core.utils import update_settings_from_dict
  40. from shared.abstractions import IngestionMode
  41. from ...abstractions import R2RProviders, R2RServices
  42. from ...config import R2RConfig
  43. from .base_router import BaseRouterV3
  44. logger = logging.getLogger()
  45. MAX_CHUNKS_PER_REQUEST = 1024 * 100
  46. def merge_search_settings(
  47. base: SearchSettings, overrides: SearchSettings
  48. ) -> SearchSettings:
  49. # Convert both to dict
  50. base_dict = base.model_dump()
  51. overrides_dict = overrides.model_dump(exclude_unset=True)
  52. # Update base_dict with values from overrides_dict
  53. # This ensures that any field set in overrides takes precedence
  54. for k, v in overrides_dict.items():
  55. base_dict[k] = v
  56. # Construct a new SearchSettings from the merged dict
  57. return SearchSettings(**base_dict)
  58. def merge_ingestion_config(
  59. base: IngestionConfig, overrides: IngestionConfig
  60. ) -> IngestionConfig:
  61. base_dict = base.model_dump()
  62. overrides_dict = overrides.model_dump(exclude_unset=True)
  63. for k, v in overrides_dict.items():
  64. base_dict[k] = v
  65. return IngestionConfig(**base_dict)
  66. class DocumentsRouter(BaseRouterV3):
  67. def __init__(
  68. self,
  69. providers: R2RProviders,
  70. services: R2RServices,
  71. config: R2RConfig,
  72. ):
  73. logging.info("Initializing DocumentsRouter")
  74. super().__init__(providers, services, config)
  75. self._register_workflows()
  76. def _prepare_search_settings(
  77. self,
  78. auth_user: Any,
  79. search_mode: SearchMode,
  80. search_settings: Optional[SearchSettings],
  81. ) -> SearchSettings:
  82. """Prepare the effective search settings based on the provided
  83. search_mode, optional user-overrides in search_settings, and applied
  84. filters."""
  85. if search_mode != SearchMode.custom:
  86. # Start from mode defaults
  87. effective_settings = SearchSettings.get_default(search_mode.value)
  88. if search_settings:
  89. # Merge user-provided overrides
  90. effective_settings = merge_search_settings(
  91. effective_settings, search_settings
  92. )
  93. else:
  94. # Custom mode: use provided settings or defaults
  95. effective_settings = search_settings or SearchSettings()
  96. # Apply user-specific filters
  97. effective_settings.filters = select_search_filters(
  98. auth_user, effective_settings
  99. )
  100. return effective_settings
  101. # TODO - Remove this legacy method
  102. def _register_workflows(self):
  103. self.providers.orchestration.register_workflows(
  104. Workflow.INGESTION,
  105. self.services.ingestion,
  106. {
  107. "ingest-files": (
  108. "Ingest files task queued successfully."
  109. if self.providers.orchestration.config.provider != "simple"
  110. else "Document created and ingested successfully."
  111. ),
  112. "ingest-chunks": (
  113. "Ingest chunks task queued successfully."
  114. if self.providers.orchestration.config.provider != "simple"
  115. else "Document created and ingested successfully."
  116. ),
  117. "update-chunk": (
  118. "Update chunk task queued successfully."
  119. if self.providers.orchestration.config.provider != "simple"
  120. else "Chunk update completed successfully."
  121. ),
  122. "create-vector-index": (
  123. "Vector index creation task queued successfully."
  124. if self.providers.orchestration.config.provider != "simple"
  125. else "Vector index creation task completed successfully."
  126. ),
  127. "delete-vector-index": (
  128. "Vector index deletion task queued successfully."
  129. if self.providers.orchestration.config.provider != "simple"
  130. else "Vector index deletion task completed successfully."
  131. ),
  132. "select-vector-index": (
  133. "Vector index selection task queued successfully."
  134. if self.providers.orchestration.config.provider != "simple"
  135. else "Vector index selection task completed successfully."
  136. ),
  137. },
  138. )
  139. def _prepare_ingestion_config(
  140. self,
  141. ingestion_mode: IngestionMode,
  142. ingestion_config: Optional[IngestionConfig],
  143. ) -> IngestionConfig:
  144. # If not custom, start from defaults
  145. if ingestion_mode != IngestionMode.custom:
  146. effective_config = IngestionConfig.get_default(
  147. ingestion_mode.value, app=self.providers.auth.config.app
  148. )
  149. if ingestion_config:
  150. effective_config = merge_ingestion_config(
  151. effective_config, ingestion_config
  152. )
  153. else:
  154. effective_config = ingestion_config or IngestionConfig(
  155. app=self.providers.auth.config.app
  156. )
  157. effective_config.validate_config()
  158. return effective_config
  159. def _setup_routes(self):
  160. @self.router.post(
  161. "/documents",
  162. dependencies=[Depends(self.rate_limit_dependency)],
  163. status_code=202,
  164. summary="Create a new document",
  165. openapi_extra={
  166. "x-codeSamples": [
  167. {
  168. "lang": "Python",
  169. "source": textwrap.dedent("""
  170. from r2r import R2RClient
  171. client = R2RClient()
  172. # when using auth, do client.login(...)
  173. response = client.documents.create(
  174. file_path="pg_essay_1.html",
  175. metadata={"metadata_1":"some random metadata"},
  176. id=None
  177. )
  178. """),
  179. },
  180. {
  181. "lang": "JavaScript",
  182. "source": textwrap.dedent("""
  183. const { r2rClient } = require("r2r-js");
  184. const client = new r2rClient();
  185. function main() {
  186. const response = await client.documents.create({
  187. file: { path: "examples/data/marmeladov.txt", name: "marmeladov.txt" },
  188. metadata: { title: "marmeladov.txt" },
  189. });
  190. }
  191. main();
  192. """),
  193. },
  194. {
  195. "lang": "cURL",
  196. "source": textwrap.dedent("""
  197. curl -X POST "https://api.example.com/v3/documents" \\
  198. -H "Content-Type: multipart/form-data" \\
  199. -H "Authorization: Bearer YOUR_API_KEY" \\
  200. -F "file=@pg_essay_1.html;type=text/html" \\
  201. -F 'metadata={}' \\
  202. -F 'id=null'
  203. """),
  204. },
  205. ]
  206. },
  207. )
  208. @self.base_endpoint
  209. async def create_document(
  210. file: Optional[UploadFile] = File(
  211. None,
  212. description="The file to ingest. Exactly one of file, raw_text, or chunks must be provided.",
  213. ),
  214. raw_text: Optional[str] = Form(
  215. None,
  216. description="Raw text content to ingest. Exactly one of file, raw_text, or chunks must be provided.",
  217. ),
  218. chunks: Optional[Json[list[str]]] = Form(
  219. None,
  220. description="Pre-processed text chunks to ingest. Exactly one of file, raw_text, or chunks must be provided.",
  221. ),
  222. id: Optional[UUID] = Form(
  223. None,
  224. description="The ID of the document. If not provided, a new ID will be generated.",
  225. ),
  226. collection_ids: Optional[Json[list[UUID]]] = Form(
  227. None,
  228. description="Collection IDs to associate with the document. If none are provided, the document will be assigned to the user's default collection.",
  229. ),
  230. metadata: Optional[Json[dict]] = Form(
  231. None,
  232. description="Metadata to associate with the document, such as title, description, or custom fields.",
  233. ),
  234. ingestion_mode: IngestionMode = Form(
  235. default=IngestionMode.custom,
  236. description=(
  237. "Ingestion modes:\n"
  238. "- `hi-res`: Thorough ingestion with full summaries and enrichment.\n"
  239. "- `ocr`: OCR via Mistral and full summaries.\n"
  240. "- `fast`: Quick ingestion with minimal enrichment and no summaries.\n"
  241. "- `custom`: Full control via `ingestion_config`.\n\n"
  242. "If `filters` or `limit` (in `ingestion_config`) are provided alongside `hi-res` or `fast`, "
  243. "they will override the default settings for that mode."
  244. ),
  245. ),
  246. ingestion_config: Optional[Json[IngestionConfig]] = Form(
  247. None,
  248. 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.",
  249. ),
  250. run_with_orchestration: Optional[bool] = Form(
  251. True,
  252. 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.",
  253. ),
  254. auth_user=Depends(self.providers.auth.auth_wrapper()),
  255. ) -> WrappedIngestionResponse:
  256. """
  257. Creates a new Document object from an input file, text content, or chunks. The chosen `ingestion_mode` determines
  258. how the ingestion process is configured:
  259. **Ingestion Modes:**
  260. - `hi-res`: Comprehensive parsing and enrichment, including summaries and possibly more thorough parsing.
  261. - `fast`: Speed-focused ingestion that skips certain enrichment steps like summaries.
  262. - `custom`: Provide a full `ingestion_config` to customize the entire ingestion process.
  263. 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.
  264. The ingestion process runs asynchronously and its progress can be tracked using the returned
  265. task_id.
  266. """
  267. if not auth_user.is_superuser:
  268. user_document_count = 0
  269. '''
  270. (
  271. await self.services.management.documents_overview(
  272. user_ids=[auth_user.id],
  273. offset=0,
  274. limit=1,
  275. )
  276. )["total_entries"]
  277. '''
  278. user_max_documents = (
  279. await self.services.management.get_user_max_documents(
  280. auth_user.id
  281. )
  282. )
  283. if user_document_count >= user_max_documents:
  284. raise R2RException(
  285. status_code=403,
  286. message=f"User has reached the maximum number of documents allowed ({user_max_documents}).",
  287. )
  288. # Get chunks using the vector handler's list_chunks method
  289. user_chunk_count = 0
  290. '''
  291. (
  292. await self.services.ingestion.list_chunks(
  293. filters={"owner_id": {"$eq": str(auth_user.id)}},
  294. offset=0,
  295. limit=1,
  296. )
  297. )["total_entries"]
  298. '''
  299. user_max_chunks = (
  300. await self.services.management.get_user_max_chunks(
  301. auth_user.id
  302. )
  303. )
  304. if user_chunk_count >= user_max_chunks:
  305. raise R2RException(
  306. status_code=403,
  307. message=f"User has reached the maximum number of chunks allowed ({user_max_chunks}).",
  308. )
  309. user_collections_count = 0
  310. '''
  311. (
  312. await self.services.management.collections_overview(
  313. user_ids=[auth_user.id],
  314. offset=0,
  315. limit=1,
  316. )
  317. )["total_entries"]
  318. '''
  319. user_max_collections = (
  320. await self.services.management.get_user_max_collections(
  321. auth_user.id
  322. )
  323. )
  324. if user_collections_count >= user_max_collections: # type: ignore
  325. raise R2RException(
  326. status_code=403,
  327. message=f"User has reached the maximum number of collections allowed ({user_max_collections}).",
  328. )
  329. effective_ingestion_config = self._prepare_ingestion_config(
  330. ingestion_mode=ingestion_mode,
  331. ingestion_config=ingestion_config,
  332. )
  333. if not file and not raw_text and not chunks:
  334. raise R2RException(
  335. status_code=422,
  336. message="Either a `file`, `raw_text`, or `chunks` must be provided.",
  337. )
  338. if (
  339. (file and raw_text)
  340. or (file and chunks)
  341. or (raw_text and chunks)
  342. ):
  343. raise R2RException(
  344. status_code=422,
  345. message="Only one of `file`, `raw_text`, or `chunks` may be provided.",
  346. )
  347. # Check if the user is a superuser
  348. metadata = metadata or {}
  349. if chunks:
  350. if len(chunks) == 0:
  351. raise R2RException("Empty list of chunks provided", 400)
  352. if len(chunks) > MAX_CHUNKS_PER_REQUEST:
  353. raise R2RException(
  354. f"Maximum of {MAX_CHUNKS_PER_REQUEST} chunks per request",
  355. 400,
  356. )
  357. document_id = id or generate_document_id(
  358. "".join(chunks), auth_user.id
  359. )
  360. # FIXME: Metadata doesn't seem to be getting passed through
  361. raw_chunks_for_doc = [
  362. UnprocessedChunk(
  363. text=chunk,
  364. metadata=metadata,
  365. id=generate_id(),
  366. )
  367. for chunk in chunks
  368. ]
  369. # Prepare workflow input
  370. workflow_input = {
  371. "document_id": str(document_id),
  372. "chunks": [
  373. chunk.model_dump(mode="json")
  374. for chunk in raw_chunks_for_doc
  375. ],
  376. "collection_ids": (
  377. [str(cid) for cid in collection_ids]
  378. if collection_ids
  379. else None
  380. ),
  381. "metadata": metadata, # Base metadata for the document
  382. "user": auth_user.model_dump_json(),
  383. "ingestion_config": effective_ingestion_config.model_dump(
  384. mode="json"
  385. ),
  386. }
  387. if run_with_orchestration:
  388. try:
  389. # Run ingestion with orchestration
  390. raw_message = (
  391. await self.providers.orchestration.run_workflow(
  392. "ingest-chunks",
  393. {"request": workflow_input},
  394. options={
  395. "additional_metadata": {
  396. "document_id": str(document_id),
  397. }
  398. },
  399. )
  400. )
  401. raw_message["document_id"] = str(document_id)
  402. return raw_message # type: ignore
  403. except Exception as e: # TODO: Need to find specific errors that we should be excepting (gRPC most likely?)
  404. logger.error(
  405. f"Error running orchestrated ingestion: {e} \n\nAttempting to run without orchestration."
  406. )
  407. logger.info("Running chunk ingestion without orchestration.")
  408. from core.main.orchestration import simple_ingestion_factory
  409. simple_ingestor = simple_ingestion_factory(
  410. self.services.ingestion
  411. )
  412. await simple_ingestor["ingest-chunks"](workflow_input)
  413. return { # type: ignore
  414. "message": "Document created and ingested successfully.",
  415. "document_id": str(document_id),
  416. "task_id": None,
  417. }
  418. else:
  419. if file:
  420. file_data = await self._process_file(file)
  421. if metadata.get("title"):
  422. file_data["filename"] = metadata["title"]
  423. if not file_data["filename"]:
  424. raise R2RException(
  425. status_code=422,
  426. message="Uploaded file must have a filename.",
  427. )
  428. file_ext = file_data["filename"].split(".")[
  429. -1
  430. ] # e.g. "pdf", "txt"
  431. max_allowed_size = await self.services.management.get_max_upload_size_by_type(
  432. user_id=auth_user.id, file_type_or_ext=file_ext
  433. )
  434. content_length = file_data["content_length"]
  435. if content_length > max_allowed_size:
  436. raise R2RException(
  437. status_code=413, # HTTP 413: Payload Too Large
  438. message=(
  439. f"File size exceeds maximum of {max_allowed_size} bytes "
  440. f"for extension '{file_ext}'."
  441. ),
  442. )
  443. file_content = BytesIO(
  444. base64.b64decode(file_data["content"])
  445. )
  446. file_data.pop("content", None)
  447. document_id = id or generate_document_id(
  448. file_data["filename"], auth_user.id
  449. )
  450. elif raw_text:
  451. content_length = len(raw_text)
  452. file_content = BytesIO(raw_text.encode("utf-8"))
  453. document_id = id or generate_document_id(
  454. raw_text, auth_user.id
  455. )
  456. title = metadata.get("title", None)
  457. title = title + ".txt" if title else None
  458. file_data = {
  459. "filename": title or "N/A",
  460. "content_type": "text/plain",
  461. }
  462. else:
  463. raise R2RException(
  464. status_code=422,
  465. message="Either a file or content must be provided.",
  466. )
  467. workflow_input = {
  468. "file_data": file_data,
  469. "document_id": str(document_id),
  470. "collection_ids": (
  471. [str(cid) for cid in collection_ids]
  472. if collection_ids
  473. else None
  474. ),
  475. "metadata": metadata,
  476. "ingestion_config": effective_ingestion_config.model_dump(
  477. mode="json"
  478. ),
  479. "user": auth_user.model_dump_json(),
  480. "size_in_bytes": content_length,
  481. "version": "v0",
  482. }
  483. file_name = file_data["filename"]
  484. await self.providers.file.store_file(
  485. document_id,
  486. file_name,
  487. file_content,
  488. file_data["content_type"],
  489. )
  490. await self.services.ingestion.ingest_file_ingress(
  491. file_data=workflow_input["file_data"],
  492. user=auth_user,
  493. document_id=workflow_input["document_id"],
  494. size_in_bytes=workflow_input["size_in_bytes"],
  495. metadata=workflow_input["metadata"],
  496. version=workflow_input["version"],
  497. )
  498. if run_with_orchestration:
  499. try:
  500. # TODO - Modify create_chunks so that we can add chunks to existing document
  501. workflow_result: dict[
  502. str, str | None
  503. ] = await self.providers.orchestration.run_workflow( # type: ignore
  504. "ingest-files",
  505. {"request": workflow_input},
  506. options={
  507. "additional_metadata": {
  508. "document_id": str(document_id),
  509. }
  510. },
  511. )
  512. workflow_result["document_id"] = str(document_id)
  513. return workflow_result # type: ignore
  514. except Exception as e: # TODO: Need to find specific error (gRPC most likely?)
  515. logger.error(
  516. f"Error running orchestrated ingestion: {e} \n\nAttempting to run without orchestration."
  517. )
  518. logger.info(
  519. f"Running ingestion without orchestration for file {file_name} and document_id {document_id}."
  520. )
  521. # TODO - Clean up implementation logic here to be more explicitly `synchronous`
  522. from core.main.orchestration import simple_ingestion_factory
  523. simple_ingestor = simple_ingestion_factory(self.services.ingestion)
  524. await simple_ingestor["ingest-files"](workflow_input)
  525. return { # type: ignore
  526. "message": "Document created and ingested successfully.",
  527. "document_id": str(document_id),
  528. "task_id": None,
  529. }
  530. @self.router.patch(
  531. "/documents/{id}/metadata",
  532. dependencies=[Depends(self.rate_limit_dependency)],
  533. summary="Append metadata to a document",
  534. openapi_extra={
  535. "x-codeSamples": [
  536. {
  537. "lang": "Python",
  538. "source": textwrap.dedent("""
  539. from r2r import R2RClient
  540. client = R2RClient()
  541. # when using auth, do client.login(...)
  542. response = client.documents.append_metadata(
  543. id="9fbe403b-c11c-5aae-8ade-ef22980c3ad1",
  544. metadata=[{"key": "new_key", "value": "new_value"}]
  545. )
  546. """),
  547. },
  548. {
  549. "lang": "JavaScript",
  550. "source": textwrap.dedent("""
  551. const { r2rClient } = require("r2r-js");
  552. const client = new r2rClient();
  553. function main() {
  554. const response = await client.documents.appendMetadata({
  555. id: "9fbe403b-c11c-5aae-8ade-ef22980c3ad1",
  556. metadata: [{ key: "new_key", value: "new_value" }],
  557. });
  558. }
  559. main();
  560. """),
  561. },
  562. ]
  563. },
  564. )
  565. @self.base_endpoint
  566. async def patch_metadata(
  567. id: UUID = Path(
  568. ...,
  569. description="The ID of the document to append metadata to.",
  570. ),
  571. metadata: list[dict] = Body(
  572. ...,
  573. description="Metadata to append to the document.",
  574. ),
  575. auth_user=Depends(self.providers.auth.auth_wrapper()),
  576. ) -> WrappedDocumentResponse:
  577. """Appends metadata to a document. This endpoint allows adding new metadata fields or updating existing ones."""
  578. request_user_ids = (
  579. None if auth_user.is_superuser else [auth_user.id]
  580. )
  581. documents_overview_response = (
  582. await self.services.management.documents_overview(
  583. user_ids=request_user_ids,
  584. document_ids=[id],
  585. offset=0,
  586. limit=1,
  587. )
  588. )
  589. results = documents_overview_response["results"]
  590. if len(results) == 0:
  591. raise R2RException("Document not found.", 404)
  592. return await self.services.management.update_document_metadata(
  593. document_id=id,
  594. metadata=metadata,
  595. overwrite=False,
  596. )
  597. @self.router.put(
  598. "/documents/{id}/metadata",
  599. dependencies=[Depends(self.rate_limit_dependency)],
  600. summary="Replace metadata of a document",
  601. openapi_extra={
  602. "x-codeSamples": [
  603. {
  604. "lang": "Python",
  605. "source": textwrap.dedent("""
  606. from r2r import R2RClient
  607. client = R2RClient()
  608. # when using auth, do client.login(...)
  609. response = client.documents.replace_metadata(
  610. id="9fbe403b-c11c-5aae-8ade-ef22980c3ad1",
  611. metadata=[{"key": "new_key", "value": "new_value"}]
  612. )
  613. """),
  614. },
  615. {
  616. "lang": "JavaScript",
  617. "source": textwrap.dedent("""
  618. const { r2rClient } = require("r2r-js");
  619. const client = new r2rClient();
  620. function main() {
  621. const response = await client.documents.replaceMetadata({
  622. id: "9fbe403b-c11c-5aae-8ade-ef22980c3ad1",
  623. metadata: [{ key: "new_key", value: "new_value" }],
  624. });
  625. }
  626. main();
  627. """),
  628. },
  629. ]
  630. },
  631. )
  632. @self.base_endpoint
  633. async def put_metadata(
  634. id: UUID = Path(
  635. ...,
  636. description="The ID of the document to append metadata to.",
  637. ),
  638. metadata: list[dict] = Body(
  639. ...,
  640. description="Metadata to append to the document.",
  641. ),
  642. auth_user=Depends(self.providers.auth.auth_wrapper()),
  643. ) -> WrappedDocumentResponse:
  644. """Replaces metadata in a document. This endpoint allows overwriting existing metadata fields."""
  645. request_user_ids = (
  646. None if auth_user.is_superuser else [auth_user.id]
  647. )
  648. documents_overview_response = (
  649. await self.services.management.documents_overview(
  650. user_ids=request_user_ids,
  651. document_ids=[id],
  652. offset=0,
  653. limit=1,
  654. )
  655. )
  656. results = documents_overview_response["results"]
  657. if len(results) == 0:
  658. raise R2RException("Document not found.", 404)
  659. return await self.services.management.update_document_metadata(
  660. document_id=id,
  661. metadata=metadata,
  662. overwrite=True,
  663. )
  664. @self.router.post(
  665. "/documents/export",
  666. summary="Export documents to CSV",
  667. dependencies=[Depends(self.rate_limit_dependency)],
  668. openapi_extra={
  669. "x-codeSamples": [
  670. {
  671. "lang": "Python",
  672. "source": textwrap.dedent("""
  673. from r2r import R2RClient
  674. client = R2RClient("http://localhost:7272")
  675. # when using auth, do client.login(...)
  676. response = client.documents.export(
  677. output_path="export.csv",
  678. columns=["id", "title", "created_at"],
  679. include_header=True,
  680. )
  681. """),
  682. },
  683. {
  684. "lang": "JavaScript",
  685. "source": textwrap.dedent("""
  686. const { r2rClient } = require("r2r-js");
  687. const client = new r2rClient("http://localhost:7272");
  688. function main() {
  689. await client.documents.export({
  690. outputPath: "export.csv",
  691. columns: ["id", "title", "created_at"],
  692. includeHeader: true,
  693. });
  694. }
  695. main();
  696. """),
  697. },
  698. {
  699. "lang": "cURL",
  700. "source": textwrap.dedent("""
  701. curl -X POST "http://127.0.0.1:7272/v3/documents/export" \
  702. -H "Authorization: Bearer YOUR_API_KEY" \
  703. -H "Content-Type: application/json" \
  704. -H "Accept: text/csv" \
  705. -d '{ "columns": ["id", "title", "created_at"], "include_header": true }' \
  706. --output export.csv
  707. """),
  708. },
  709. ]
  710. },
  711. )
  712. @self.base_endpoint
  713. async def export_documents(
  714. background_tasks: BackgroundTasks,
  715. columns: Optional[list[str]] = Body(
  716. None, description="Specific columns to export"
  717. ),
  718. filters: Optional[dict] = Body(
  719. None, description="Filters to apply to the export"
  720. ),
  721. include_header: Optional[bool] = Body(
  722. True, description="Whether to include column headers"
  723. ),
  724. auth_user=Depends(self.providers.auth.auth_wrapper()),
  725. ) -> FileResponse:
  726. """Export documents as a downloadable CSV file."""
  727. if not auth_user.is_superuser:
  728. raise R2RException(
  729. "Only a superuser can export data.",
  730. 403,
  731. )
  732. (
  733. csv_file_path,
  734. temp_file,
  735. ) = await self.services.management.export_documents(
  736. columns=columns,
  737. filters=filters,
  738. include_header=include_header
  739. if include_header is not None
  740. else True,
  741. )
  742. background_tasks.add_task(temp_file.close)
  743. return FileResponse(
  744. path=csv_file_path,
  745. media_type="text/csv",
  746. filename="documents_export.csv",
  747. )
  748. @self.router.get(
  749. "/documents/download_zip",
  750. dependencies=[Depends(self.rate_limit_dependency)],
  751. response_class=StreamingResponse,
  752. summary="Export multiple documents as zip",
  753. openapi_extra={
  754. "x-codeSamples": [
  755. {
  756. "lang": "Python",
  757. "source": textwrap.dedent("""
  758. client.documents.download_zip(
  759. document_ids=["uuid1", "uuid2"],
  760. start_date="2024-01-01",
  761. end_date="2024-12-31"
  762. )
  763. """),
  764. },
  765. {
  766. "lang": "cURL",
  767. "source": textwrap.dedent("""
  768. 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" \\
  769. -H "Authorization: Bearer YOUR_API_KEY"
  770. """),
  771. },
  772. ]
  773. },
  774. )
  775. @self.base_endpoint
  776. async def export_files(
  777. document_ids: Optional[list[UUID]] = Query(
  778. None,
  779. description="List of document IDs to include in the export. If not provided, all accessible documents will be included.",
  780. ),
  781. start_date: Optional[datetime] = Query(
  782. None,
  783. description="Filter documents created on or after this date.",
  784. ),
  785. end_date: Optional[datetime] = Query(
  786. None,
  787. description="Filter documents created before this date.",
  788. ),
  789. auth_user=Depends(self.providers.auth.auth_wrapper()),
  790. ) -> StreamingResponse:
  791. """Export multiple documents as a zip file. Documents can be
  792. filtered by IDs and/or date range.
  793. The endpoint allows downloading:
  794. - Specific documents by providing their IDs
  795. - Documents within a date range
  796. - All accessible documents if no filters are provided
  797. Files are streamed as a zip archive to handle potentially large downloads efficiently.
  798. """
  799. if not auth_user.is_superuser:
  800. # For non-superusers, verify access to requested documents
  801. if document_ids:
  802. documents_overview = (
  803. await self.services.management.documents_overview(
  804. user_ids=[auth_user.id],
  805. document_ids=document_ids,
  806. offset=0,
  807. limit=len(document_ids),
  808. )
  809. )
  810. if len(documents_overview["results"]) != len(document_ids):
  811. raise R2RException(
  812. status_code=403,
  813. message="You don't have access to one or more requested documents.",
  814. )
  815. if not document_ids:
  816. raise R2RException(
  817. status_code=403,
  818. message="Non-superusers must provide document IDs to export.",
  819. )
  820. (
  821. zip_name,
  822. zip_content,
  823. zip_size,
  824. ) = await self.services.management.export_files(
  825. document_ids=document_ids,
  826. start_date=start_date,
  827. end_date=end_date,
  828. )
  829. encoded_filename = quote(zip_name)
  830. async def stream_file():
  831. yield zip_content.getvalue()
  832. return StreamingResponse(
  833. stream_file(),
  834. media_type="application/zip",
  835. headers={
  836. "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}",
  837. "Content-Length": str(zip_size),
  838. },
  839. )
  840. @self.router.get(
  841. "/documents",
  842. dependencies=[Depends(self.rate_limit_dependency)],
  843. summary="List documents",
  844. openapi_extra={
  845. "x-codeSamples": [
  846. {
  847. "lang": "Python",
  848. "source": textwrap.dedent("""
  849. from r2r import R2RClient
  850. client = R2RClient()
  851. # when using auth, do client.login(...)
  852. response = client.documents.list(
  853. limit=10,
  854. offset=0
  855. )
  856. """),
  857. },
  858. {
  859. "lang": "JavaScript",
  860. "source": textwrap.dedent("""
  861. const { r2rClient } = require("r2r-js");
  862. const client = new r2rClient();
  863. function main() {
  864. const response = await client.documents.list({
  865. limit: 10,
  866. offset: 0,
  867. });
  868. }
  869. main();
  870. """),
  871. },
  872. {
  873. "lang": "cURL",
  874. "source": textwrap.dedent("""
  875. curl -X GET "https://api.example.com/v3/documents" \\
  876. -H "Authorization: Bearer YOUR_API_KEY"
  877. """),
  878. },
  879. ]
  880. },
  881. )
  882. @self.base_endpoint
  883. async def get_documents(
  884. ids: list[str] = Query(
  885. [],
  886. description="A list of document IDs to retrieve. If not provided, all documents will be returned.",
  887. ),
  888. offset: int = Query(
  889. 0,
  890. ge=0,
  891. description="Specifies the number of objects to skip. Defaults to 0.",
  892. ),
  893. limit: int = Query(
  894. 100,
  895. ge=1,
  896. le=1000,
  897. description="Specifies a limit on the number of objects to return, ranging between 1 and 100. Defaults to 100.",
  898. ),
  899. include_summary_embeddings: bool = Query(
  900. False,
  901. description="Specifies whether or not to include embeddings of each document summary.",
  902. ),
  903. owner_only: bool = Query(
  904. False,
  905. description="If true, only returns documents owned by the user, not all accessible documents.",
  906. ),
  907. auth_user=Depends(self.providers.auth.auth_wrapper()),
  908. ) -> WrappedDocumentsResponse:
  909. """Returns a paginated list of documents the authenticated user has
  910. access to.
  911. Results can be filtered by providing specific document IDs. Regular
  912. users will only see documents they own or have access to through
  913. collections. Superusers can see all documents.
  914. The documents are returned in order of last modification, with most
  915. recent first.
  916. """
  917. if auth_user.is_superuser:
  918. requesting_user_id = [auth_user.id] if owner_only else None
  919. filter_collection_ids = None
  920. else:
  921. requesting_user_id = [auth_user.id]
  922. filter_collection_ids = auth_user.collection_ids
  923. document_uuids = [UUID(document_id) for document_id in ids]
  924. documents_overview_response = (
  925. await self.services.management.documents_overview(
  926. user_ids=requesting_user_id,
  927. collection_ids=filter_collection_ids,
  928. document_ids=document_uuids,
  929. offset=offset,
  930. limit=limit,
  931. owner_only=owner_only,
  932. )
  933. )
  934. if not include_summary_embeddings:
  935. for document in documents_overview_response["results"]:
  936. document.summary_embedding = None
  937. return ( # type: ignore
  938. documents_overview_response["results"],
  939. {
  940. "total_entries": documents_overview_response[
  941. "total_entries"
  942. ]
  943. },
  944. )
  945. @self.router.get(
  946. "/documents/{id}",
  947. dependencies=[Depends(self.rate_limit_dependency)],
  948. summary="Retrieve a document",
  949. openapi_extra={
  950. "x-codeSamples": [
  951. {
  952. "lang": "Python",
  953. "source": textwrap.dedent("""
  954. from r2r import R2RClient
  955. client = R2RClient()
  956. # when using auth, do client.login(...)
  957. response = client.documents.retrieve(
  958. id="b4ac4dd6-5f27-596e-a55b-7cf242ca30aa"
  959. )
  960. """),
  961. },
  962. {
  963. "lang": "JavaScript",
  964. "source": textwrap.dedent("""
  965. const { r2rClient } = require("r2r-js");
  966. const client = new r2rClient();
  967. function main() {
  968. const response = await client.documents.retrieve({
  969. id: "b4ac4dd6-5f27-596e-a55b-7cf242ca30aa",
  970. });
  971. }
  972. main();
  973. """),
  974. },
  975. {
  976. "lang": "cURL",
  977. "source": textwrap.dedent("""
  978. curl -X GET "https://api.example.com/v3/documents/b4ac4dd6-5f27-596e-a55b-7cf242ca30aa" \\
  979. -H "Authorization: Bearer YOUR_API_KEY"
  980. """),
  981. },
  982. ]
  983. },
  984. )
  985. @self.base_endpoint
  986. async def get_document(
  987. id: UUID = Path(
  988. ...,
  989. description="The ID of the document to retrieve.",
  990. ),
  991. auth_user=Depends(self.providers.auth.auth_wrapper()),
  992. ) -> WrappedDocumentResponse:
  993. """Retrieves detailed information about a specific document by its
  994. ID.
  995. This endpoint returns the document's metadata, status, and system information. It does not
  996. return the document's content - use the `/documents/{id}/download` endpoint for that.
  997. Users can only retrieve documents they own or have access to through collections.
  998. Superusers can retrieve any document.
  999. """
  1000. request_user_ids = (
  1001. None if auth_user.is_superuser else [auth_user.id]
  1002. )
  1003. filter_collection_ids = (
  1004. None if auth_user.is_superuser else auth_user.collection_ids
  1005. )
  1006. 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.
  1007. user_ids=request_user_ids,
  1008. collection_ids=filter_collection_ids,
  1009. document_ids=[id],
  1010. offset=0,
  1011. limit=100,
  1012. )
  1013. results = documents_overview_response["results"]
  1014. if len(results) == 0:
  1015. raise R2RException("Document not found.", 404)
  1016. return results[0]
  1017. @self.router.get(
  1018. "/documents/{id}/chunks",
  1019. dependencies=[Depends(self.rate_limit_dependency)],
  1020. summary="List document chunks",
  1021. openapi_extra={
  1022. "x-codeSamples": [
  1023. {
  1024. "lang": "Python",
  1025. "source": textwrap.dedent("""
  1026. from r2r import R2RClient
  1027. client = R2RClient()
  1028. # when using auth, do client.login(...)
  1029. response = client.documents.list_chunks(
  1030. id="32b6a70f-a995-5c51-85d2-834f06283a1e"
  1031. )
  1032. """),
  1033. },
  1034. {
  1035. "lang": "JavaScript",
  1036. "source": textwrap.dedent("""
  1037. const { r2rClient } = require("r2r-js");
  1038. const client = new r2rClient();
  1039. function main() {
  1040. const response = await client.documents.listChunks({
  1041. id: "32b6a70f-a995-5c51-85d2-834f06283a1e",
  1042. });
  1043. }
  1044. main();
  1045. """),
  1046. },
  1047. {
  1048. "lang": "cURL",
  1049. "source": textwrap.dedent("""
  1050. curl -X GET "https://api.example.com/v3/documents/b4ac4dd6-5f27-596e-a55b-7cf242ca30aa/chunks" \\
  1051. -H "Authorization: Bearer YOUR_API_KEY"\
  1052. """),
  1053. },
  1054. ]
  1055. },
  1056. )
  1057. @self.base_endpoint
  1058. async def list_chunks(
  1059. id: UUID = Path(
  1060. ...,
  1061. description="The ID of the document to retrieve chunks for.",
  1062. ),
  1063. offset: int = Query(
  1064. 0,
  1065. ge=0,
  1066. description="Specifies the number of objects to skip. Defaults to 0.",
  1067. ),
  1068. limit: int = Query(
  1069. 100,
  1070. ge=1,
  1071. le=1000,
  1072. description="Specifies a limit on the number of objects to return, ranging between 1 and 100. Defaults to 100.",
  1073. ),
  1074. include_vectors: Optional[bool] = Query(
  1075. False,
  1076. description="Whether to include vector embeddings in the response.",
  1077. ),
  1078. auth_user=Depends(self.providers.auth.auth_wrapper()),
  1079. ) -> WrappedChunksResponse:
  1080. """Retrieves the text chunks that were generated from a document
  1081. during ingestion. Chunks represent semantic sections of the
  1082. document and are used for retrieval and analysis.
  1083. Users can only access chunks from documents they own or have access
  1084. to through collections. Vector embeddings are only included if
  1085. specifically requested.
  1086. Results are returned in chunk sequence order, representing their
  1087. position in the original document.
  1088. """
  1089. list_document_chunks = (
  1090. await self.services.management.list_document_chunks(
  1091. document_id=id,
  1092. offset=offset,
  1093. limit=limit,
  1094. include_vectors=include_vectors or False,
  1095. )
  1096. )
  1097. if not list_document_chunks["results"]:
  1098. raise R2RException(
  1099. "No chunks found for the given document ID.", 404
  1100. )
  1101. is_owner = str(
  1102. list_document_chunks["results"][0].get("owner_id")
  1103. ) == str(auth_user.id)
  1104. document_collections = (
  1105. await self.services.management.collections_overview(
  1106. offset=0,
  1107. limit=-1,
  1108. document_ids=[id],
  1109. )
  1110. )
  1111. user_has_access = (
  1112. is_owner
  1113. or set(auth_user.collection_ids).intersection(
  1114. {ele.id for ele in document_collections["results"]} # type: ignore
  1115. )
  1116. != set()
  1117. )
  1118. if not user_has_access and not auth_user.is_superuser:
  1119. raise R2RException(
  1120. "Not authorized to access this document's chunks.", 403
  1121. )
  1122. return ( # type: ignore
  1123. list_document_chunks["results"],
  1124. {"total_entries": list_document_chunks["total_entries"]},
  1125. )
  1126. @self.router.get(
  1127. "/documents/{id}/download",
  1128. dependencies=[Depends(self.rate_limit_dependency)],
  1129. response_class=StreamingResponse,
  1130. summary="Download document content",
  1131. openapi_extra={
  1132. "x-codeSamples": [
  1133. {
  1134. "lang": "Python",
  1135. "source": textwrap.dedent("""
  1136. from r2r import R2RClient
  1137. client = R2RClient()
  1138. # when using auth, do client.login(...)
  1139. response = client.documents.download(
  1140. id="b4ac4dd6-5f27-596e-a55b-7cf242ca30aa"
  1141. )
  1142. """),
  1143. },
  1144. {
  1145. "lang": "JavaScript",
  1146. "source": textwrap.dedent("""
  1147. const { r2rClient } = require("r2r-js");
  1148. const client = new r2rClient();
  1149. function main() {
  1150. const response = await client.documents.download({
  1151. id: "b4ac4dd6-5f27-596e-a55b-7cf242ca30aa",
  1152. });
  1153. }
  1154. main();
  1155. """),
  1156. },
  1157. {
  1158. "lang": "cURL",
  1159. "source": textwrap.dedent("""
  1160. curl -X GET "https://api.example.com/v3/documents/b4ac4dd6-5f27-596e-a55b-7cf242ca30aa/download" \\
  1161. -H "Authorization: Bearer YOUR_API_KEY"
  1162. """),
  1163. },
  1164. ]
  1165. },
  1166. )
  1167. @self.base_endpoint
  1168. async def get_document_file(
  1169. id: str = Path(..., description="Document ID"),
  1170. auth_user=Depends(self.providers.auth.auth_wrapper()),
  1171. ) -> StreamingResponse:
  1172. """Downloads the original file content of a document.
  1173. For uploaded files, returns the original file with its proper MIME
  1174. type. For text-only documents, returns the content as plain text.
  1175. Users can only download documents they own or have access to
  1176. through collections.
  1177. """
  1178. try:
  1179. document_uuid = UUID(id)
  1180. except ValueError:
  1181. raise R2RException(
  1182. status_code=422, message="Invalid document ID format."
  1183. ) from None
  1184. # Retrieve the document's information
  1185. documents_overview_response = (
  1186. await self.services.management.documents_overview(
  1187. user_ids=None,
  1188. collection_ids=None,
  1189. document_ids=[document_uuid],
  1190. offset=0,
  1191. limit=1,
  1192. )
  1193. )
  1194. if not documents_overview_response["results"]:
  1195. raise R2RException("Document not found.", 404)
  1196. document = documents_overview_response["results"][0]
  1197. is_owner = str(document.owner_id) == str(auth_user.id)
  1198. if not auth_user.is_superuser and not is_owner:
  1199. document_collections = (
  1200. await self.services.management.collections_overview(
  1201. offset=0,
  1202. limit=-1,
  1203. document_ids=[document_uuid],
  1204. )
  1205. )
  1206. document_collection_ids = {
  1207. str(ele.id)
  1208. for ele in document_collections["results"] # type: ignore
  1209. }
  1210. user_collection_ids = {
  1211. str(cid) for cid in auth_user.collection_ids
  1212. }
  1213. has_collection_access = user_collection_ids.intersection(
  1214. document_collection_ids
  1215. )
  1216. if not has_collection_access:
  1217. raise R2RException(
  1218. "Not authorized to access this document.", 403
  1219. )
  1220. file_tuple = await self.services.management.download_file(
  1221. document_uuid
  1222. )
  1223. if not file_tuple:
  1224. raise R2RException(status_code=404, message="File not found.")
  1225. file_name, file_content, file_size = file_tuple
  1226. encoded_filename = quote(file_name)
  1227. mime_type, _ = mimetypes.guess_type(file_name)
  1228. if not mime_type:
  1229. mime_type = "application/octet-stream"
  1230. async def file_stream():
  1231. chunk_size = 1024 * 1024 # 1MB
  1232. while True:
  1233. data = file_content.read(chunk_size)
  1234. if not data:
  1235. break
  1236. yield data
  1237. return StreamingResponse(
  1238. file_stream(),
  1239. media_type=mime_type,
  1240. headers={
  1241. "Content-Disposition": f"inline; filename*=UTF-8''{encoded_filename}",
  1242. "Content-Length": str(file_size),
  1243. },
  1244. )
  1245. @self.router.delete(
  1246. "/documents/by-filter",
  1247. dependencies=[Depends(self.rate_limit_dependency)],
  1248. summary="Delete documents by filter",
  1249. openapi_extra={
  1250. "x-codeSamples": [
  1251. {
  1252. "lang": "Python",
  1253. "source": textwrap.dedent("""
  1254. from r2r import R2RClient
  1255. client = R2RClient()
  1256. # when using auth, do client.login(...)
  1257. response = client.documents.delete_by_filter(
  1258. filters={"document_type": {"$eq": "txt"}}
  1259. )
  1260. """),
  1261. },
  1262. {
  1263. "lang": "cURL",
  1264. "source": textwrap.dedent("""
  1265. curl -X DELETE "https://api.example.com/v3/documents/by-filter?filters=%7B%22document_type%22%3A%7B%22%24eq%22%3A%22text%22%7D%2C%22created_at%22%3A%7B%22%24lt%22%3A%222023-01-01T00%3A00%3A00Z%22%7D%7D" \\
  1266. -H "Authorization: Bearer YOUR_API_KEY"
  1267. """),
  1268. },
  1269. ]
  1270. },
  1271. )
  1272. @self.base_endpoint
  1273. async def delete_document_by_filter(
  1274. filters: Json[dict] = Body(
  1275. ..., description="JSON-encoded filters"
  1276. ),
  1277. auth_user=Depends(self.providers.auth.auth_wrapper()),
  1278. ) -> WrappedBooleanResponse:
  1279. """Delete documents based on provided filters.
  1280. Allowed operators
  1281. include: `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `like`,
  1282. `ilike`, `in`, and `nin`. Deletion requests are limited to a
  1283. user's own documents.
  1284. """
  1285. filters_dict = {
  1286. "$and": [{"owner_id": {"$eq": str(auth_user.id)}}, filters]
  1287. }
  1288. await (
  1289. self.services.management.delete_documents_and_chunks_by_filter(
  1290. filters=filters_dict
  1291. )
  1292. )
  1293. return GenericBooleanResponse(success=True) # type: ignore
  1294. @self.router.delete(
  1295. "/documents/{id}",
  1296. dependencies=[Depends(self.rate_limit_dependency)],
  1297. summary="Delete a document",
  1298. openapi_extra={
  1299. "x-codeSamples": [
  1300. {
  1301. "lang": "Python",
  1302. "source": textwrap.dedent("""
  1303. from r2r import R2RClient
  1304. client = R2RClient()
  1305. # when using auth, do client.login(...)
  1306. response = client.documents.delete(
  1307. id="b4ac4dd6-5f27-596e-a55b-7cf242ca30aa"
  1308. )
  1309. """),
  1310. },
  1311. {
  1312. "lang": "JavaScript",
  1313. "source": textwrap.dedent("""
  1314. const { r2rClient } = require("r2r-js");
  1315. const client = new r2rClient();
  1316. function main() {
  1317. const response = await client.documents.delete({
  1318. id: "b4ac4dd6-5f27-596e-a55b-7cf242ca30aa",
  1319. });
  1320. }
  1321. main();
  1322. """),
  1323. },
  1324. {
  1325. "lang": "cURL",
  1326. "source": textwrap.dedent("""
  1327. curl -X DELETE "https://api.example.com/v3/documents/b4ac4dd6-5f27-596e-a55b-7cf242ca30aa" \\
  1328. -H "Authorization: Bearer YOUR_API_KEY"
  1329. """),
  1330. },
  1331. ]
  1332. },
  1333. )
  1334. @self.base_endpoint
  1335. async def delete_document_by_id(
  1336. id: UUID = Path(..., description="Document ID"),
  1337. auth_user=Depends(self.providers.auth.auth_wrapper()),
  1338. ) -> WrappedBooleanResponse:
  1339. """Delete a specific document. All chunks corresponding to the
  1340. document are deleted, and all other references to the document are
  1341. removed.
  1342. NOTE - Deletions do not yet impact the knowledge graph or other derived data. This feature is planned for a future release.
  1343. """
  1344. filters: dict[str, Any] = {"document_id": {"$eq": str(id)}}
  1345. if not auth_user.is_superuser:
  1346. filters = {
  1347. "$and": [
  1348. {"owner_id": {"$eq": str(auth_user.id)}},
  1349. {"document_id": {"$eq": str(id)}},
  1350. ]
  1351. }
  1352. await (
  1353. self.services.management.delete_documents_and_chunks_by_filter(
  1354. filters=filters
  1355. )
  1356. )
  1357. return GenericBooleanResponse(success=True) # type: ignore
  1358. @self.router.get(
  1359. "/documents/{id}/collections",
  1360. dependencies=[Depends(self.rate_limit_dependency)],
  1361. summary="List document collections",
  1362. openapi_extra={
  1363. "x-codeSamples": [
  1364. {
  1365. "lang": "Python",
  1366. "source": textwrap.dedent("""
  1367. from r2r import R2RClient
  1368. client = R2RClient()
  1369. # when using auth, do client.login(...)
  1370. response = client.documents.list_collections(
  1371. id="b4ac4dd6-5f27-596e-a55b-7cf242ca30aa", offset=0, limit=10
  1372. )
  1373. """),
  1374. },
  1375. {
  1376. "lang": "JavaScript",
  1377. "source": textwrap.dedent("""
  1378. const { r2rClient } = require("r2r-js");
  1379. const client = new r2rClient();
  1380. function main() {
  1381. const response = await client.documents.listCollections({
  1382. id: "b4ac4dd6-5f27-596e-a55b-7cf242ca30aa",
  1383. });
  1384. }
  1385. main();
  1386. """),
  1387. },
  1388. {
  1389. "lang": "cURL",
  1390. "source": textwrap.dedent("""
  1391. curl -X GET "https://api.example.com/v3/documents/b4ac4dd6-5f27-596e-a55b-7cf242ca30aa/collections" \\
  1392. -H "Authorization: Bearer YOUR_API_KEY"
  1393. """),
  1394. },
  1395. ]
  1396. },
  1397. )
  1398. @self.base_endpoint
  1399. async def get_document_collections(
  1400. id: str = Path(..., description="Document ID"),
  1401. offset: int = Query(
  1402. 0,
  1403. ge=0,
  1404. description="Specifies the number of objects to skip. Defaults to 0.",
  1405. ),
  1406. limit: int = Query(
  1407. 100,
  1408. ge=1,
  1409. le=1000,
  1410. description="Specifies a limit on the number of objects to return, ranging between 1 and 100. Defaults to 100.",
  1411. ),
  1412. auth_user=Depends(self.providers.auth.auth_wrapper()),
  1413. ) -> WrappedCollectionsResponse:
  1414. """Retrieves all collections that contain the specified document.
  1415. This endpoint is restricted to superusers only and provides a
  1416. system-wide view of document organization.
  1417. Collections are used to organize documents and manage access control. A document can belong
  1418. to multiple collections, and users can access documents through collection membership.
  1419. The results are paginated and ordered by collection creation date, with the most recently
  1420. created collections appearing first.
  1421. NOTE - This endpoint is only available to superusers, it will be extended to regular users in a future release.
  1422. """
  1423. if not auth_user.is_superuser:
  1424. raise R2RException(
  1425. "Only a superuser can get the collections belonging to a document.",
  1426. 403,
  1427. )
  1428. collections_response = (
  1429. await self.services.management.collections_overview(
  1430. offset=offset,
  1431. limit=limit,
  1432. document_ids=[UUID(id)], # Convert string ID to UUID
  1433. )
  1434. )
  1435. return collections_response["results"], { # type: ignore
  1436. "total_entries": collections_response["total_entries"]
  1437. }
  1438. @self.router.post(
  1439. "/documents/{id}/extract",
  1440. dependencies=[Depends(self.rate_limit_dependency)],
  1441. summary="Extract entities and relationships",
  1442. openapi_extra={
  1443. "x-codeSamples": [
  1444. {
  1445. "lang": "Python",
  1446. "source": textwrap.dedent("""
  1447. from r2r import R2RClient
  1448. client = R2RClient()
  1449. # when using auth, do client.login(...)
  1450. response = client.documents.extract(
  1451. id="b4ac4dd6-5f27-596e-a55b-7cf242ca30aa"
  1452. )
  1453. """),
  1454. },
  1455. ],
  1456. },
  1457. )
  1458. @self.base_endpoint
  1459. async def extract(
  1460. id: UUID = Path(
  1461. ...,
  1462. description="The ID of the document to extract entities and relationships from.",
  1463. ),
  1464. settings: Optional[GraphCreationSettings] = Body(
  1465. default=None,
  1466. description="Settings for the entities and relationships extraction process.",
  1467. ),
  1468. run_with_orchestration: Optional[bool] = Body(
  1469. default=True,
  1470. description="Whether to run the entities and relationships extraction process with orchestration.",
  1471. ),
  1472. auth_user=Depends(self.providers.auth.auth_wrapper()),
  1473. ) -> WrappedGenericMessageResponse:
  1474. """Extracts entities and relationships from a document.
  1475. The entities and relationships extraction process involves:
  1476. 1. Parsing documents into semantic chunks
  1477. 2. Extracting entities and relationships using LLMs
  1478. 3. Storing the created entities and relationships in the knowledge graph
  1479. 4. Preserving the document's metadata and content, and associating the elements with collections the document belongs to
  1480. """
  1481. settings = settings.dict() if settings else None # type: ignore
  1482. documents_overview_response = (
  1483. await self.services.management.documents_overview(
  1484. user_ids=(
  1485. None if auth_user.is_superuser else [auth_user.id]
  1486. ),
  1487. collection_ids=(
  1488. None
  1489. if auth_user.is_superuser
  1490. else auth_user.collection_ids
  1491. ),
  1492. document_ids=[id],
  1493. offset=0,
  1494. limit=1,
  1495. )
  1496. )["results"]
  1497. if len(documents_overview_response) == 0:
  1498. raise R2RException("Document not found.", 404)
  1499. if (
  1500. not auth_user.is_superuser
  1501. and auth_user.id != documents_overview_response[0].owner_id
  1502. ):
  1503. raise R2RException(
  1504. "Only a superuser can extract entities and relationships from a document they do not own.",
  1505. 403,
  1506. )
  1507. # Apply runtime settings overrides
  1508. server_graph_creation_settings = (
  1509. self.providers.database.config.graph_creation_settings
  1510. )
  1511. if settings:
  1512. server_graph_creation_settings = update_settings_from_dict(
  1513. server_settings=server_graph_creation_settings,
  1514. settings_dict=settings, # type: ignore
  1515. )
  1516. workflow_input = {
  1517. "document_id": str(id),
  1518. "graph_creation_settings": server_graph_creation_settings.model_dump_json(),
  1519. "user": auth_user.json(),
  1520. }
  1521. if run_with_orchestration:
  1522. try:
  1523. return await self.providers.orchestration.run_workflow( # type: ignore
  1524. "graph-extraction", {"request": workflow_input}, {}
  1525. )
  1526. except Exception as e: # TODO: Need to find specific errors that we should be excepting (gRPC most likely?)
  1527. logger.error(
  1528. f"Error running orchestrated extraction: {e} \n\nAttempting to run without orchestration."
  1529. )
  1530. from core.main.orchestration import (
  1531. simple_graph_search_results_factory,
  1532. )
  1533. logger.info("Running extract-triples without orchestration.")
  1534. simple_graph_search_results = simple_graph_search_results_factory(
  1535. self.services.graph
  1536. )
  1537. await simple_graph_search_results["graph-extraction"](
  1538. workflow_input
  1539. )
  1540. return { # type: ignore
  1541. "message": "Graph created successfully.",
  1542. "task_id": None,
  1543. }
  1544. @self.router.post(
  1545. "/documents/{id}/deduplicate",
  1546. dependencies=[Depends(self.rate_limit_dependency)],
  1547. summary="Deduplicate entities",
  1548. openapi_extra={
  1549. "x-codeSamples": [
  1550. {
  1551. "lang": "Python",
  1552. "source": textwrap.dedent("""
  1553. from r2r import R2RClient
  1554. client = R2RClient()
  1555. response = client.documents.deduplicate(
  1556. id="b4ac4dd6-5f27-596e-a55b-7cf242ca30aa"
  1557. )
  1558. """),
  1559. },
  1560. {
  1561. "lang": "JavaScript",
  1562. "source": textwrap.dedent("""
  1563. const { r2rClient } = require("r2r-js");
  1564. const client = new r2rClient();
  1565. function main() {
  1566. const response = await client.documents.deduplicate({
  1567. id: "b4ac4dd6-5f27-596e-a55b-7cf242ca30aa",
  1568. });
  1569. }
  1570. main();
  1571. """),
  1572. },
  1573. {
  1574. "lang": "cURL",
  1575. "source": textwrap.dedent("""
  1576. curl -X POST "https://api.example.com/v3/documents/b4ac4dd6-5f27-596e-a55b-7cf242ca30aa/deduplicate" \\
  1577. -H "Authorization: Bearer YOUR_API_KEY"
  1578. """),
  1579. },
  1580. ],
  1581. },
  1582. )
  1583. @self.base_endpoint
  1584. async def deduplicate(
  1585. id: UUID = Path(
  1586. ...,
  1587. description="The ID of the document to extract entities and relationships from.",
  1588. ),
  1589. settings: Optional[GraphCreationSettings] = Body(
  1590. default=None,
  1591. description="Settings for the entities and relationships extraction process.",
  1592. ),
  1593. run_with_orchestration: Optional[bool] = Body(
  1594. default=True,
  1595. description="Whether to run the entities and relationships extraction process with orchestration.",
  1596. ),
  1597. auth_user=Depends(self.providers.auth.auth_wrapper()),
  1598. ) -> WrappedGenericMessageResponse:
  1599. """Deduplicates entities from a document."""
  1600. settings = settings.model_dump() if settings else None # type: ignore
  1601. documents_overview_response = (
  1602. await self.services.management.documents_overview(
  1603. user_ids=(
  1604. None if auth_user.is_superuser else [auth_user.id]
  1605. ),
  1606. collection_ids=(
  1607. None
  1608. if auth_user.is_superuser
  1609. else auth_user.collection_ids
  1610. ),
  1611. document_ids=[id],
  1612. offset=0,
  1613. limit=1,
  1614. )
  1615. )["results"]
  1616. if len(documents_overview_response) == 0:
  1617. raise R2RException("Document not found.", 404)
  1618. if (
  1619. not auth_user.is_superuser
  1620. and auth_user.id != documents_overview_response[0].owner_id
  1621. ):
  1622. raise R2RException(
  1623. "Only a superuser can run deduplication on a document they do not own.",
  1624. 403,
  1625. )
  1626. # Apply runtime settings overrides
  1627. server_graph_creation_settings = (
  1628. self.providers.database.config.graph_creation_settings
  1629. )
  1630. if settings:
  1631. server_graph_creation_settings = update_settings_from_dict(
  1632. server_settings=server_graph_creation_settings,
  1633. settings_dict=settings, # type: ignore
  1634. )
  1635. if run_with_orchestration:
  1636. try:
  1637. workflow_input = {
  1638. "document_id": str(id),
  1639. }
  1640. return await self.providers.orchestration.run_workflow( # type: ignore
  1641. "graph-deduplication",
  1642. {"request": workflow_input},
  1643. {},
  1644. )
  1645. except Exception as e: # TODO: Need to find specific errors that we should be excepting (gRPC most likely?)
  1646. logger.error(
  1647. f"Error running orchestrated deduplication: {e} \n\nAttempting to run without orchestration."
  1648. )
  1649. from core.main.orchestration import (
  1650. simple_graph_search_results_factory,
  1651. )
  1652. logger.info(
  1653. "Running deduplicate-document-entities without orchestration."
  1654. )
  1655. simple_graph_search_results = simple_graph_search_results_factory(
  1656. self.services.graph
  1657. )
  1658. await simple_graph_search_results["graph-deduplication"](
  1659. workflow_input
  1660. )
  1661. return { # type: ignore
  1662. "message": "Graph created successfully.",
  1663. "task_id": None,
  1664. }
  1665. @self.router.get(
  1666. "/documents/{id}/entities",
  1667. dependencies=[Depends(self.rate_limit_dependency)],
  1668. summary="Lists the entities from the document",
  1669. openapi_extra={
  1670. "x-codeSamples": [
  1671. {
  1672. "lang": "Python",
  1673. "source": textwrap.dedent("""
  1674. from r2r import R2RClient
  1675. client = R2RClient()
  1676. # when using auth, do client.login(...)
  1677. response = client.documents.extract(
  1678. id="b4ac4dd6-5f27-596e-a55b-7cf242ca30aa"
  1679. )
  1680. """),
  1681. },
  1682. ],
  1683. },
  1684. )
  1685. @self.base_endpoint
  1686. async def get_entities(
  1687. id: UUID = Path(
  1688. ...,
  1689. description="The ID of the document to retrieve entities from.",
  1690. ),
  1691. offset: int = Query(
  1692. 0,
  1693. ge=0,
  1694. description="Specifies the number of objects to skip. Defaults to 0.",
  1695. ),
  1696. limit: int = Query(
  1697. 100,
  1698. ge=1,
  1699. le=1000,
  1700. description="Specifies a limit on the number of objects to return, ranging between 1 and 100. Defaults to 100.",
  1701. ),
  1702. include_embeddings: Optional[bool] = Query(
  1703. False,
  1704. description="Whether to include vector embeddings in the response.",
  1705. ),
  1706. auth_user=Depends(self.providers.auth.auth_wrapper()),
  1707. ) -> WrappedEntitiesResponse:
  1708. """Retrieves the entities that were extracted from a document.
  1709. These represent important semantic elements like people, places,
  1710. organizations, concepts, etc.
  1711. Users can only access entities from documents they own or have
  1712. access to through collections. Entity embeddings are only included
  1713. if specifically requested.
  1714. Results are returned in the order they were extracted from the
  1715. document.
  1716. """
  1717. # if (
  1718. # not auth_user.is_superuser
  1719. # and id not in auth_user.collection_ids
  1720. # ):
  1721. # raise R2RException(
  1722. # "The currently authenticated user does not have access to the specified collection.",
  1723. # 403,
  1724. # )
  1725. # First check if the document exists and user has access
  1726. documents_overview_response = (
  1727. await self.services.management.documents_overview(
  1728. user_ids=(
  1729. None if auth_user.is_superuser else [auth_user.id]
  1730. ),
  1731. collection_ids=(
  1732. None
  1733. if auth_user.is_superuser
  1734. else auth_user.collection_ids
  1735. ),
  1736. document_ids=[id],
  1737. offset=0,
  1738. limit=1,
  1739. )
  1740. )
  1741. if not documents_overview_response["results"]:
  1742. raise R2RException("Document not found.", 404)
  1743. # Get all entities for this document from the document_entity table
  1744. (
  1745. entities,
  1746. count,
  1747. ) = await self.providers.database.graphs_handler.entities.get(
  1748. parent_id=id,
  1749. store_type=StoreType.DOCUMENTS,
  1750. offset=offset,
  1751. limit=limit,
  1752. include_embeddings=include_embeddings or False,
  1753. )
  1754. return entities, {"total_entries": count} # type: ignore
  1755. @self.router.post(
  1756. "/documents/{id}/entities/export",
  1757. summary="Export document entities to CSV",
  1758. dependencies=[Depends(self.rate_limit_dependency)],
  1759. openapi_extra={
  1760. "x-codeSamples": [
  1761. {
  1762. "lang": "Python",
  1763. "source": textwrap.dedent("""
  1764. from r2r import R2RClient
  1765. client = R2RClient("http://localhost:7272")
  1766. # when using auth, do client.login(...)
  1767. response = client.documents.export_entities(
  1768. id="b4ac4dd6-5f27-596e-a55b-7cf242ca30aa",
  1769. output_path="export.csv",
  1770. columns=["id", "title", "created_at"],
  1771. include_header=True,
  1772. )
  1773. """),
  1774. },
  1775. {
  1776. "lang": "JavaScript",
  1777. "source": textwrap.dedent("""
  1778. const { r2rClient } = require("r2r-js");
  1779. const client = new r2rClient("http://localhost:7272");
  1780. function main() {
  1781. await client.documents.exportEntities({
  1782. id: "b4ac4dd6-5f27-596e-a55b-7cf242ca30aa",
  1783. outputPath: "export.csv",
  1784. columns: ["id", "title", "created_at"],
  1785. includeHeader: true,
  1786. });
  1787. }
  1788. main();
  1789. """),
  1790. },
  1791. {
  1792. "lang": "cURL",
  1793. "source": textwrap.dedent("""
  1794. curl -X POST "http://127.0.0.1:7272/v3/documents/export_entities" \
  1795. -H "Authorization: Bearer YOUR_API_KEY" \
  1796. -H "Content-Type: application/json" \
  1797. -H "Accept: text/csv" \
  1798. -d '{ "columns": ["id", "title", "created_at"], "include_header": true }' \
  1799. --output export.csv
  1800. """),
  1801. },
  1802. ]
  1803. },
  1804. )
  1805. @self.base_endpoint
  1806. async def export_entities(
  1807. background_tasks: BackgroundTasks,
  1808. id: UUID = Path(
  1809. ...,
  1810. description="The ID of the document to export entities from.",
  1811. ),
  1812. columns: Optional[list[str]] = Body(
  1813. None, description="Specific columns to export"
  1814. ),
  1815. filters: Optional[dict] = Body(
  1816. None, description="Filters to apply to the export"
  1817. ),
  1818. include_header: Optional[bool] = Body(
  1819. True, description="Whether to include column headers"
  1820. ),
  1821. auth_user=Depends(self.providers.auth.auth_wrapper()),
  1822. ) -> FileResponse:
  1823. """Export documents as a downloadable CSV file."""
  1824. if not auth_user.is_superuser:
  1825. raise R2RException(
  1826. "Only a superuser can export data.",
  1827. 403,
  1828. )
  1829. (
  1830. csv_file_path,
  1831. temp_file,
  1832. ) = await self.services.management.export_document_entities(
  1833. id=id,
  1834. columns=columns,
  1835. filters=filters,
  1836. include_header=include_header
  1837. if include_header is not None
  1838. else True,
  1839. )
  1840. background_tasks.add_task(temp_file.close)
  1841. return FileResponse(
  1842. path=csv_file_path,
  1843. media_type="text/csv",
  1844. filename="documents_export.csv",
  1845. )
  1846. @self.router.get(
  1847. "/documents/{id}/relationships",
  1848. dependencies=[Depends(self.rate_limit_dependency)],
  1849. summary="List document relationships",
  1850. openapi_extra={
  1851. "x-codeSamples": [
  1852. {
  1853. "lang": "Python",
  1854. "source": textwrap.dedent("""
  1855. from r2r import R2RClient
  1856. client = R2RClient()
  1857. # when using auth, do client.login(...)
  1858. response = client.documents.list_relationships(
  1859. id="b4ac4dd6-5f27-596e-a55b-7cf242ca30aa",
  1860. offset=0,
  1861. limit=100
  1862. )
  1863. """),
  1864. },
  1865. {
  1866. "lang": "JavaScript",
  1867. "source": textwrap.dedent("""
  1868. const { r2rClient } = require("r2r-js");
  1869. const client = new r2rClient();
  1870. function main() {
  1871. const response = await client.documents.listRelationships({
  1872. id: "b4ac4dd6-5f27-596e-a55b-7cf242ca30aa",
  1873. offset: 0,
  1874. limit: 100,
  1875. });
  1876. }
  1877. main();
  1878. """),
  1879. },
  1880. {
  1881. "lang": "cURL",
  1882. "source": textwrap.dedent("""
  1883. curl -X GET "https://api.example.com/v3/documents/b4ac4dd6-5f27-596e-a55b-7cf242ca30aa/relationships" \\
  1884. -H "Authorization: Bearer YOUR_API_KEY"
  1885. """),
  1886. },
  1887. ]
  1888. },
  1889. )
  1890. @self.base_endpoint
  1891. async def get_relationships(
  1892. id: UUID = Path(
  1893. ...,
  1894. description="The ID of the document to retrieve relationships for.",
  1895. ),
  1896. offset: int = Query(
  1897. 0,
  1898. ge=0,
  1899. description="Specifies the number of objects to skip. Defaults to 0.",
  1900. ),
  1901. limit: int = Query(
  1902. 100,
  1903. ge=1,
  1904. le=1000,
  1905. description="Specifies a limit on the number of objects to return, ranging between 1 and 100. Defaults to 100.",
  1906. ),
  1907. entity_names: Optional[list[str]] = Query(
  1908. None,
  1909. description="Filter relationships by specific entity names.",
  1910. ),
  1911. relationship_types: Optional[list[str]] = Query(
  1912. None,
  1913. description="Filter relationships by specific relationship types.",
  1914. ),
  1915. auth_user=Depends(self.providers.auth.auth_wrapper()),
  1916. ) -> WrappedRelationshipsResponse:
  1917. """Retrieves the relationships between entities that were extracted
  1918. from a document. These represent connections and interactions
  1919. between entities found in the text.
  1920. Users can only access relationships from documents they own or have
  1921. access to through collections. Results can be filtered by entity
  1922. names and relationship types.
  1923. Results are returned in the order they were extracted from the
  1924. document.
  1925. """
  1926. # if (
  1927. # not auth_user.is_superuser
  1928. # and id not in auth_user.collection_ids
  1929. # ):
  1930. # raise R2RException(
  1931. # "The currently authenticated user does not have access to the specified collection.",
  1932. # 403,
  1933. # )
  1934. # First check if the document exists and user has access
  1935. documents_overview_response = (
  1936. await self.services.management.documents_overview(
  1937. user_ids=(
  1938. None if auth_user.is_superuser else [auth_user.id]
  1939. ),
  1940. collection_ids=(
  1941. None
  1942. if auth_user.is_superuser
  1943. else auth_user.collection_ids
  1944. ),
  1945. document_ids=[id],
  1946. offset=0,
  1947. limit=1,
  1948. )
  1949. )
  1950. if not documents_overview_response["results"]:
  1951. raise R2RException("Document not found.", 404)
  1952. # Get relationships for this document
  1953. (
  1954. relationships,
  1955. count,
  1956. ) = await self.providers.database.graphs_handler.relationships.get(
  1957. parent_id=id,
  1958. store_type=StoreType.DOCUMENTS,
  1959. entity_names=entity_names,
  1960. relationship_types=relationship_types,
  1961. offset=offset,
  1962. limit=limit,
  1963. )
  1964. return relationships, {"total_entries": count} # type: ignore
  1965. @self.router.post(
  1966. "/documents/{id}/relationships/export",
  1967. summary="Export document relationships to CSV",
  1968. dependencies=[Depends(self.rate_limit_dependency)],
  1969. openapi_extra={
  1970. "x-codeSamples": [
  1971. {
  1972. "lang": "Python",
  1973. "source": textwrap.dedent("""
  1974. from r2r import R2RClient
  1975. client = R2RClient("http://localhost:7272")
  1976. # when using auth, do client.login(...)
  1977. response = client.documents.export_entities(
  1978. id="b4ac4dd6-5f27-596e-a55b-7cf242ca30aa",
  1979. output_path="export.csv",
  1980. columns=["id", "title", "created_at"],
  1981. include_header=True,
  1982. )
  1983. """),
  1984. },
  1985. {
  1986. "lang": "JavaScript",
  1987. "source": textwrap.dedent("""
  1988. const { r2rClient } = require("r2r-js");
  1989. const client = new r2rClient("http://localhost:7272");
  1990. function main() {
  1991. await client.documents.exportEntities({
  1992. id: "b4ac4dd6-5f27-596e-a55b-7cf242ca30aa",
  1993. outputPath: "export.csv",
  1994. columns: ["id", "title", "created_at"],
  1995. includeHeader: true,
  1996. });
  1997. }
  1998. main();
  1999. """),
  2000. },
  2001. {
  2002. "lang": "cURL",
  2003. "source": textwrap.dedent("""
  2004. curl -X POST "http://127.0.0.1:7272/v3/documents/export_entities" \
  2005. -H "Authorization: Bearer YOUR_API_KEY" \
  2006. -H "Content-Type: application/json" \
  2007. -H "Accept: text/csv" \
  2008. -d '{ "columns": ["id", "title", "created_at"], "include_header": true }' \
  2009. --output export.csv
  2010. """),
  2011. },
  2012. ]
  2013. },
  2014. )
  2015. @self.base_endpoint
  2016. async def export_relationships(
  2017. background_tasks: BackgroundTasks,
  2018. id: UUID = Path(
  2019. ...,
  2020. description="The ID of the document to export entities from.",
  2021. ),
  2022. columns: Optional[list[str]] = Body(
  2023. None, description="Specific columns to export"
  2024. ),
  2025. filters: Optional[dict] = Body(
  2026. None, description="Filters to apply to the export"
  2027. ),
  2028. include_header: Optional[bool] = Body(
  2029. True, description="Whether to include column headers"
  2030. ),
  2031. auth_user=Depends(self.providers.auth.auth_wrapper()),
  2032. ) -> FileResponse:
  2033. """Export documents as a downloadable CSV file."""
  2034. if not auth_user.is_superuser:
  2035. raise R2RException(
  2036. "Only a superuser can export data.",
  2037. 403,
  2038. )
  2039. (
  2040. csv_file_path,
  2041. temp_file,
  2042. ) = await self.services.management.export_document_relationships(
  2043. id=id,
  2044. columns=columns,
  2045. filters=filters,
  2046. include_header=include_header
  2047. if include_header is not None
  2048. else True,
  2049. )
  2050. background_tasks.add_task(temp_file.close)
  2051. return FileResponse(
  2052. path=csv_file_path,
  2053. media_type="text/csv",
  2054. filename="documents_export.csv",
  2055. )
  2056. @self.router.post(
  2057. "/documents/search",
  2058. dependencies=[Depends(self.rate_limit_dependency)],
  2059. summary="Search document summaries",
  2060. )
  2061. @self.base_endpoint
  2062. async def search_documents(
  2063. query: str = Body(
  2064. ...,
  2065. description="The search query to perform.",
  2066. ),
  2067. search_mode: SearchMode = Body(
  2068. default=SearchMode.custom,
  2069. description=(
  2070. "Default value of `custom` allows full control over search settings.\n\n"
  2071. "Pre-configured search modes:\n"
  2072. "`basic`: A simple semantic-based search.\n"
  2073. "`advanced`: A more powerful hybrid search combining semantic and full-text.\n"
  2074. "`custom`: Full control via `search_settings`.\n\n"
  2075. "If `filters` or `limit` are provided alongside `basic` or `advanced`, "
  2076. "they will override the default settings for that mode."
  2077. ),
  2078. ),
  2079. search_settings: SearchSettings = Body(
  2080. default_factory=SearchSettings,
  2081. description="Settings for document search",
  2082. ),
  2083. auth_user=Depends(self.providers.auth.auth_wrapper()),
  2084. ) -> WrappedDocumentSearchResponse:
  2085. """Perform a search query on the automatically generated document
  2086. summaries in the system.
  2087. This endpoint allows for complex filtering of search results using PostgreSQL-based queries.
  2088. Filters can be applied to various fields such as document_id, and internal metadata values.
  2089. Allowed operators include `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `like`, `ilike`, `in`, and `nin`.
  2090. """
  2091. effective_settings = self._prepare_search_settings(
  2092. auth_user, search_mode, search_settings
  2093. )
  2094. query_embedding = (
  2095. await self.providers.embedding.async_get_embedding(query)
  2096. )
  2097. results = await self.services.retrieval.search_documents(
  2098. query=query,
  2099. query_embedding=query_embedding,
  2100. settings=effective_settings,
  2101. )
  2102. return results # type: ignore
  2103. @staticmethod
  2104. async def _process_file(file):
  2105. import base64
  2106. content = await file.read()
  2107. return {
  2108. "filename": file.filename,
  2109. "content": base64.b64encode(content).decode("utf-8"),
  2110. "content_type": file.content_type,
  2111. "content_length": len(content),
  2112. }