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

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