Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

python_api_reference.md 46KB

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