您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

python_api_reference.md 38KB

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