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

python_api_reference.md 49KB

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