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

python_api_reference.md 47KB

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