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

python_api_reference.md 49KB

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