You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  1. # DRAFT Python API Reference
  2. **THE API REFERENCES BELOW ARE STILL UNDER DEVELOPMENT.**
  3. ---
  4. :::tip NOTE
  5. Dataset Management
  6. :::
  7. ---
  8. ## Create dataset
  9. ```python
  10. RAGFlow.create_dataset(
  11. name: str,
  12. avatar: str = "",
  13. description: str = "",
  14. embedding_model: str = "BAAI/bge-zh-v1.5",
  15. language: str = "English",
  16. permission: str = "me",
  17. chunk_method: str = "naive",
  18. parser_config: DataSet.ParserConfig = None
  19. ) -> DataSet
  20. ```
  21. Creates a dataset.
  22. ### Parameters
  23. #### name: `str`, *Required*
  24. The unique name of the dataset to create. It must adhere to the following requirements:
  25. - Permitted characters include:
  26. - English letters (a-z, A-Z)
  27. - Digits (0-9)
  28. - "_" (underscore)
  29. - Must begin with an English letter or underscore.
  30. - Maximum 65,535 characters.
  31. - Case-insensitive.
  32. #### avatar: `str`
  33. Base64 encoding of the avatar. Defaults to `""`
  34. #### description: `str`
  35. A brief description of the dataset to create. Defaults to `""`.
  36. #### language: `str`
  37. The language setting of the dataset to create. Available options:
  38. - `"English"` (Default)
  39. - `"Chinese"`
  40. #### permission
  41. Specifies who can access the dataset to create. You can set it only to `"me"` for now.
  42. #### chunk_method, `str`
  43. The chunking method of the dataset to create. Available options:
  44. - `"naive"`: General (default)
  45. - `"manual`: Manual
  46. - `"qa"`: Q&A
  47. - `"table"`: Table
  48. - `"paper"`: Paper
  49. - `"book"`: Book
  50. - `"laws"`: Laws
  51. - `"presentation"`: Presentation
  52. - `"picture"`: Picture
  53. - `"one"`:One
  54. - `"knowledge_graph"`: Knowledge Graph
  55. - `"email"`: Email
  56. #### parser_config
  57. The parser configuration of the dataset. A `ParserConfig` object contains the following attributes:
  58. - `chunk_token_count`: Defaults to `128`.
  59. - `layout_recognize`: Defaults to `True`.
  60. - `delimiter`: Defaults to `"\n!?。;!?"`.
  61. - `task_page_size`: Defaults to `12`.
  62. ### Returns
  63. - Success: A `dataset` object.
  64. - Failure: `Exception`
  65. ### Examples
  66. ```python
  67. from ragflow import RAGFlow
  68. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  69. dataset = rag_object.create_dataset(name="kb_1")
  70. ```
  71. ---
  72. ## Delete datasets
  73. ```python
  74. RAGFlow.delete_datasets(ids: list[str] = None)
  75. ```
  76. Deletes specified datasets or all datasets in the system.
  77. ### Parameters
  78. #### ids: `list[str]`
  79. The IDs of the datasets to delete. Defaults to `None`. If not specified, all datasets in the system will be deleted.
  80. ### Returns
  81. - Success: No value is returned.
  82. - Failure: `Exception`
  83. ### Examples
  84. ```python
  85. rag_object.delete_datasets(ids=["id_1","id_2"])
  86. ```
  87. ---
  88. ## List datasets
  89. ```python
  90. RAGFlow.list_datasets(
  91. page: int = 1,
  92. page_size: int = 1024,
  93. orderby: str = "create_time",
  94. desc: bool = True,
  95. id: str = None,
  96. name: str = None
  97. ) -> list[DataSet]
  98. ```
  99. Lists datasets.
  100. ### Parameters
  101. #### page: `int`
  102. Specifies the page on which the datasets will be displayed. Defaults to `1`.
  103. #### page_size: `int`
  104. The number of datasets on each page. Defaults to `1024`.
  105. #### orderby: `str`
  106. The field by which datasets should be sorted. Available options:
  107. - `"create_time"` (default)
  108. - `"update_time"`
  109. #### desc: `bool`
  110. Indicates whether the retrieved datasets should be sorted in descending order. Defaults to `True`.
  111. #### id: `str`
  112. The ID of the dataset to retrieve. Defaults to `None`.
  113. #### name: `str`
  114. The name of the dataset to retrieve. Defaults to `None`.
  115. ### Returns
  116. - Success: A list of `DataSet` objects.
  117. - Failure: `Exception`.
  118. ### Examples
  119. #### List all datasets
  120. ```python
  121. for dataset in rag_object.list_datasets():
  122. print(dataset)
  123. ```
  124. #### Retrieve a dataset by ID
  125. ```python
  126. dataset = rag_object.list_datasets(id = "id_1")
  127. print(dataset[0])
  128. ```
  129. ---
  130. ## Update dataset
  131. ```python
  132. DataSet.update(update_message: dict)
  133. ```
  134. Updates configurations for the current dataset.
  135. ### Parameters
  136. #### update_message: `dict[str, str|int]`, *Required*
  137. A dictionary representing the attributes to update, with the following keys:
  138. - `"name"`: `str` The name of the dataset to update.
  139. - `"embedding_model"`: `str` The embedding model name to update.
  140. - Ensure that `"chunk_count"` is `0` before updating `"embedding_model"`.
  141. - `"chunk_method"`: `str` The chunking method for the dataset. Available options:
  142. - `"naive"`: General
  143. - `"manual`: Manual
  144. - `"qa"`: Q&A
  145. - `"table"`: Table
  146. - `"paper"`: Paper
  147. - `"book"`: Book
  148. - `"laws"`: Laws
  149. - `"presentation"`: Presentation
  150. - `"picture"`: Picture
  151. - `"one"`:One
  152. - `"knowledge_graph"`: Knowledge Graph
  153. - `"email"`: Email
  154. ### Returns
  155. - Success: No value is returned.
  156. - Failure: `Exception`
  157. ### Examples
  158. ```python
  159. from ragflow import RAGFlow
  160. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  161. dataset = rag_object.list_datasets(name="kb_name")
  162. dataset.update({"embedding_model":"BAAI/bge-zh-v1.5", "chunk_method":"manual"})
  163. ```
  164. ---
  165. :::tip API GROUPING
  166. File Management within Dataset
  167. :::
  168. ---
  169. ## Upload documents
  170. ```python
  171. DataSet.upload_documents(document_list: list[dict])
  172. ```
  173. Uploads documents to the current dataset.
  174. ### Parameters
  175. #### document_list: `list[dict]`, *Required*
  176. A list of dictionaries representing the documents to upload, each containing the following keys:
  177. - `"display_name"`: (Optional) The file name to display in the dataset.
  178. - `"blob"`: (Optional) The binary content of the file to upload.
  179. ### Returns
  180. - Success: No value is returned.
  181. - Failure: `Exception`
  182. ### Examples
  183. ```python
  184. dataset = rag_object.create_dataset(name="kb_name")
  185. dataset.upload_documents([{"display_name": "1.txt", "blob": "<BINARY_CONTENT_OF_THE_DOC>"}, {"display_name": "2.pdf", "blob": "<BINARY_CONTENT_OF_THE_DOC>"}])
  186. ```
  187. ---
  188. ## Update document
  189. ```python
  190. Document.update(update_message:dict)
  191. ```
  192. Updates configurations for the current document.
  193. ### Parameters
  194. #### update_message: `dict[str, str|dict[]]`, *Required*
  195. A dictionary representing the attributes to update, with the following keys:
  196. - `"display_name"`: `str` The name of the document to update.
  197. - `"parser_config"`: `dict[str, Any]` The parsing configuration for the document:
  198. - `"chunk_token_count"`: Defaults to `128`.
  199. - `"layout_recognize"`: Defaults to `True`.
  200. - `"delimiter"`: Defaults to `'\n!?。;!?'`.
  201. - `"task_page_size"`: Defaults to `12`.
  202. - `"chunk_method"`: `str` The parsing method to apply to the document.
  203. - `"naive"`: General
  204. - `"manual`: Manual
  205. - `"qa"`: Q&A
  206. - `"table"`: Table
  207. - `"paper"`: Paper
  208. - `"book"`: Book
  209. - `"laws"`: Laws
  210. - `"presentation"`: Presentation
  211. - `"picture"`: Picture
  212. - `"one"`: One
  213. - `"knowledge_graph"`: Knowledge Graph
  214. - `"email"`: Email
  215. ### Returns
  216. - Success: No value is returned.
  217. - Failure: `Exception`
  218. ### Examples
  219. ```python
  220. from ragflow import RAGFlow
  221. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  222. dataset = rag_object.list_datasets(id='id')
  223. dataset = dataset[0]
  224. doc = dataset.list_documents(id="wdfxb5t547d")
  225. doc = doc[0]
  226. doc.update([{"parser_config": {"chunk_token_count": 256}}, {"chunk_method": "manual"}])
  227. ```
  228. ---
  229. ## Download document
  230. ```python
  231. Document.download() -> bytes
  232. ```
  233. Downloads the current document.
  234. ### Returns
  235. The downloaded document in bytes.
  236. ### Examples
  237. ```python
  238. from ragflow import RAGFlow
  239. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  240. dataset = rag_object.list_datasets(id="id")
  241. dataset = dataset[0]
  242. doc = dataset.list_documents(id="wdfxb5t547d")
  243. doc = doc[0]
  244. open("~/ragflow.txt", "wb+").write(doc.download())
  245. print(doc)
  246. ```
  247. ---
  248. ## List documents
  249. ```python
  250. Dataset.list_documents(id:str =None, keywords: str=None, offset: int=0, limit:int = 1024,order_by:str = "create_time", desc: bool = True) -> list[Document]
  251. ```
  252. Lists documents in the current dataset.
  253. ### Parameters
  254. #### id: `str`
  255. The ID of the document to retrieve. Defaults to `None`.
  256. #### keywords: `str`
  257. The keywords used to match document titles. Defaults to `None`.
  258. #### offset: `int`
  259. The starting index for the documents to retrieve. Typically used in confunction with `limit`. Defaults to `0`.
  260. #### limit: `int`
  261. The maximum number of documents to retrieve. Defaults to `1024`.
  262. #### orderby: `str`
  263. The field by which documents should be sorted. Available options:
  264. - `"create_time"` (default)
  265. - `"update_time"`
  266. #### desc: `bool`
  267. Indicates whether the retrieved documents should be sorted in descending order. Defaults to `True`.
  268. ### Returns
  269. - Success: A list of `Document` objects.
  270. - Failure: `Exception`.
  271. A `Document` object contains the following attributes:
  272. - `id`: The document ID. Defaults to `""`.
  273. - `name`: The document name. Defaults to `""`.
  274. - `thumbnail`: The thumbnail image of the document. Defaults to `None`.
  275. - `knowledgebase_id`: The dataset ID associated with the document. Defaults to `None`.
  276. - `chunk_method` The chunk method name. Defaults to `"naive"`.
  277. - `parser_config`: `ParserConfig` Configuration object for the parser. Defaults to `{"pages": [[1, 1000000]]}`.
  278. - `source_type`: The source type of the document. Defaults to `"local"`.
  279. - `type`: Type or category of the document. Defaults to `""`. Reserved for future use.
  280. - `created_by`: `str` The creator of the document. Defaults to `""`.
  281. - `size`: `int` The document size in bytes. Defaults to `0`.
  282. - `token_count`: `int` The number of tokens in the document. Defaults to `0`.
  283. - `chunk_count`: `int` The number of chunks in the document. Defaults to `0`.
  284. - `progress`: `float` The current processing progress as a percentage. Defaults to `0.0`.
  285. - `progress_msg`: `str` A message indicating the current progress status. Defaults to `""`.
  286. - `process_begin_at`: `datetime` The start time of document processing. Defaults to `None`.
  287. - `process_duation`: `float` Duration of the processing in seconds. Defaults to `0.0`.
  288. - `run`: `str` The document's processing status:
  289. - `"0"`: UNSTART (default) ?????????
  290. - `"1"`: RUNNING
  291. - `"2"`: CANCEL
  292. - `"3"`: DONE
  293. - `"4"`: FAIL
  294. - `status`: `str` Reserved for future use.
  295. ### Examples
  296. ```python
  297. from ragflow import RAGFlow
  298. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  299. dataset = rag_object.create_dataset(name="kb_1")
  300. filename1 = "~/ragflow.txt"
  301. blob = open(filename1 , "rb").read()
  302. dataset.upload_documents([{"name":filename1,"blob":blob}])
  303. for doc in dataset.list_documents(keywords="rag", offset=0, limit=12):
  304. print(doc)
  305. ```
  306. ---
  307. ## Delete documents
  308. ```python
  309. DataSet.delete_documents(ids: list[str] = None)
  310. ```
  311. Deletes documents by ID.
  312. ### Parameters
  313. #### ids: `list[list]`
  314. The IDs of the documents to delete. Defaults to `None`. If not specified, all documents in the dataset will be deleted.
  315. ### Returns
  316. - Success: No value is returned.
  317. - Failure: `Exception`
  318. ### Examples
  319. ```python
  320. from ragflow import RAGFlow
  321. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  322. dataset = rag_object.list_datasets(name="kb_1")
  323. dataset = dataset[0]
  324. dataset.delete_documents(ids=["id_1","id_2"])
  325. ```
  326. ---
  327. ## Parse documents
  328. ```python
  329. DataSet.async_parse_documents(document_ids:list[str]) -> None
  330. ```
  331. Parses documents in the current dataset.
  332. ### Parameters
  333. #### document_ids: `list[str]`, *Required*
  334. The IDs of the documents to parse.
  335. ### Returns
  336. - Success: No value is returned.
  337. - Failure: `Exception`
  338. ### Examples
  339. ```python
  340. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  341. dataset = rag_object.create_dataset(name="dataset_name")
  342. documents = [
  343. {'display_name': 'test1.txt', 'blob': open('./test_data/test1.txt',"rb").read()},
  344. {'display_name': 'test2.txt', 'blob': open('./test_data/test2.txt',"rb").read()},
  345. {'display_name': 'test3.txt', 'blob': open('./test_data/test3.txt',"rb").read()}
  346. ]
  347. dataset.upload_documents(documents)
  348. documents = dataset.list_documents(keywords="test")
  349. ids = []
  350. for document in documents:
  351. ids.append(document.id)
  352. dataset.async_parse_documents(ids)
  353. print("Async bulk parsing initiated.")
  354. ```
  355. ---
  356. ## Stop parsing documents
  357. ```python
  358. DataSet.async_cancel_parse_documents(document_ids:list[str])-> None
  359. ```
  360. Stops parsing specified documents.
  361. ### Parameters
  362. #### document_ids: `list[str]`, *Required*
  363. The IDs of the documents for which parsing should be stopped.
  364. ### Returns
  365. - Success: No value is returned.
  366. - Failure: `Exception`
  367. ### Examples
  368. ```python
  369. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  370. dataset = rag_object.create_dataset(name="dataset_name")
  371. documents = [
  372. {'display_name': 'test1.txt', 'blob': open('./test_data/test1.txt',"rb").read()},
  373. {'display_name': 'test2.txt', 'blob': open('./test_data/test2.txt',"rb").read()},
  374. {'display_name': 'test3.txt', 'blob': open('./test_data/test3.txt',"rb").read()}
  375. ]
  376. dataset.upload_documents(documents)
  377. documents = dataset.list_documents(keywords="test")
  378. ids = []
  379. for document in documents:
  380. ids.append(document.id)
  381. dataset.async_parse_documents(ids)
  382. print("Async bulk parsing initiated.")
  383. dataset.async_cancel_parse_documents(ids)
  384. print("Async bulk parsing cancelled.")
  385. ```
  386. ---
  387. ## Add chunk
  388. ```python
  389. Document.add_chunk(content:str, important_keywords:list[str] = []) -> Chunk
  390. ```
  391. Adds a chunk to the current document.
  392. ### Parameters
  393. #### content: `str`, *Required*
  394. The text content of the chunk.
  395. #### important_keywords: `list[str]`
  396. The key terms or phrases to tag with the chunk.
  397. ### Returns
  398. - Success: A `Chunk` object.
  399. - Failure: `Exception`.
  400. A `Chunk` object contains the following attributes:
  401. - `id`: `str`
  402. - `content`: `str` Content of the chunk.
  403. - `important_keywords`: `list[str]` A list of key terms or phrases to tag with the chunk.
  404. - `create_time`: `str` The time when the chunk was created (added to the document).
  405. - `create_timestamp`: `float` The timestamp representing the creation time of the chunk, expressed in seconds since January 1, 1970.
  406. - `knowledgebase_id`: `str` The ID of the associated dataset.
  407. - `document_name`: `str` The name of the associated document.
  408. - `document_id`: `str` The ID of the associated document.
  409. - `available`: `bool` The chunk's availability status in the dataset. Value options:
  410. - `False`: Unavailable
  411. - `True`: Available
  412. ### Examples
  413. ```python
  414. from ragflow import RAGFlow
  415. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  416. dataset = rag_object.list_datasets(id="123")
  417. dtaset = dataset[0]
  418. doc = dataset.list_documents(id="wdfxb5t547d")
  419. doc = doc[0]
  420. chunk = doc.add_chunk(content="xxxxxxx")
  421. ```
  422. ---
  423. ## List chunks
  424. ```python
  425. Document.list_chunks(keywords: str = None, offset: int = 1, limit: int = 1024, id : str = None) -> list[Chunk]
  426. ```
  427. Lists chunks in the current document.
  428. ### Parameters
  429. #### keywords: `str`
  430. The keywords used to match chunk content. Defaults to `None`
  431. #### offset: `int`
  432. The starting index for the chunks to retrieve. Defaults to `1`.
  433. #### limit: `int`
  434. The maximum number of chunks to retrieve. Default: `1024`
  435. #### id: `str`
  436. The ID of the chunk to retrieve. Default: `None`
  437. ### Returns
  438. - Success: A list of `Chunk` objects.
  439. - Failure: `Exception`.
  440. ### Examples
  441. ```python
  442. from ragflow import RAGFlow
  443. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  444. dataset = rag_object.list_datasets("123")
  445. dataset = dataset[0]
  446. dataset.async_parse_documents(["wdfxb5t547d"])
  447. for chunk in doc.list_chunks(keywords="rag", offset=0, limit=12):
  448. print(chunk)
  449. ```
  450. ---
  451. ## Delete chunks
  452. ```python
  453. Document.delete_chunks(chunk_ids: list[str])
  454. ```
  455. Deletes chunks by ID.
  456. ### Parameters
  457. #### chunk_ids: `list[str]`
  458. The IDs of the chunks to delete. Defaults to `None`. If not specified, all chunks of the current document will be deleted.
  459. ### Returns
  460. - Success: No value is returned.
  461. - Failure: `Exception`
  462. ### Examples
  463. ```python
  464. from ragflow import RAGFlow
  465. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  466. dataset = rag_object.list_datasets(id="123")
  467. dataset = dataset[0]
  468. doc = dataset.list_documents(id="wdfxb5t547d")
  469. doc = doc[0]
  470. chunk = doc.add_chunk(content="xxxxxxx")
  471. doc.delete_chunks(["id_1","id_2"])
  472. ```
  473. ---
  474. ## Update chunk
  475. ```python
  476. Chunk.update(update_message: dict)
  477. ```
  478. Updates content or configurations for the current chunk.
  479. ### Parameters
  480. #### update_message: `dict[str, str|list[str]|int]` *Required*
  481. A dictionary representing the attributes to update, with the following keys:
  482. - `"content"`: `str` Content of the chunk.
  483. - `"important_keywords"`: `list[str]` A list of key terms or phrases to tag with the chunk.
  484. - `"available"`: `bool` The chunk's availability status in the dataset. Value options:
  485. - `False`: Unavailable
  486. - `True`: Available
  487. ### Returns
  488. - Success: No value is returned.
  489. - Failure: `Exception`
  490. ### Examples
  491. ```python
  492. from ragflow import RAGFlow
  493. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  494. dataset = rag_object.list_datasets(id="123")
  495. dataset = dataset[0]
  496. doc = dataset.list_documents(id="wdfxb5t547d")
  497. doc = doc[0]
  498. chunk = doc.add_chunk(content="xxxxxxx")
  499. chunk.update({"content":"sdfx..."})
  500. ```
  501. ---
  502. ## Retrieve chunks
  503. ```python
  504. RAGFlow.retrieve(question:str="", datasets:list[str]=None, document=list[str]=None, offset:int=1, limit:int=1024, similarity_threshold:float=0.2, vector_similarity_weight:float=0.3, top_k:int=1024,rerank_id:str=None,keyword:bool=False,higlight:bool=False) -> list[Chunk]
  505. ```
  506. Retrieves chunks from specified datasets.
  507. ### Parameters
  508. #### question: `str` *Required*
  509. The user query or query keywords. Defaults to `""`.
  510. #### datasets: `list[str]`, *Required*
  511. The datasets to search from.
  512. #### document: `list[str]`
  513. The documents to search from. Defaults to `None`.
  514. #### offset: `int`
  515. The starting index for the documents to retrieve. Defaults to `1`.
  516. #### limit: `int`
  517. The maximum number of chunks to retrieve. Defaults to `1024`.
  518. #### Similarity_threshold: `float`
  519. The minimum similarity score. Defaults to `0.2`.
  520. #### similarity_threshold_weight: `float`
  521. The weight of vector cosine similarity. Defaults to `0.3`. If x represents the vector cosine similarity, then (1 - x) is the term similarity weight.
  522. #### top_k: `int`
  523. The number of chunks engaged in vector cosine computaton. Defaults to `1024`.
  524. #### rerank_id: `str`
  525. The ID of the rerank model. Defaults to `None`.
  526. #### keyword: `bool`
  527. Indicates whether to enable keyword-based matching:
  528. - `True`: Enable keyword-based matching.
  529. - `False`: Disable keyword-based matching (default).
  530. #### highlight: `bool`
  531. Specifying whether to enable highlighting of matched terms in the results:
  532. - `True`: Enable highlighting of matched terms.
  533. - `False`: Disable highlighting of matched terms (default).
  534. ### Returns
  535. - Success: A list of `Chunk` objects representing the document chunks.
  536. - Failure: `Exception`
  537. ### Examples
  538. ```python
  539. from ragflow import RAGFlow
  540. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  541. dataset = rag_object.list_datasets(name="ragflow")
  542. dataset = dataset[0]
  543. name = 'ragflow_test.txt'
  544. path = './test_data/ragflow_test.txt'
  545. rag_object.create_document(dataset, name=name, blob=open(path, "rb").read())
  546. doc = dataset.list_documents(name=name)
  547. doc = doc[0]
  548. dataset.async_parse_documents([doc.id])
  549. for c in rag_object.retrieve(question="What's ragflow?",
  550. datasets=[dataset.id], documents=[doc.id],
  551. offset=1, limit=30, similarity_threshold=0.2,
  552. vector_similarity_weight=0.3,
  553. top_k=1024
  554. ):
  555. print(c)
  556. ```
  557. ---
  558. :::tip API GROUPING
  559. Chat Assistant Management
  560. :::
  561. ---
  562. ## Create chat assistant
  563. ```python
  564. RAGFlow.create_chat(
  565. name: str,
  566. avatar: str = "",
  567. knowledgebases: list[str] = [],
  568. llm: Chat.LLM = None,
  569. prompt: Chat.Prompt = None
  570. ) -> Chat
  571. ```
  572. Creates a chat assistant.
  573. ### Parameters
  574. The following shows the attributes of a `Chat` object:
  575. #### name: `str`, *Required*
  576. The name of the chat assistant..
  577. #### avatar: `str`
  578. Base64 encoding of the avatar. Defaults to `""`.
  579. #### knowledgebases: `list[str]`
  580. The IDs of the associated datasets. Defaults to `[""]`.
  581. #### llm: `Chat.LLM`
  582. The llm of the created chat. Defaults to `None`. When the value is `None`, a dictionary with the following values will be generated as the default.
  583. An `LLM` object contains the following attributes:
  584. - `model_name`, `str`
  585. The chat model name. If it is `None`, the user's default chat model will be returned.
  586. - `temperature`, `float`
  587. Controls the randomness of the model's predictions. A lower temperature increases the model's conficence in its responses; a higher temperature increases creativity and diversity. Defaults to `0.1`.
  588. - `top_p`, `float`
  589. Also known as “nucleus sampling”, this parameter sets a threshold to select a smaller set of words to sample from. It focuses on the most likely words, cutting off the less probable ones. Defaults to `0.3`
  590. - `presence_penalty`, `float`
  591. This discourages the model from repeating the same information by penalizing words that have already appeared in the conversation. Defaults to `0.2`.
  592. - `frequency penalty`, `float`
  593. Similar to the presence penalty, this reduces the model’s tendency to repeat the same words frequently. Defaults to `0.7`.
  594. - `max_token`, `int`
  595. This sets the maximum length of the model’s output, measured in the number of tokens (words or pieces of words). Defaults to `512`.
  596. #### prompt: `Chat.Prompt`
  597. Instructions for the LLM to follow. A `Prompt` object contains the following attributes:
  598. - `"similarity_threshold"`: `float` A similarity score to evaluate distance between two lines of text. It's weighted keywords similarity and vector cosine similarity. If the similarity between query and chunk is less than this threshold, the chunk will be filtered out. Defaults to `0.2`.
  599. - `"keywords_similarity_weight"`: `float` It's weighted keywords similarity and vector cosine similarity or rerank score (0~1). Defaults to `0.7`.
  600. - `"top_n"`: `int` Not all the chunks whose similarity score is above the 'similarity threshold' will be feed to LLMs. LLM can only see these 'Top N' chunks. Defaults to `8`.
  601. - `"variables"`: `list[dict[]]` If you use dialog APIs, the variables might help you chat with your clients with different strategies. The variables are used to fill in the 'System' part in prompt in order to give LLM a hint. The 'knowledge' is a very special variable which will be filled-in with the retrieved chunks. All the variables in 'System' should be curly bracketed. Defaults to `[{"key": "knowledge", "optional": True}]`
  602. - `"rerank_model"`: `str` If it is not specified, vector cosine similarity will be used; otherwise, reranking score will be used. Defaults to `""`.
  603. - `"empty_response"`: `str` If nothing is retrieved in the dataset for the user's question, this will be used as the response. To allow the LLM to improvise when nothing is retrieved, leave this blank. Defaults to `None`.
  604. - `"opener"`: `str` The opening greeting for the user. Defaults to `"Hi! I am your assistant, can I help you?"`.
  605. - `"show_quote`: `bool` Indicates whether the source of text should be displayed Defaults to `True`.
  606. - `"prompt"`: `str` The prompt content. Defaults to `You are an intelligent assistant. Please summarize the content of the dataset to answer the question. Please list the data in the knowledge base and answer in detail. When all knowledge base content is irrelevant to the question, your answer must include the sentence "The answer you are looking for is not found in the knowledge base!" Answers need to consider chat history.
  607. Here is the knowledge base:
  608. {knowledge}
  609. The above is the knowledge base.`.
  610. ### Returns
  611. - Success: A `Chat` object representing the chat assistant.
  612. - Failure: `Exception`
  613. ### Examples
  614. ```python
  615. from ragflow import RAGFlow
  616. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  617. datasets = rag_object.list_datasets(name="kb_1")
  618. dataset_ids = []
  619. for dataset in datasets:
  620. dataset_ids.append(dataset.id)
  621. assistant = rag_object.create_chat("Miss R", knowledgebases=dataset_ids)
  622. ```
  623. ---
  624. ## Update chat assistant
  625. ```python
  626. Chat.update(update_message: dict)
  627. ```
  628. Updates configurations for the current chat assistant.
  629. ### Parameters
  630. #### update_message: `dict[str, str|list[str]|dict[]]`, *Required*
  631. A dictionary representing the attributes to update, with the following keys:
  632. - `"name"`: `str` The name of the chat assistant to update.
  633. - `"avatar"`: `str` Base64 encoding of the avatar. Defaults to `""`
  634. - `"knowledgebases"`: `list[str]` The datasets to update.
  635. - `"llm"`: `dict` The LLM settings:
  636. - `"model_name"`, `str` The chat model name.
  637. - `"temperature"`, `float` Controls the randomness of the model's predictions.
  638. - `"top_p"`, `float` Also known as “nucleus sampling”, this parameter sets a threshold to select a smaller set of words to sample from.
  639. - `"presence_penalty"`, `float` This discourages the model from repeating the same information by penalizing words that have appeared in the conversation.
  640. - `"frequency penalty"`, `float` Similar to presence penalty, this reduces the model’s tendency to repeat the same words.
  641. - `"max_token"`, `int` This sets the maximum length of the model’s output, measured in the number of tokens (words or pieces of words).
  642. - `"prompt"` : Instructions for the LLM to follow.
  643. - `"similarity_threshold"`: `float` A score to evaluate distance between two lines of text. It's weighted keywords similarity and vector cosine similarity. If the similarity between query and chunk is less than this threshold, the chunk will be filtered out. Defaults to `0.2`.
  644. - `"keywords_similarity_weight"`: `float` It's weighted keywords similarity and vector cosine similarity or rerank score (0~1). Defaults to `0.7`.
  645. - `"top_n"`: `int` Not all the chunks whose similarity score is above the 'similarity threshold' will be feed to LLMs. LLM can only see these 'Top N' chunks. Defaults to `8`.
  646. - `"variables"`: `list[dict[]]` If you use dialog APIs, the variables might help you chat with your clients with different strategies. The variables are used to fill in the 'System' part in prompt in order to give LLM a hint. The 'knowledge' is a very special variable which will be filled-in with the retrieved chunks. All the variables in 'System' should be curly bracketed. Defaults to `[{"key": "knowledge", "optional": True}]`
  647. - `"rerank_model"`: `str` If it is not specified, vector cosine similarity will be used; otherwise, reranking score will be used. Defaults to `""`.
  648. - `"empty_response"`: `str` If nothing is retrieved in the dataset for the user's question, this will be used as the response. To allow the LLM to improvise when nothing is retrieved, leave this blank. Defaults to `None`.
  649. - `"opener"`: `str` The opening greeting for the user. Defaults to `"Hi! I am your assistant, can I help you?"`.
  650. - `"show_quote`: `bool` Indicates whether the source of text should be displayed Defaults to `True`.
  651. - `"prompt"`: `str` The prompt content. Defaults to `You are an intelligent assistant. Please summarize the content of the knowledge base to answer the question. Please list the data in the knowledge base and answer in detail. When all knowledge base content is irrelevant to the question, your answer must include the sentence "The answer you are looking for is not found in the knowledge base!" Answers need to consider chat history.
  652. Here is the knowledge base:
  653. {knowledge}
  654. The above is the knowledge base.`.
  655. ### Returns
  656. - Success: No value is returned.
  657. - Failure: `Exception`
  658. ### Examples
  659. ```python
  660. from ragflow import RAGFlow
  661. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  662. datasets = rag_object.list_datasets(name="kb_1")
  663. assistant = rag_object.create_chat("Miss R", knowledgebases=datasets)
  664. assistant.update({"name": "Stefan", "llm": {"temperature": 0.8}, "prompt": {"top_n": 8}})
  665. ```
  666. ---
  667. ## Delete chat assistants
  668. ```python
  669. RAGFlow.delete_chats(ids: list[str] = None)
  670. ```
  671. Deletes chat assistants by ID.
  672. ### Parameters
  673. #### ids: `list[str]`
  674. The IDs of the chat assistants to delete. Defaults to `None`. If not specified, all chat assistants in the system will be deleted.
  675. ### Returns
  676. - Success: No value is returned.
  677. - Failure: `Exception`
  678. ### Examples
  679. ```python
  680. from ragflow import RAGFlow
  681. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  682. rag_object.delete_chats(ids=["id_1","id_2"])
  683. ```
  684. ---
  685. ## List chat assistants
  686. ```python
  687. RAGFlow.list_chats(
  688. page: int = 1,
  689. page_size: int = 1024,
  690. orderby: str = "create_time",
  691. desc: bool = True,
  692. id: str = None,
  693. name: str = None
  694. ) -> list[Chat]
  695. ```
  696. Lists chat assistants.
  697. ### Parameters
  698. #### page: `int`
  699. Specifies the page on which the chat assistants will be displayed. Defaults to `1`.
  700. #### page_size: `int`
  701. The number of chat assistants on each page. Defaults to `1024`.
  702. #### orderby: `str`
  703. The attribute by which the results are sorted. Available options:
  704. - `"create_time"` (default)
  705. - `"update_time"`
  706. #### desc: `bool`
  707. Indicates whether the retrieved chat assistants should be sorted in descending order. Defaults to `True`.
  708. #### id: `str`
  709. The ID of the chat assistant to retrieve. Defaults to `None`.
  710. #### name: `str`
  711. The name of the chat assistant to retrieve. Defaults to `None`.
  712. ### Returns
  713. - Success: A list of `Chat` objects.
  714. - Failure: `Exception`.
  715. ### Examples
  716. ```python
  717. from ragflow import RAGFlow
  718. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  719. for assistant in rag_object.list_chats():
  720. print(assistant)
  721. ```
  722. ---
  723. :::tip API GROUPING
  724. Chat Session APIs
  725. :::
  726. ---
  727. ## Create session
  728. ```python
  729. Chat.create_session(name: str = "New session") -> Session
  730. ```
  731. Creates a chat session.
  732. ### Parameters
  733. #### name: `str`
  734. The name of the chat session to create.
  735. ### Returns
  736. - Success: A `Session` object containing the following attributes:
  737. - `id`: `str` The auto-generated unique identifier of the created session.
  738. - `name`: `str` The name of the created session.
  739. - `message`: `list[Message]` The messages of the created session assistant. Default: `[{"role": "assistant", "content": "Hi! I am your assistant,can I help you?"}]`
  740. - `chat_id`: `str` The ID of the associated chat assistant.
  741. - Failure: `Exception`
  742. ### Examples
  743. ```python
  744. from ragflow import RAGFlow
  745. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  746. assistant = rag_object.list_chats(name="Miss R")
  747. assistant = assistant[0]
  748. session = assistant.create_session()
  749. ```
  750. ---
  751. ## Update session
  752. ```python
  753. Session.update(update_message: dict)
  754. ```
  755. Updates the current session name.
  756. ### Parameters
  757. #### update_message: `dict[str, Any]`, *Required*
  758. A dictionary representing the attributes to update, with only one key:
  759. - `"name"`: `str` The name of the session to update.
  760. ### Returns
  761. - Success: No value is returned.
  762. - Failure: `Exception`
  763. ### Examples
  764. ```python
  765. from ragflow import RAGFlow
  766. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  767. assistant = rag_object.list_chats(name="Miss R")
  768. assistant = assistant[0]
  769. session = assistant.create_session("session_name")
  770. session.update({"name": "updated_name"})
  771. ```
  772. ---
  773. ## List sessions
  774. ```python
  775. Chat.list_sessions(
  776. page: int = 1,
  777. page_size: int = 1024,
  778. orderby: str = "create_time",
  779. desc: bool = True,
  780. id: str = None,
  781. name: str = None
  782. ) -> list[Session]
  783. ```
  784. Lists sessions associated with the current chat assistant.
  785. ### Parameters
  786. #### page: `int`
  787. Specifies the page on which the sessions will be displayed. Defaults to `1`.
  788. #### page_size: `int`
  789. The number of sessions on each page. Defaults to `1024`.
  790. #### orderby: `str`
  791. The field by which sessions should be sorted. Available options:
  792. - `"create_time"` (default)
  793. - `"update_time"`
  794. #### desc: `bool`
  795. Indicates whether the retrieved sessions should be sorted in descending order. Defaults to `True`.
  796. #### id: `str`
  797. The ID of the chat session to retrieve. Defaults to `None`.
  798. #### name: `str`
  799. The name of the chat session to retrieve. Defaults to `None`.
  800. ### Returns
  801. - Success: A list of `Session` objects associated with the current chat assistant.
  802. - Failure: `Exception`.
  803. ### Examples
  804. ```python
  805. from ragflow import RAGFlow
  806. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  807. assistant = rag_object.list_chats(name="Miss R")
  808. assistant = assistant[0]
  809. for session in assistant.list_sessions():
  810. print(session)
  811. ```
  812. ---
  813. ## Delete sessions
  814. ```python
  815. Chat.delete_sessions(ids:list[str] = None)
  816. ```
  817. Deletes sessions by ID.
  818. ### Parameters
  819. #### ids: `list[str]`
  820. The IDs of the sessions to delete. Defaults to `None`. If not specified, all sessions associated with the current chat assistant will be deleted.
  821. ### Returns
  822. - Success: No value is returned.
  823. - Failure: `Exception`
  824. ### Examples
  825. ```python
  826. from ragflow import RAGFlow
  827. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  828. assistant = rag_object.list_chats(name="Miss R")
  829. assistant = assistant[0]
  830. assistant.delete_sessions(ids=["id_1","id_2"])
  831. ```
  832. ---
  833. ## Chat
  834. ```python
  835. Session.ask(question: str, stream: bool = False) -> Optional[Message, iter[Message]]
  836. ```
  837. Asks a question to start a conversation.
  838. ### Parameters
  839. #### question: `str` *Required*
  840. The question to start an AI chat.
  841. #### stream: `str`
  842. Indicates whether to output responses in a streaming way:
  843. - `True`: Enable streaming.
  844. - `False`: (Default) Disable streaming.
  845. ### Returns
  846. - A `Message` object containing the response to the question if `stream` is set to `False`
  847. - An iterator containing multiple `message` objects (`iter[Message]`) if `stream` is set to `True`
  848. The following shows the attributes of a `Message` object:
  849. #### id: `str`
  850. The auto-generated message ID.
  851. #### content: `str`
  852. The content of the message. Defaults to `"Hi! I am your assistant, can I help you?"`.
  853. #### reference: `list[Chunk]`
  854. A list of `Chunk` objects representing references to the message, each containing the following attributes:
  855. - `id` `str`
  856. The chunk ID.
  857. - `content` `str`
  858. The content of the chunk.
  859. - `image_id` `str`
  860. The ID of the snapshot of the chunk.
  861. - `document_id` `str`
  862. The ID of the referenced document.
  863. - `document_name` `str`
  864. The name of the referenced document.
  865. - `position` `list[str]`
  866. The location information of the chunk within the referenced document.
  867. - `knowledgebase_id` `str`
  868. The ID of the dataset to which the referenced document belongs.
  869. - `similarity` `float`
  870. A composite similarity score of the chunk ranging from `0` to `1`, with a higher value indicating greater similarity.
  871. - `vector_similarity` `float`
  872. A vector similarity score of the chunk ranging from `0` to `1`, with a higher value indicating greater similarity between vector embeddings.
  873. - `term_similarity` `float`
  874. A keyword similarity score of the chunk ranging from `0` to `1`, with a higher value indicating greater similarity between keywords.
  875. ### Examples
  876. ```python
  877. from ragflow import RAGFlow
  878. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  879. assistant = rag_object.list_chats(name="Miss R")
  880. assistant = assistant[0]
  881. session = assistant.create_session()
  882. print("\n==================== Miss R =====================\n")
  883. print(assistant.get_prologue())
  884. while True:
  885. question = input("\n==================== User =====================\n> ")
  886. print("\n==================== Miss R =====================\n")
  887. cont = ""
  888. for ans in session.ask(question, stream=True):
  889. print(answer.content[len(cont):], end='', flush=True)
  890. cont = answer.content
  891. ```