documents_router.py 93 KB

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