documents_router.py 93 KB

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