documents_router.py 83 KB

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