選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

python_api_reference.md 47KB

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