You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

python_api_reference.md 50KB

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