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.

python_api_reference.md 45KB

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