Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

python_api_reference.md 45KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660
  1. ---
  2. sidebar_position: 2
  3. slug: /python_api_reference
  4. ---
  5. # Python API
  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-large-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. - `"meta_fields"`: `dict[str, Any]` The meta fields of the dataset.
  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. ## FILE MANAGEMENT WITHIN DATASET
  199. ---
  200. ### Upload documents
  201. ```python
  202. DataSet.upload_documents(document_list: list[dict])
  203. ```
  204. Uploads documents to the current dataset.
  205. #### Parameters
  206. ##### document_list: `list[dict]`, *Required*
  207. A list of dictionaries representing the documents to upload, each containing the following keys:
  208. - `"display_name"`: (Optional) The file name to display in the dataset.
  209. - `"blob"`: (Optional) The binary content of the file to upload.
  210. #### Returns
  211. - Success: No value is returned.
  212. - Failure: `Exception`
  213. #### Examples
  214. ```python
  215. dataset = rag_object.create_dataset(name="kb_name")
  216. dataset.upload_documents([{"display_name": "1.txt", "blob": "<BINARY_CONTENT_OF_THE_DOC>"}, {"display_name": "2.pdf", "blob": "<BINARY_CONTENT_OF_THE_DOC>"}])
  217. ```
  218. ---
  219. ### Update document
  220. ```python
  221. Document.update(update_message:dict)
  222. ```
  223. Updates configurations for the current document.
  224. #### Parameters
  225. ##### update_message: `dict[str, str|dict[]]`, *Required*
  226. A dictionary representing the attributes to update, with the following keys:
  227. - `"display_name"`: `str` The name of the document to update.
  228. - `"chunk_method"`: `str` The parsing method to apply to the document.
  229. - `"naive"`: General
  230. - `"manual`: Manual
  231. - `"qa"`: Q&A
  232. - `"table"`: Table
  233. - `"paper"`: Paper
  234. - `"book"`: Book
  235. - `"laws"`: Laws
  236. - `"presentation"`: Presentation
  237. - `"picture"`: Picture
  238. - `"one"`: One
  239. - `"knowledge_graph"`: Knowledge Graph
  240. 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!
  241. - `"email"`: Email
  242. - `"parser_config"`: `dict[str, Any]` The parsing configuration for the document. Its attributes vary based on the selected `"chunk_method"`:
  243. - `"chunk_method"`=`"naive"`:
  244. `{"chunk_token_num":128,"delimiter":"\\n!?;。;!?","html4excel":False,"layout_recognize":True,"raptor":{"user_raptor":False}}`.
  245. - `chunk_method`=`"qa"`:
  246. `{"raptor": {"user_raptor": False}}`
  247. - `chunk_method`=`"manuel"`:
  248. `{"raptor": {"user_raptor": False}}`
  249. - `chunk_method`=`"table"`:
  250. `None`
  251. - `chunk_method`=`"paper"`:
  252. `{"raptor": {"user_raptor": False}}`
  253. - `chunk_method`=`"book"`:
  254. `{"raptor": {"user_raptor": False}}`
  255. - `chunk_method`=`"laws"`:
  256. `{"raptor": {"user_raptor": False}}`
  257. - `chunk_method`=`"presentation"`:
  258. `{"raptor": {"user_raptor": False}}`
  259. - `chunk_method`=`"picture"`:
  260. `None`
  261. - `chunk_method`=`"one"`:
  262. `None`
  263. - `chunk_method`=`"knowledge-graph"`:
  264. `{"chunk_token_num":128,"delimiter":"\\n!?;。;!?","entity_types":["organization","person","location","event","time"]}`
  265. - `chunk_method`=`"email"`:
  266. `None`
  267. #### Returns
  268. - Success: No value is returned.
  269. - Failure: `Exception`
  270. #### Examples
  271. ```python
  272. from ragflow_sdk import RAGFlow
  273. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  274. dataset = rag_object.list_datasets(id='id')
  275. dataset = dataset[0]
  276. doc = dataset.list_documents(id="wdfxb5t547d")
  277. doc = doc[0]
  278. doc.update([{"parser_config": {"chunk_token_count": 256}}, {"chunk_method": "manual"}])
  279. ```
  280. ---
  281. ### Download document
  282. ```python
  283. Document.download() -> bytes
  284. ```
  285. Downloads the current document.
  286. #### Returns
  287. The downloaded document in bytes.
  288. #### Examples
  289. ```python
  290. from ragflow_sdk import RAGFlow
  291. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  292. dataset = rag_object.list_datasets(id="id")
  293. dataset = dataset[0]
  294. doc = dataset.list_documents(id="wdfxb5t547d")
  295. doc = doc[0]
  296. open("~/ragflow.txt", "wb+").write(doc.download())
  297. print(doc)
  298. ```
  299. ---
  300. ### List documents
  301. ```python
  302. 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]
  303. ```
  304. Lists documents in the current dataset.
  305. #### Parameters
  306. ##### id: `str`
  307. The ID of the document to retrieve. Defaults to `None`.
  308. ##### keywords: `str`
  309. The keywords used to match document titles. Defaults to `None`.
  310. ##### page: `int`
  311. Specifies the page on which the documents will be displayed. Defaults to `1`.
  312. ##### page_size: `int`
  313. The maximum number of documents on each page. Defaults to `30`.
  314. ##### orderby: `str`
  315. The field by which documents should be sorted. Available options:
  316. - `"create_time"` (default)
  317. - `"update_time"`
  318. ##### desc: `bool`
  319. Indicates whether the retrieved documents should be sorted in descending order. Defaults to `True`.
  320. #### Returns
  321. - Success: A list of `Document` objects.
  322. - Failure: `Exception`.
  323. A `Document` object contains the following attributes:
  324. - `id`: The document ID. Defaults to `""`.
  325. - `name`: The document name. Defaults to `""`.
  326. - `thumbnail`: The thumbnail image of the document. Defaults to `None`.
  327. - `dataset_id`: The dataset ID associated with the document. Defaults to `None`.
  328. - `chunk_method` The chunk method name. Defaults to `"naive"`.
  329. - `source_type`: The source type of the document. Defaults to `"local"`.
  330. - `type`: Type or category of the document. Defaults to `""`. Reserved for future use.
  331. - `created_by`: `str` The creator of the document. Defaults to `""`.
  332. - `size`: `int` The document size in bytes. Defaults to `0`.
  333. - `token_count`: `int` The number of tokens in the document. Defaults to `0`.
  334. - `chunk_count`: `int` The number of chunks in the document. Defaults to `0`.
  335. - `progress`: `float` The current processing progress as a percentage. Defaults to `0.0`.
  336. - `progress_msg`: `str` A message indicating the current progress status. Defaults to `""`.
  337. - `process_begin_at`: `datetime` The start time of document processing. Defaults to `None`.
  338. - `process_duation`: `float` Duration of the processing in seconds. Defaults to `0.0`.
  339. - `run`: `str` The document's processing status:
  340. - `"UNSTART"` (default)
  341. - `"RUNNING"`
  342. - `"CANCEL"`
  343. - `"DONE"`
  344. - `"FAIL"`
  345. - `status`: `str` Reserved for future use.
  346. - `parser_config`: `ParserConfig` Configuration object for the parser. Its attributes vary based on the selected `chunk_method`:
  347. - `chunk_method`=`"naive"`:
  348. `{"chunk_token_num":128,"delimiter":"\\n!?;。;!?","html4excel":False,"layout_recognize":True,"raptor":{"user_raptor":False}}`.
  349. - `chunk_method`=`"qa"`:
  350. `{"raptor": {"user_raptor": False}}`
  351. - `chunk_method`=`"manuel"`:
  352. `{"raptor": {"user_raptor": False}}`
  353. - `chunk_method`=`"table"`:
  354. `None`
  355. - `chunk_method`=`"paper"`:
  356. `{"raptor": {"user_raptor": False}}`
  357. - `chunk_method`=`"book"`:
  358. `{"raptor": {"user_raptor": False}}`
  359. - `chunk_method`=`"laws"`:
  360. `{"raptor": {"user_raptor": False}}`
  361. - `chunk_method`=`"presentation"`:
  362. `{"raptor": {"user_raptor": False}}`
  363. - `chunk_method`=`"picure"`:
  364. `None`
  365. - `chunk_method`=`"one"`:
  366. `None`
  367. - `chunk_method`=`"knowledge-graph"`:
  368. `{"chunk_token_num":128,"delimiter": "\\n!?;。;!?","entity_types":["organization","person","location","event","time"]}`
  369. - `chunk_method`=`"email"`:
  370. `None`
  371. #### Examples
  372. ```python
  373. from ragflow_sdk import RAGFlow
  374. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  375. dataset = rag_object.create_dataset(name="kb_1")
  376. filename1 = "~/ragflow.txt"
  377. blob = open(filename1 , "rb").read()
  378. dataset.upload_documents([{"name":filename1,"blob":blob}])
  379. for doc in dataset.list_documents(keywords="rag", page=0, page_size=12):
  380. print(doc)
  381. ```
  382. ---
  383. ### Delete documents
  384. ```python
  385. DataSet.delete_documents(ids: list[str] = None)
  386. ```
  387. Deletes documents by ID.
  388. #### Parameters
  389. ##### ids: `list[list]`
  390. The IDs of the documents to delete. Defaults to `None`. If it is not specified, all documents in the dataset will be deleted.
  391. #### Returns
  392. - Success: No value is returned.
  393. - Failure: `Exception`
  394. #### Examples
  395. ```python
  396. from ragflow_sdk import RAGFlow
  397. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  398. dataset = rag_object.list_datasets(name="kb_1")
  399. dataset = dataset[0]
  400. dataset.delete_documents(ids=["id_1","id_2"])
  401. ```
  402. ---
  403. ### Parse documents
  404. ```python
  405. DataSet.async_parse_documents(document_ids:list[str]) -> None
  406. ```
  407. Parses documents in the current dataset.
  408. #### Parameters
  409. ##### document_ids: `list[str]`, *Required*
  410. The IDs of the documents to parse.
  411. #### Returns
  412. - Success: No value is returned.
  413. - Failure: `Exception`
  414. #### Examples
  415. ```python
  416. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  417. dataset = rag_object.create_dataset(name="dataset_name")
  418. documents = [
  419. {'display_name': 'test1.txt', 'blob': open('./test_data/test1.txt',"rb").read()},
  420. {'display_name': 'test2.txt', 'blob': open('./test_data/test2.txt',"rb").read()},
  421. {'display_name': 'test3.txt', 'blob': open('./test_data/test3.txt',"rb").read()}
  422. ]
  423. dataset.upload_documents(documents)
  424. documents = dataset.list_documents(keywords="test")
  425. ids = []
  426. for document in documents:
  427. ids.append(document.id)
  428. dataset.async_parse_documents(ids)
  429. print("Async bulk parsing initiated.")
  430. ```
  431. ---
  432. ### Stop parsing documents
  433. ```python
  434. DataSet.async_cancel_parse_documents(document_ids:list[str])-> None
  435. ```
  436. Stops parsing specified documents.
  437. #### Parameters
  438. ##### document_ids: `list[str]`, *Required*
  439. The IDs of the documents for which parsing should be stopped.
  440. #### Returns
  441. - Success: No value is returned.
  442. - Failure: `Exception`
  443. #### Examples
  444. ```python
  445. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  446. dataset = rag_object.create_dataset(name="dataset_name")
  447. documents = [
  448. {'display_name': 'test1.txt', 'blob': open('./test_data/test1.txt',"rb").read()},
  449. {'display_name': 'test2.txt', 'blob': open('./test_data/test2.txt',"rb").read()},
  450. {'display_name': 'test3.txt', 'blob': open('./test_data/test3.txt',"rb").read()}
  451. ]
  452. dataset.upload_documents(documents)
  453. documents = dataset.list_documents(keywords="test")
  454. ids = []
  455. for document in documents:
  456. ids.append(document.id)
  457. dataset.async_parse_documents(ids)
  458. print("Async bulk parsing initiated.")
  459. dataset.async_cancel_parse_documents(ids)
  460. print("Async bulk parsing cancelled.")
  461. ```
  462. ---
  463. ## CHUNK MANAGEMENT WITHIN DATASET
  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. datasets = rag_object.list_datasets(id="123")
  495. dataset = datasets[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. docs = dataset.list_documents(keywords="test", page=1, page_size=12)
  525. for chunk in docs[0].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 computation. 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. documents =[{"display_name":"test_retrieve_chunks.txt","blob":open(path, "rb").read()}]
  624. docs = dataset.upload_documents(documents)
  625. doc = docs[0]
  626. doc.add_chunk(content="This is a chunk addition test")
  627. for c in rag_object.retrieve(dataset_ids=[dataset.id],document_ids=[doc.id]):
  628. print(c)
  629. ```
  630. ---
  631. ## CHAT ASSISTANT MANAGEMENT
  632. ---
  633. ### Create chat assistant
  634. ```python
  635. RAGFlow.create_chat(
  636. name: str,
  637. avatar: str = "",
  638. dataset_ids: list[str] = [],
  639. llm: Chat.LLM = None,
  640. prompt: Chat.Prompt = None
  641. ) -> Chat
  642. ```
  643. Creates a chat assistant.
  644. #### Parameters
  645. ##### name: `str`, *Required*
  646. The name of the chat assistant.
  647. ##### avatar: `str`
  648. Base64 encoding of the avatar. Defaults to `""`.
  649. ##### dataset_ids: `list[str]`
  650. The IDs of the associated datasets. Defaults to `[""]`.
  651. ##### llm: `Chat.LLM`
  652. 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:
  653. - `model_name`: `str`
  654. The chat model name. If it is `None`, the user's default chat model will be used.
  655. - `temperature`: `float`
  656. 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`.
  657. - `top_p`: `float`
  658. 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`
  659. - `presence_penalty`: `float`
  660. This discourages the model from repeating the same information by penalizing words that have already appeared in the conversation. Defaults to `0.2`.
  661. - `frequency penalty`: `float`
  662. Similar to the presence penalty, this reduces the model’s tendency to repeat the same words frequently. Defaults to `0.7`.
  663. - `max_token`: `int`
  664. 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.
  665. ##### prompt: `Chat.Prompt`
  666. Instructions for the LLM to follow. A `Prompt` object contains the following attributes:
  667. - `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`.
  668. - `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`.
  669. - `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`.
  670. - `variables`: `list[dict[]]` This argument lists the variables to use in the 'System' field of **Chat Configurations**. Note that:
  671. - `knowledge` is a reserved variable, which represents the retrieved chunks.
  672. - All the variables in 'System' should be curly bracketed.
  673. - The default value is `[{"key": "knowledge", "optional": True}]`.
  674. - `rerank_model`: `str` If it is not specified, vector cosine similarity will be used; otherwise, reranking score will be used. Defaults to `""`.
  675. - `top_k`: `int` Refers to the process of reordering or selecting the top-k items from a list or set based on a specific ranking criterion. Default to 1024.
  676. - `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`.
  677. - `opener`: `str` The opening greeting for the user. Defaults to `"Hi! I am your assistant, can I help you?"`.
  678. - `show_quote`: `bool` Indicates whether the source of text should be displayed. Defaults to `True`.
  679. - `prompt`: `str` The prompt content.
  680. #### Returns
  681. - Success: A `Chat` object representing the chat assistant.
  682. - Failure: `Exception`
  683. #### Examples
  684. ```python
  685. from ragflow_sdk import RAGFlow
  686. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  687. datasets = rag_object.list_datasets(name="kb_1")
  688. dataset_ids = []
  689. for dataset in datasets:
  690. dataset_ids.append(dataset.id)
  691. assistant = rag_object.create_chat("Miss R", dataset_ids=dataset_ids)
  692. ```
  693. ---
  694. ### Update chat assistant
  695. ```python
  696. Chat.update(update_message: dict)
  697. ```
  698. Updates configurations for the current chat assistant.
  699. #### Parameters
  700. ##### update_message: `dict[str, str|list[str]|dict[]]`, *Required*
  701. A dictionary representing the attributes to update, with the following keys:
  702. - `"name"`: `str` The revised name of the chat assistant.
  703. - `"avatar"`: `str` Base64 encoding of the avatar. Defaults to `""`
  704. - `"dataset_ids"`: `list[str]` The datasets to update.
  705. - `"llm"`: `dict` The LLM settings:
  706. - `"model_name"`, `str` The chat model name.
  707. - `"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.
  708. - `"top_p"`, `float` Also known as “nucleus sampling”, this parameter sets a threshold to select a smaller set of words to sample from.
  709. - `"presence_penalty"`, `float` This discourages the model from repeating the same information by penalizing words that have appeared in the conversation.
  710. - `"frequency penalty"`, `float` Similar to presence penalty, this reduces the model’s tendency to repeat the same words.
  711. - `"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.
  712. - `"prompt"` : Instructions for the LLM to follow.
  713. - `"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`.
  714. - `"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`.
  715. - `"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`.
  716. - `"variables"`: `list[dict[]]` This argument lists the variables to use in the 'System' field of **Chat Configurations**. Note that:
  717. - `knowledge` is a reserved variable, which represents the retrieved chunks.
  718. - All the variables in 'System' should be curly bracketed.
  719. - The default value is `[{"key": "knowledge", "optional": True}]`.
  720. - `"rerank_model"`: `str` If it is not specified, vector cosine similarity will be used; otherwise, reranking score will be used. Defaults to `""`.
  721. - `"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`.
  722. - `"opener"`: `str` The opening greeting for the user. Defaults to `"Hi! I am your assistant, can I help you?"`.
  723. - `"show_quote`: `bool` Indicates whether the source of text should be displayed Defaults to `True`.
  724. - `"prompt"`: `str` The prompt content.
  725. #### Returns
  726. - Success: No value is returned.
  727. - Failure: `Exception`
  728. #### Examples
  729. ```python
  730. from ragflow_sdk import RAGFlow
  731. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  732. datasets = rag_object.list_datasets(name="kb_1")
  733. dataset_id = datasets[0].id
  734. assistant = rag_object.create_chat("Miss R", dataset_ids=[dataset_id])
  735. assistant.update({"name": "Stefan", "llm": {"temperature": 0.8}, "prompt": {"top_n": 8}})
  736. ```
  737. ---
  738. ### Delete chat assistants
  739. ```python
  740. RAGFlow.delete_chats(ids: list[str] = None)
  741. ```
  742. Deletes chat assistants by ID.
  743. #### Parameters
  744. ##### ids: `list[str]`
  745. 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.
  746. #### Returns
  747. - Success: No value is returned.
  748. - Failure: `Exception`
  749. #### Examples
  750. ```python
  751. from ragflow_sdk import RAGFlow
  752. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  753. rag_object.delete_chats(ids=["id_1","id_2"])
  754. ```
  755. ---
  756. ### List chat assistants
  757. ```python
  758. RAGFlow.list_chats(
  759. page: int = 1,
  760. page_size: int = 30,
  761. orderby: str = "create_time",
  762. desc: bool = True,
  763. id: str = None,
  764. name: str = None
  765. ) -> list[Chat]
  766. ```
  767. Lists chat assistants.
  768. #### Parameters
  769. ##### page: `int`
  770. Specifies the page on which the chat assistants will be displayed. Defaults to `1`.
  771. ##### page_size: `int`
  772. The number of chat assistants on each page. Defaults to `30`.
  773. ##### orderby: `str`
  774. The attribute by which the results are sorted. Available options:
  775. - `"create_time"` (default)
  776. - `"update_time"`
  777. ##### desc: `bool`
  778. Indicates whether the retrieved chat assistants should be sorted in descending order. Defaults to `True`.
  779. ##### id: `str`
  780. The ID of the chat assistant to retrieve. Defaults to `None`.
  781. ##### name: `str`
  782. The name of the chat assistant to retrieve. Defaults to `None`.
  783. #### Returns
  784. - Success: A list of `Chat` objects.
  785. - Failure: `Exception`.
  786. #### Examples
  787. ```python
  788. from ragflow_sdk import RAGFlow
  789. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  790. for assistant in rag_object.list_chats():
  791. print(assistant)
  792. ```
  793. ---
  794. ## SESSION MANAGEMENT
  795. ---
  796. ### Create session with chat assistant
  797. ```python
  798. Chat.create_session(name: str = "New session") -> Session
  799. ```
  800. Creates a session with the current chat assistant.
  801. #### Parameters
  802. ##### name: `str`
  803. The name of the chat session to create.
  804. #### Returns
  805. - Success: A `Session` object containing the following attributes:
  806. - `id`: `str` The auto-generated unique identifier of the created session.
  807. - `name`: `str` The name of the created session.
  808. - `message`: `list[Message]` The opening message of the created session. Default: `[{"role": "assistant", "content": "Hi! I am your assistant,can I help you?"}]`
  809. - `chat_id`: `str` The ID of the associated chat assistant.
  810. - Failure: `Exception`
  811. #### Examples
  812. ```python
  813. from ragflow_sdk import RAGFlow
  814. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  815. assistant = rag_object.list_chats(name="Miss R")
  816. assistant = assistant[0]
  817. session = assistant.create_session()
  818. ```
  819. ---
  820. ### Update chat assistant's session
  821. ```python
  822. Session.update(update_message: dict)
  823. ```
  824. Updates the current session of the current chat assistant.
  825. #### Parameters
  826. ##### update_message: `dict[str, Any]`, *Required*
  827. A dictionary representing the attributes to update, with only one key:
  828. - `"name"`: `str` The revised name of the session.
  829. #### Returns
  830. - Success: No value is returned.
  831. - Failure: `Exception`
  832. #### Examples
  833. ```python
  834. from ragflow_sdk import RAGFlow
  835. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  836. assistant = rag_object.list_chats(name="Miss R")
  837. assistant = assistant[0]
  838. session = assistant.create_session("session_name")
  839. session.update({"name": "updated_name"})
  840. ```
  841. ---
  842. ### List chat assistant's sessions
  843. ```python
  844. Chat.list_sessions(
  845. page: int = 1,
  846. page_size: int = 30,
  847. orderby: str = "create_time",
  848. desc: bool = True,
  849. id: str = None,
  850. name: str = None
  851. ) -> list[Session]
  852. ```
  853. Lists sessions associated with the current chat assistant.
  854. #### Parameters
  855. ##### page: `int`
  856. Specifies the page on which the sessions will be displayed. Defaults to `1`.
  857. ##### page_size: `int`
  858. The number of sessions on each page. Defaults to `30`.
  859. ##### orderby: `str`
  860. The field by which sessions should be sorted. Available options:
  861. - `"create_time"` (default)
  862. - `"update_time"`
  863. ##### desc: `bool`
  864. Indicates whether the retrieved sessions should be sorted in descending order. Defaults to `True`.
  865. ##### id: `str`
  866. The ID of the chat session to retrieve. Defaults to `None`.
  867. ##### name: `str`
  868. The name of the chat session to retrieve. Defaults to `None`.
  869. #### Returns
  870. - Success: A list of `Session` objects associated with the current chat assistant.
  871. - Failure: `Exception`.
  872. #### Examples
  873. ```python
  874. from ragflow_sdk import RAGFlow
  875. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  876. assistant = rag_object.list_chats(name="Miss R")
  877. assistant = assistant[0]
  878. for session in assistant.list_sessions():
  879. print(session)
  880. ```
  881. ---
  882. ### Delete chat assistant's sessions
  883. ```python
  884. Chat.delete_sessions(ids:list[str] = None)
  885. ```
  886. Deletes sessions of the current chat assistant by ID.
  887. #### Parameters
  888. ##### ids: `list[str]`
  889. 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.
  890. #### Returns
  891. - Success: No value is returned.
  892. - Failure: `Exception`
  893. #### Examples
  894. ```python
  895. from ragflow_sdk import RAGFlow
  896. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  897. assistant = rag_object.list_chats(name="Miss R")
  898. assistant = assistant[0]
  899. assistant.delete_sessions(ids=["id_1","id_2"])
  900. ```
  901. ---
  902. ### Converse with chat assistant
  903. ```python
  904. Session.ask(question: str = "", stream: bool = False, **kwargs) -> Optional[Message, iter[Message]]
  905. ```
  906. Asks a specified chat assistant a question to start an AI-powered conversation.
  907. :::tip NOTE
  908. In streaming mode, not all responses include a reference, as this depends on the system's judgement.
  909. :::
  910. #### Parameters
  911. ##### question: `str`, *Required*
  912. The question to start an AI-powered conversation. Default to `""`
  913. ##### stream: `bool`
  914. Indicates whether to output responses in a streaming way:
  915. - `True`: Enable streaming (default).
  916. - `False`: Disable streaming.
  917. ##### **kwargs
  918. The parameters in prompt(system).
  919. #### Returns
  920. - A `Message` object containing the response to the question if `stream` is set to `False`.
  921. - An iterator containing multiple `message` objects (`iter[Message]`) if `stream` is set to `True`
  922. The following shows the attributes of a `Message` object:
  923. ##### id: `str`
  924. The auto-generated message ID.
  925. ##### content: `str`
  926. The content of the message. Defaults to `"Hi! I am your assistant, can I help you?"`.
  927. ##### reference: `list[Chunk]`
  928. A list of `Chunk` objects representing references to the message, each containing the following attributes:
  929. - `id` `str`
  930. The chunk ID.
  931. - `content` `str`
  932. The content of the chunk.
  933. - `img_id` `str`
  934. The ID of the snapshot of the chunk. Applicable only when the source of the chunk is an image, PPT, PPTX, or PDF file.
  935. - `document_id` `str`
  936. The ID of the referenced document.
  937. - `document_name` `str`
  938. The name of the referenced document.
  939. - `position` `list[str]`
  940. The location information of the chunk within the referenced document.
  941. - `dataset_id` `str`
  942. The ID of the dataset to which the referenced document belongs.
  943. - `similarity` `float`
  944. 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`.
  945. - `vector_similarity` `float`
  946. A vector similarity score of the chunk ranging from `0` to `1`, with a higher value indicating greater similarity between vector embeddings.
  947. - `term_similarity` `float`
  948. A keyword similarity score of the chunk ranging from `0` to `1`, with a higher value indicating greater similarity between keywords.
  949. #### Examples
  950. ```python
  951. from ragflow_sdk import RAGFlow
  952. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  953. assistant = rag_object.list_chats(name="Miss R")
  954. assistant = assistant[0]
  955. session = assistant.create_session()
  956. print("\n==================== Miss R =====================\n")
  957. print("Hello. What can I do for you?")
  958. while True:
  959. question = input("\n==================== User =====================\n> ")
  960. print("\n==================== Miss R =====================\n")
  961. cont = ""
  962. for ans in session.ask(question, stream=True):
  963. print(ans.content[len(cont):], end='', flush=True)
  964. cont = ans.content
  965. ```
  966. ---
  967. ### Create session with agent
  968. ```python
  969. Agent.create_session(id,rag, **kwargs) -> Session
  970. ```
  971. Creates a session with the current agent.
  972. #### Parameters
  973. ##### id: `str`, *Required*
  974. The id of agent
  975. ##### rag:`RAGFlow object`
  976. The RAGFlow object
  977. ##### **kwargs
  978. The parameters in `begin` component.
  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.
  984. - Failure: `Exception`
  985. #### Examples
  986. ```python
  987. from ragflow_sdk import RAGFlow, Agent
  988. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  989. AGENT_ID = "AGENT_ID"
  990. session = Agent.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`
  1003. The question to start an AI-powered conversation. Ifthe **Begin** component takes parameters, a question is not required.
  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. ## AGENT MANAGEMENT
  1095. ---
  1096. ### List agents
  1097. ```python
  1098. RAGFlow.list_agents(
  1099. page: int = 1,
  1100. page_size: int = 30,
  1101. orderby: str = "create_time",
  1102. desc: bool = True,
  1103. id: str = None,
  1104. title: str = None
  1105. ) -> List[Agent]
  1106. ```
  1107. Lists agents.
  1108. #### Parameters
  1109. ##### page: `int`
  1110. Specifies the page on which the agents will be displayed. Defaults to `1`.
  1111. ##### page_size: `int`
  1112. The number of agents on each page. Defaults to `30`.
  1113. ##### orderby: `str`
  1114. The attribute by which the results are sorted. Available options:
  1115. - `"create_time"` (default)
  1116. - `"update_time"`
  1117. ##### desc: `bool`
  1118. Indicates whether the retrieved agents should be sorted in descending order. Defaults to `True`.
  1119. ##### id: `str`
  1120. The ID of the agent to retrieve. Defaults to `None`.
  1121. ##### name: `str`
  1122. The name of the agent to retrieve. Defaults to `None`.
  1123. #### Returns
  1124. - Success: A list of `Agent` objects.
  1125. - Failure: `Exception`.
  1126. #### Examples
  1127. ```python
  1128. from ragflow_sdk import RAGFlow
  1129. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  1130. for agent in rag_object.list_agents():
  1131. print(agent)
  1132. ```
  1133. ---