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 45KB

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