選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

python_api_reference.md 50KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913
  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](https://ragflow.io/docs/dev/acquire_ragflow_api_key).
  7. :::tip NOTE
  8. Run the following command to download the Python SDK:
  9. ```bash
  10. pip install ragflow-sdk
  11. ```
  12. :::
  13. ---
  14. ## 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(
  366. id: str = None,
  367. keywords: str = None,
  368. page: int = 1,
  369. page_size: int = 30,
  370. order_by: str = "create_time",
  371. desc: bool = True,
  372. create_time_from: int = 0,
  373. create_time_to: int = 0
  374. ) -> list[Document]
  375. ```
  376. Lists documents in the current dataset.
  377. #### Parameters
  378. ##### id: `str`
  379. The ID of the document to retrieve. Defaults to `None`.
  380. ##### keywords: `str`
  381. The keywords used to match document titles. Defaults to `None`.
  382. ##### page: `int`
  383. Specifies the page on which the documents will be displayed. Defaults to `1`.
  384. ##### page_size: `int`
  385. The maximum number of documents on each page. Defaults to `30`.
  386. ##### orderby: `str`
  387. The field by which documents should be sorted. Available options:
  388. - `"create_time"` (default)
  389. - `"update_time"`
  390. ##### desc: `bool`
  391. Indicates whether the retrieved documents should be sorted in descending order. Defaults to `True`.
  392. ##### create_time_from: `int`
  393. Unix timestamp for filtering documents created after this time. 0 means no filter. Defaults to 0.
  394. ##### create_time_to: `int`
  395. Unix timestamp for filtering documents created before this time. 0 means no filter. Defaults to 0.
  396. #### Returns
  397. - Success: A list of `Document` objects.
  398. - Failure: `Exception`.
  399. A `Document` object contains the following attributes:
  400. - `id`: The document ID. Defaults to `""`.
  401. - `name`: The document name. Defaults to `""`.
  402. - `thumbnail`: The thumbnail image of the document. Defaults to `None`.
  403. - `dataset_id`: The dataset ID associated with the document. Defaults to `None`.
  404. - `chunk_method` The chunking method name. Defaults to `"naive"`.
  405. - `source_type`: The source type of the document. Defaults to `"local"`.
  406. - `type`: Type or category of the document. Defaults to `""`. Reserved for future use.
  407. - `created_by`: `str` The creator of the document. Defaults to `""`.
  408. - `size`: `int` The document size in bytes. Defaults to `0`.
  409. - `token_count`: `int` The number of tokens in the document. Defaults to `0`.
  410. - `chunk_count`: `int` The number of chunks in the document. Defaults to `0`.
  411. - `progress`: `float` The current processing progress as a percentage. Defaults to `0.0`.
  412. - `progress_msg`: `str` A message indicating the current progress status. Defaults to `""`.
  413. - `process_begin_at`: `datetime` The start time of document processing. Defaults to `None`.
  414. - `process_duration`: `float` Duration of the processing in seconds. Defaults to `0.0`.
  415. - `run`: `str` The document's processing status:
  416. - `"UNSTART"` (default)
  417. - `"RUNNING"`
  418. - `"CANCEL"`
  419. - `"DONE"`
  420. - `"FAIL"`
  421. - `status`: `str` Reserved for future use.
  422. - `parser_config`: `ParserConfig` Configuration object for the parser. Its attributes vary based on the selected `chunk_method`:
  423. - `chunk_method`=`"naive"`:
  424. `{"chunk_token_num":128,"delimiter":"\\n","html4excel":False,"layout_recognize":True,"raptor":{"use_raptor":False}}`.
  425. - `chunk_method`=`"qa"`:
  426. `{"raptor": {"use_raptor": False}}`
  427. - `chunk_method`=`"manuel"`:
  428. `{"raptor": {"use_raptor": False}}`
  429. - `chunk_method`=`"table"`:
  430. `None`
  431. - `chunk_method`=`"paper"`:
  432. `{"raptor": {"use_raptor": False}}`
  433. - `chunk_method`=`"book"`:
  434. `{"raptor": {"use_raptor": False}}`
  435. - `chunk_method`=`"laws"`:
  436. `{"raptor": {"use_raptor": False}}`
  437. - `chunk_method`=`"presentation"`:
  438. `{"raptor": {"use_raptor": False}}`
  439. - `chunk_method`=`"picure"`:
  440. `None`
  441. - `chunk_method`=`"one"`:
  442. `None`
  443. - `chunk_method`=`"email"`:
  444. `None`
  445. #### Examples
  446. ```python
  447. from ragflow_sdk import RAGFlow
  448. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  449. dataset = rag_object.create_dataset(name="kb_1")
  450. filename1 = "~/ragflow.txt"
  451. blob = open(filename1 , "rb").read()
  452. dataset.upload_documents([{"name":filename1,"blob":blob}])
  453. for doc in dataset.list_documents(keywords="rag", page=0, page_size=12):
  454. print(doc)
  455. ```
  456. ---
  457. ### Delete documents
  458. ```python
  459. DataSet.delete_documents(ids: list[str] = None)
  460. ```
  461. Deletes documents by ID.
  462. #### Parameters
  463. ##### ids: `list[list]`
  464. The IDs of the documents to delete. Defaults to `None`. If it is not specified, all documents in the dataset will be deleted.
  465. #### Returns
  466. - Success: No value is returned.
  467. - Failure: `Exception`
  468. #### Examples
  469. ```python
  470. from ragflow_sdk import RAGFlow
  471. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  472. dataset = rag_object.list_datasets(name="kb_1")
  473. dataset = dataset[0]
  474. dataset.delete_documents(ids=["id_1","id_2"])
  475. ```
  476. ---
  477. ### Parse documents
  478. ```python
  479. DataSet.async_parse_documents(document_ids:list[str]) -> None
  480. ```
  481. Parses documents in the current dataset.
  482. #### Parameters
  483. ##### document_ids: `list[str]`, *Required*
  484. The IDs of the documents to parse.
  485. #### Returns
  486. - Success: No value is returned.
  487. - Failure: `Exception`
  488. #### Examples
  489. ```python
  490. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  491. dataset = rag_object.create_dataset(name="dataset_name")
  492. documents = [
  493. {'display_name': 'test1.txt', 'blob': open('./test_data/test1.txt',"rb").read()},
  494. {'display_name': 'test2.txt', 'blob': open('./test_data/test2.txt',"rb").read()},
  495. {'display_name': 'test3.txt', 'blob': open('./test_data/test3.txt',"rb").read()}
  496. ]
  497. dataset.upload_documents(documents)
  498. documents = dataset.list_documents(keywords="test")
  499. ids = []
  500. for document in documents:
  501. ids.append(document.id)
  502. dataset.async_parse_documents(ids)
  503. print("Async bulk parsing initiated.")
  504. ```
  505. ---
  506. ### Stop parsing documents
  507. ```python
  508. DataSet.async_cancel_parse_documents(document_ids:list[str])-> None
  509. ```
  510. Stops parsing specified documents.
  511. #### Parameters
  512. ##### document_ids: `list[str]`, *Required*
  513. The IDs of the documents for which parsing should be stopped.
  514. #### Returns
  515. - Success: No value is returned.
  516. - Failure: `Exception`
  517. #### Examples
  518. ```python
  519. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  520. dataset = rag_object.create_dataset(name="dataset_name")
  521. documents = [
  522. {'display_name': 'test1.txt', 'blob': open('./test_data/test1.txt',"rb").read()},
  523. {'display_name': 'test2.txt', 'blob': open('./test_data/test2.txt',"rb").read()},
  524. {'display_name': 'test3.txt', 'blob': open('./test_data/test3.txt',"rb").read()}
  525. ]
  526. dataset.upload_documents(documents)
  527. documents = dataset.list_documents(keywords="test")
  528. ids = []
  529. for document in documents:
  530. ids.append(document.id)
  531. dataset.async_parse_documents(ids)
  532. print("Async bulk parsing initiated.")
  533. dataset.async_cancel_parse_documents(ids)
  534. print("Async bulk parsing cancelled.")
  535. ```
  536. ---
  537. ## CHUNK MANAGEMENT WITHIN DATASET
  538. ---
  539. ### Add chunk
  540. ```python
  541. Document.add_chunk(content:str, important_keywords:list[str] = []) -> Chunk
  542. ```
  543. Adds a chunk to the current document.
  544. #### Parameters
  545. ##### content: `str`, *Required*
  546. The text content of the chunk.
  547. ##### important_keywords: `list[str]`
  548. The key terms or phrases to tag with the chunk.
  549. #### Returns
  550. - Success: A `Chunk` object.
  551. - Failure: `Exception`.
  552. A `Chunk` object contains the following attributes:
  553. - `id`: `str`: The chunk ID.
  554. - `content`: `str` The text content of the chunk.
  555. - `important_keywords`: `list[str]` A list of key terms or phrases tagged with the chunk.
  556. - `create_time`: `str` The time when the chunk was created (added to the document).
  557. - `create_timestamp`: `float` The timestamp representing the creation time of the chunk, expressed in seconds since January 1, 1970.
  558. - `dataset_id`: `str` The ID of the associated dataset.
  559. - `document_name`: `str` The name of the associated document.
  560. - `document_id`: `str` The ID of the associated document.
  561. - `available`: `bool` The chunk's availability status in the dataset. Value options:
  562. - `False`: Unavailable
  563. - `True`: Available (default)
  564. #### Examples
  565. ```python
  566. from ragflow_sdk import RAGFlow
  567. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  568. datasets = rag_object.list_datasets(id="123")
  569. dataset = datasets[0]
  570. doc = dataset.list_documents(id="wdfxb5t547d")
  571. doc = doc[0]
  572. chunk = doc.add_chunk(content="xxxxxxx")
  573. ```
  574. ---
  575. ### List chunks
  576. ```python
  577. Document.list_chunks(keywords: str = None, page: int = 1, page_size: int = 30, id : str = None) -> list[Chunk]
  578. ```
  579. Lists chunks in the current document.
  580. #### Parameters
  581. ##### keywords: `str`
  582. The keywords used to match chunk content. Defaults to `None`
  583. ##### page: `int`
  584. Specifies the page on which the chunks will be displayed. Defaults to `1`.
  585. ##### page_size: `int`
  586. The maximum number of chunks on each page. Defaults to `30`.
  587. ##### id: `str`
  588. The ID of the chunk to retrieve. Default: `None`
  589. #### Returns
  590. - Success: A list of `Chunk` objects.
  591. - Failure: `Exception`.
  592. #### Examples
  593. ```python
  594. from ragflow_sdk import RAGFlow
  595. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  596. dataset = rag_object.list_datasets("123")
  597. dataset = dataset[0]
  598. docs = dataset.list_documents(keywords="test", page=1, page_size=12)
  599. for chunk in docs[0].list_chunks(keywords="rag", page=0, page_size=12):
  600. print(chunk)
  601. ```
  602. ---
  603. ### Delete chunks
  604. ```python
  605. Document.delete_chunks(chunk_ids: list[str])
  606. ```
  607. Deletes chunks by ID.
  608. #### Parameters
  609. ##### chunk_ids: `list[str]`
  610. The IDs of the chunks to delete. Defaults to `None`. If it is not specified, all chunks of the current document will be deleted.
  611. #### Returns
  612. - Success: No value is returned.
  613. - Failure: `Exception`
  614. #### Examples
  615. ```python
  616. from ragflow_sdk import RAGFlow
  617. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  618. dataset = rag_object.list_datasets(id="123")
  619. dataset = dataset[0]
  620. doc = dataset.list_documents(id="wdfxb5t547d")
  621. doc = doc[0]
  622. chunk = doc.add_chunk(content="xxxxxxx")
  623. doc.delete_chunks(["id_1","id_2"])
  624. ```
  625. ---
  626. ### Update chunk
  627. ```python
  628. Chunk.update(update_message: dict)
  629. ```
  630. Updates content or configurations for the current chunk.
  631. #### Parameters
  632. ##### update_message: `dict[str, str|list[str]|int]` *Required*
  633. A dictionary representing the attributes to update, with the following keys:
  634. - `"content"`: `str` The text content of the chunk.
  635. - `"important_keywords"`: `list[str]` A list of key terms or phrases to tag with the chunk.
  636. - `"available"`: `bool` The chunk's availability status in the dataset. Value options:
  637. - `False`: Unavailable
  638. - `True`: Available (default)
  639. #### Returns
  640. - Success: No value is returned.
  641. - Failure: `Exception`
  642. #### Examples
  643. ```python
  644. from ragflow_sdk import RAGFlow
  645. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  646. dataset = rag_object.list_datasets(id="123")
  647. dataset = dataset[0]
  648. doc = dataset.list_documents(id="wdfxb5t547d")
  649. doc = doc[0]
  650. chunk = doc.add_chunk(content="xxxxxxx")
  651. chunk.update({"content":"sdfx..."})
  652. ```
  653. ---
  654. ### Retrieve chunks
  655. ```python
  656. 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]
  657. ```
  658. Retrieves chunks from specified datasets.
  659. #### Parameters
  660. ##### question: `str`, *Required*
  661. The user query or query keywords. Defaults to `""`.
  662. ##### dataset_ids: `list[str]`, *Required*
  663. The IDs of the datasets to search. Defaults to `None`.
  664. ##### document_ids: `list[str]`
  665. 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.
  666. ##### page: `int`
  667. The starting index for the documents to retrieve. Defaults to `1`.
  668. ##### page_size: `int`
  669. The maximum number of chunks to retrieve. Defaults to `30`.
  670. ##### Similarity_threshold: `float`
  671. The minimum similarity score. Defaults to `0.2`.
  672. ##### vector_similarity_weight: `float`
  673. 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.
  674. ##### top_k: `int`
  675. The number of chunks engaged in vector cosine computation. Defaults to `1024`.
  676. ##### rerank_id: `str`
  677. The ID of the rerank model. Defaults to `None`.
  678. ##### keyword: `bool`
  679. Indicates whether to enable keyword-based matching:
  680. - `True`: Enable keyword-based matching.
  681. - `False`: Disable keyword-based matching (default).
  682. ##### highlight: `bool`
  683. Specifies whether to enable highlighting of matched terms in the results:
  684. - `True`: Enable highlighting of matched terms.
  685. - `False`: Disable highlighting of matched terms (default).
  686. ##### cross_languages: `list[string]`
  687. The languages that should be translated into, in order to achieve keywords retrievals in different languages.
  688. #### Returns
  689. - Success: A list of `Chunk` objects representing the document chunks.
  690. - Failure: `Exception`
  691. #### Examples
  692. ```python
  693. from ragflow_sdk import RAGFlow
  694. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  695. dataset = rag_object.list_datasets(name="ragflow")
  696. dataset = dataset[0]
  697. name = 'ragflow_test.txt'
  698. path = './test_data/ragflow_test.txt'
  699. documents =[{"display_name":"test_retrieve_chunks.txt","blob":open(path, "rb").read()}]
  700. docs = dataset.upload_documents(documents)
  701. doc = docs[0]
  702. doc.add_chunk(content="This is a chunk addition test")
  703. for c in rag_object.retrieve(dataset_ids=[dataset.id],document_ids=[doc.id]):
  704. print(c)
  705. ```
  706. ---
  707. ## CHAT ASSISTANT MANAGEMENT
  708. ---
  709. ### Create chat assistant
  710. ```python
  711. RAGFlow.create_chat(
  712. name: str,
  713. avatar: str = "",
  714. dataset_ids: list[str] = [],
  715. llm: Chat.LLM = None,
  716. prompt: Chat.Prompt = None
  717. ) -> Chat
  718. ```
  719. Creates a chat assistant.
  720. #### Parameters
  721. ##### name: `str`, *Required*
  722. The name of the chat assistant.
  723. ##### avatar: `str`
  724. Base64 encoding of the avatar. Defaults to `""`.
  725. ##### dataset_ids: `list[str]`
  726. The IDs of the associated datasets. Defaults to `[""]`.
  727. ##### llm: `Chat.LLM`
  728. 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:
  729. - `model_name`: `str`
  730. The chat model name. If it is `None`, the user's default chat model will be used.
  731. - `temperature`: `float`
  732. 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`.
  733. - `top_p`: `float`
  734. 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`
  735. - `presence_penalty`: `float`
  736. This discourages the model from repeating the same information by penalizing words that have already appeared in the conversation. Defaults to `0.2`.
  737. - `frequency penalty`: `float`
  738. Similar to the presence penalty, this reduces the model’s tendency to repeat the same words frequently. Defaults to `0.7`.
  739. ##### prompt: `Chat.Prompt`
  740. Instructions for the LLM to follow. A `Prompt` object contains the following attributes:
  741. - `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`.
  742. - `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`.
  743. - `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`.
  744. - `variables`: `list[dict[]]` This argument lists the variables to use in the 'System' field of **Chat Configurations**. Note that:
  745. - `knowledge` is a reserved variable, which represents the retrieved chunks.
  746. - All the variables in 'System' should be curly bracketed.
  747. - The default value is `[{"key": "knowledge", "optional": True}]`.
  748. - `rerank_model`: `str` If it is not specified, vector cosine similarity will be used; otherwise, reranking score will be used. Defaults to `""`.
  749. - `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.
  750. - `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`.
  751. - `opener`: `str` The opening greeting for the user. Defaults to `"Hi! I am your assistant, can I help you?"`.
  752. - `show_quote`: `bool` Indicates whether the source of text should be displayed. Defaults to `True`.
  753. - `prompt`: `str` The prompt content.
  754. #### Returns
  755. - Success: A `Chat` object representing the chat assistant.
  756. - Failure: `Exception`
  757. #### Examples
  758. ```python
  759. from ragflow_sdk import RAGFlow
  760. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  761. datasets = rag_object.list_datasets(name="kb_1")
  762. dataset_ids = []
  763. for dataset in datasets:
  764. dataset_ids.append(dataset.id)
  765. assistant = rag_object.create_chat("Miss R", dataset_ids=dataset_ids)
  766. ```
  767. ---
  768. ### Update chat assistant
  769. ```python
  770. Chat.update(update_message: dict)
  771. ```
  772. Updates configurations for the current chat assistant.
  773. #### Parameters
  774. ##### update_message: `dict[str, str|list[str]|dict[]]`, *Required*
  775. A dictionary representing the attributes to update, with the following keys:
  776. - `"name"`: `str` The revised name of the chat assistant.
  777. - `"avatar"`: `str` Base64 encoding of the avatar. Defaults to `""`
  778. - `"dataset_ids"`: `list[str]` The datasets to update.
  779. - `"llm"`: `dict` The LLM settings:
  780. - `"model_name"`, `str` The chat model name.
  781. - `"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.
  782. - `"top_p"`, `float` Also known as “nucleus sampling”, this parameter sets a threshold to select a smaller set of words to sample from.
  783. - `"presence_penalty"`, `float` This discourages the model from repeating the same information by penalizing words that have appeared in the conversation.
  784. - `"frequency penalty"`, `float` Similar to presence penalty, this reduces the model’s tendency to repeat the same words.
  785. - `"prompt"` : Instructions for the LLM to follow.
  786. - `"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`.
  787. - `"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`.
  788. - `"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`.
  789. - `"variables"`: `list[dict[]]` This argument lists the variables to use in the 'System' field of **Chat Configurations**. Note that:
  790. - `knowledge` is a reserved variable, which represents the retrieved chunks.
  791. - All the variables in 'System' should be curly bracketed.
  792. - The default value is `[{"key": "knowledge", "optional": True}]`.
  793. - `"rerank_model"`: `str` If it is not specified, vector cosine similarity will be used; otherwise, reranking score will be used. Defaults to `""`.
  794. - `"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`.
  795. - `"opener"`: `str` The opening greeting for the user. Defaults to `"Hi! I am your assistant, can I help you?"`.
  796. - `"show_quote`: `bool` Indicates whether the source of text should be displayed Defaults to `True`.
  797. - `"prompt"`: `str` The prompt content.
  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. datasets = rag_object.list_datasets(name="kb_1")
  806. dataset_id = datasets[0].id
  807. assistant = rag_object.create_chat("Miss R", dataset_ids=[dataset_id])
  808. assistant.update({"name": "Stefan", "llm": {"temperature": 0.8}, "prompt": {"top_n": 8}})
  809. ```
  810. ---
  811. ### Delete chat assistants
  812. ```python
  813. RAGFlow.delete_chats(ids: list[str] = None)
  814. ```
  815. Deletes chat assistants by ID.
  816. #### Parameters
  817. ##### ids: `list[str]`
  818. 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.
  819. #### Returns
  820. - Success: No value is returned.
  821. - Failure: `Exception`
  822. #### Examples
  823. ```python
  824. from ragflow_sdk import RAGFlow
  825. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  826. rag_object.delete_chats(ids=["id_1","id_2"])
  827. ```
  828. ---
  829. ### List chat assistants
  830. ```python
  831. RAGFlow.list_chats(
  832. page: int = 1,
  833. page_size: int = 30,
  834. orderby: str = "create_time",
  835. desc: bool = True,
  836. id: str = None,
  837. name: str = None
  838. ) -> list[Chat]
  839. ```
  840. Lists chat assistants.
  841. #### Parameters
  842. ##### page: `int`
  843. Specifies the page on which the chat assistants will be displayed. Defaults to `1`.
  844. ##### page_size: `int`
  845. The number of chat assistants on each page. Defaults to `30`.
  846. ##### orderby: `str`
  847. The attribute by which the results are sorted. Available options:
  848. - `"create_time"` (default)
  849. - `"update_time"`
  850. ##### desc: `bool`
  851. Indicates whether the retrieved chat assistants should be sorted in descending order. Defaults to `True`.
  852. ##### id: `str`
  853. The ID of the chat assistant to retrieve. Defaults to `None`.
  854. ##### name: `str`
  855. The name of the chat assistant to retrieve. Defaults to `None`.
  856. #### Returns
  857. - Success: A list of `Chat` objects.
  858. - Failure: `Exception`.
  859. #### Examples
  860. ```python
  861. from ragflow_sdk import RAGFlow
  862. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  863. for assistant in rag_object.list_chats():
  864. print(assistant)
  865. ```
  866. ---
  867. ## SESSION MANAGEMENT
  868. ---
  869. ### Create session with chat assistant
  870. ```python
  871. Chat.create_session(name: str = "New session") -> Session
  872. ```
  873. Creates a session with the current chat assistant.
  874. #### Parameters
  875. ##### name: `str`
  876. The name of the chat session to create.
  877. #### Returns
  878. - Success: A `Session` object containing the following attributes:
  879. - `id`: `str` The auto-generated unique identifier of the created session.
  880. - `name`: `str` The name of the created session.
  881. - `message`: `list[Message]` The opening message of the created session. Default: `[{"role": "assistant", "content": "Hi! I am your assistant, can I help you?"}]`
  882. - `chat_id`: `str` The ID of the associated chat assistant.
  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()
  891. ```
  892. ---
  893. ### Update chat assistant's session
  894. ```python
  895. Session.update(update_message: dict)
  896. ```
  897. Updates the current session of the current chat assistant.
  898. #### Parameters
  899. ##### update_message: `dict[str, Any]`, *Required*
  900. A dictionary representing the attributes to update, with only one key:
  901. - `"name"`: `str` The revised name of the session.
  902. #### Returns
  903. - Success: No value is returned.
  904. - Failure: `Exception`
  905. #### Examples
  906. ```python
  907. from ragflow_sdk import RAGFlow
  908. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  909. assistant = rag_object.list_chats(name="Miss R")
  910. assistant = assistant[0]
  911. session = assistant.create_session("session_name")
  912. session.update({"name": "updated_name"})
  913. ```
  914. ---
  915. ### List chat assistant's sessions
  916. ```python
  917. Chat.list_sessions(
  918. page: int = 1,
  919. page_size: int = 30,
  920. orderby: str = "create_time",
  921. desc: bool = True,
  922. id: str = None,
  923. name: str = None
  924. ) -> list[Session]
  925. ```
  926. Lists sessions associated with the current chat assistant.
  927. #### Parameters
  928. ##### page: `int`
  929. Specifies the page on which the sessions will be displayed. Defaults to `1`.
  930. ##### page_size: `int`
  931. The number of sessions on each page. Defaults to `30`.
  932. ##### orderby: `str`
  933. The field by which sessions should be sorted. Available options:
  934. - `"create_time"` (default)
  935. - `"update_time"`
  936. ##### desc: `bool`
  937. Indicates whether the retrieved sessions should be sorted in descending order. Defaults to `True`.
  938. ##### id: `str`
  939. The ID of the chat session to retrieve. Defaults to `None`.
  940. ##### name: `str`
  941. The name of the chat session to retrieve. Defaults to `None`.
  942. #### Returns
  943. - Success: A list of `Session` objects associated with the current chat assistant.
  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. for session in assistant.list_sessions():
  952. print(session)
  953. ```
  954. ---
  955. ### Delete chat assistant's sessions
  956. ```python
  957. Chat.delete_sessions(ids:list[str] = None)
  958. ```
  959. Deletes sessions of the current chat assistant by ID.
  960. #### Parameters
  961. ##### ids: `list[str]`
  962. 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.
  963. #### Returns
  964. - Success: No value is returned.
  965. - Failure: `Exception`
  966. #### Examples
  967. ```python
  968. from ragflow_sdk import RAGFlow
  969. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  970. assistant = rag_object.list_chats(name="Miss R")
  971. assistant = assistant[0]
  972. assistant.delete_sessions(ids=["id_1","id_2"])
  973. ```
  974. ---
  975. ### Converse with chat assistant
  976. ```python
  977. Session.ask(question: str = "", stream: bool = False, **kwargs) -> Optional[Message, iter[Message]]
  978. ```
  979. Asks a specified chat assistant a question to start an AI-powered conversation.
  980. :::tip NOTE
  981. In streaming mode, not all responses include a reference, as this depends on the system's judgement.
  982. :::
  983. #### Parameters
  984. ##### question: `str`, *Required*
  985. The question to start an AI-powered conversation. Default to `""`
  986. ##### stream: `bool`
  987. Indicates whether to output responses in a streaming way:
  988. - `True`: Enable streaming (default).
  989. - `False`: Disable streaming.
  990. ##### **kwargs
  991. The parameters in prompt(system).
  992. #### Returns
  993. - A `Message` object containing the response to the question if `stream` is set to `False`.
  994. - An iterator containing multiple `message` objects (`iter[Message]`) if `stream` is set to `True`
  995. The following shows the attributes of a `Message` object:
  996. ##### id: `str`
  997. The auto-generated message ID.
  998. ##### content: `str`
  999. The content of the message. Defaults to `"Hi! I am your assistant, can I help you?"`.
  1000. ##### reference: `list[Chunk]`
  1001. A list of `Chunk` objects representing references to the message, each containing the following attributes:
  1002. - `id` `str`
  1003. The chunk ID.
  1004. - `content` `str`
  1005. The content of the chunk.
  1006. - `img_id` `str`
  1007. The ID of the snapshot of the chunk. Applicable only when the source of the chunk is an image, PPT, PPTX, or PDF file.
  1008. - `document_id` `str`
  1009. The ID of the referenced document.
  1010. - `document_name` `str`
  1011. The name of the referenced document.
  1012. - `position` `list[str]`
  1013. The location information of the chunk within the referenced document.
  1014. - `dataset_id` `str`
  1015. The ID of the dataset to which the referenced document belongs.
  1016. - `similarity` `float`
  1017. 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`.
  1018. - `vector_similarity` `float`
  1019. A vector similarity score of the chunk ranging from `0` to `1`, with a higher value indicating greater similarity between vector embeddings.
  1020. - `term_similarity` `float`
  1021. A keyword similarity score of the chunk ranging from `0` to `1`, with a higher value indicating greater similarity between keywords.
  1022. #### Examples
  1023. ```python
  1024. from ragflow_sdk import RAGFlow
  1025. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  1026. assistant = rag_object.list_chats(name="Miss R")
  1027. assistant = assistant[0]
  1028. session = assistant.create_session()
  1029. print("\n==================== Miss R =====================\n")
  1030. print("Hello. What can I do for you?")
  1031. while True:
  1032. question = input("\n==================== User =====================\n> ")
  1033. print("\n==================== Miss R =====================\n")
  1034. cont = ""
  1035. for ans in session.ask(question, stream=True):
  1036. print(ans.content[len(cont):], end='', flush=True)
  1037. cont = ans.content
  1038. ```
  1039. ---
  1040. ### Create session with agent
  1041. ```python
  1042. Agent.create_session(**kwargs) -> Session
  1043. ```
  1044. Creates a session with the current agent.
  1045. #### Parameters
  1046. ##### **kwargs
  1047. The parameters in `begin` component.
  1048. #### Returns
  1049. - Success: A `Session` object containing the following attributes:
  1050. - `id`: `str` The auto-generated unique identifier of the created session.
  1051. - `message`: `list[Message]` The messages of the created session assistant. Default: `[{"role": "assistant", "content": "Hi! I am your assistant, can I help you?"}]`
  1052. - `agent_id`: `str` The ID of the associated agent.
  1053. - Failure: `Exception`
  1054. #### Examples
  1055. ```python
  1056. from ragflow_sdk import RAGFlow, Agent
  1057. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  1058. agent_id = "AGENT_ID"
  1059. agent = rag_object.list_agents(id = agent_id)[0]
  1060. session = agent.create_session()
  1061. ```
  1062. ---
  1063. ### Converse with agent
  1064. ```python
  1065. Session.ask(question: str="", stream: bool = False) -> Optional[Message, iter[Message]]
  1066. ```
  1067. Asks a specified agent a question to start an AI-powered conversation.
  1068. :::tip NOTE
  1069. In streaming mode, not all responses include a reference, as this depends on the system's judgement.
  1070. :::
  1071. #### Parameters
  1072. ##### question: `str`
  1073. The question to start an AI-powered conversation. Ifthe **Begin** component takes parameters, a question is not required.
  1074. ##### stream: `bool`
  1075. Indicates whether to output responses in a streaming way:
  1076. - `True`: Enable streaming (default).
  1077. - `False`: Disable streaming.
  1078. #### Returns
  1079. - A `Message` object containing the response to the question if `stream` is set to `False`
  1080. - An iterator containing multiple `message` objects (`iter[Message]`) if `stream` is set to `True`
  1081. The following shows the attributes of a `Message` object:
  1082. ##### id: `str`
  1083. The auto-generated message ID.
  1084. ##### content: `str`
  1085. The content of the message. Defaults to `"Hi! I am your assistant, can I help you?"`.
  1086. ##### reference: `list[Chunk]`
  1087. A list of `Chunk` objects representing references to the message, each containing the following attributes:
  1088. - `id` `str`
  1089. The chunk ID.
  1090. - `content` `str`
  1091. The content of the chunk.
  1092. - `image_id` `str`
  1093. The ID of the snapshot of the chunk. Applicable only when the source of the chunk is an image, PPT, PPTX, or PDF file.
  1094. - `document_id` `str`
  1095. The ID of the referenced document.
  1096. - `document_name` `str`
  1097. The name of the referenced document.
  1098. - `position` `list[str]`
  1099. The location information of the chunk within the referenced document.
  1100. - `dataset_id` `str`
  1101. The ID of the dataset to which the referenced document belongs.
  1102. - `similarity` `float`
  1103. 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`.
  1104. - `vector_similarity` `float`
  1105. A vector similarity score of the chunk ranging from `0` to `1`, with a higher value indicating greater similarity between vector embeddings.
  1106. - `term_similarity` `float`
  1107. A keyword similarity score of the chunk ranging from `0` to `1`, with a higher value indicating greater similarity between keywords.
  1108. #### Examples
  1109. ```python
  1110. from ragflow_sdk import RAGFlow, Agent
  1111. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  1112. AGENT_id = "AGENT_ID"
  1113. agent = rag_object.list_agents(id = AGENT_id)[0]
  1114. session = agent.create_session()
  1115. print("\n===== Miss R ====\n")
  1116. print("Hello. What can I do for you?")
  1117. while True:
  1118. question = input("\n===== User ====\n> ")
  1119. print("\n==== Miss R ====\n")
  1120. cont = ""
  1121. for ans in session.ask(question, stream=True):
  1122. print(ans.content[len(cont):], end='', flush=True)
  1123. cont = ans.content
  1124. ```
  1125. ---
  1126. ### List agent sessions
  1127. ```python
  1128. Agent.list_sessions(
  1129. page: int = 1,
  1130. page_size: int = 30,
  1131. orderby: str = "update_time",
  1132. desc: bool = True,
  1133. id: str = None
  1134. ) -> List[Session]
  1135. ```
  1136. Lists sessions associated with the current agent.
  1137. #### Parameters
  1138. ##### page: `int`
  1139. Specifies the page on which the sessions will be displayed. Defaults to `1`.
  1140. ##### page_size: `int`
  1141. The number of sessions on each page. Defaults to `30`.
  1142. ##### orderby: `str`
  1143. The field by which sessions should be sorted. Available options:
  1144. - `"create_time"`
  1145. - `"update_time"`(default)
  1146. ##### desc: `bool`
  1147. Indicates whether the retrieved sessions should be sorted in descending order. Defaults to `True`.
  1148. ##### id: `str`
  1149. The ID of the agent session to retrieve. Defaults to `None`.
  1150. #### Returns
  1151. - Success: A list of `Session` objects associated with the current agent.
  1152. - Failure: `Exception`.
  1153. #### Examples
  1154. ```python
  1155. from ragflow_sdk import RAGFlow
  1156. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  1157. AGENT_id = "AGENT_ID"
  1158. agent = rag_object.list_agents(id = AGENT_id)[0]
  1159. sessons = agent.list_sessions()
  1160. for session in sessions:
  1161. print(session)
  1162. ```
  1163. ---
  1164. ### Delete agent's sessions
  1165. ```python
  1166. Agent.delete_sessions(ids: list[str] = None)
  1167. ```
  1168. Deletes sessions of a agent by ID.
  1169. #### Parameters
  1170. ##### ids: `list[str]`
  1171. The IDs of the sessions to delete. Defaults to `None`. If it is not specified, all sessions associated with the agent will be deleted.
  1172. #### Returns
  1173. - Success: No value is returned.
  1174. - Failure: `Exception`
  1175. #### Examples
  1176. ```python
  1177. from ragflow_sdk import RAGFlow
  1178. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  1179. AGENT_id = "AGENT_ID"
  1180. agent = rag_object.list_agents(id = AGENT_id)[0]
  1181. agent.delete_sessions(ids=["id_1","id_2"])
  1182. ```
  1183. ---
  1184. ## AGENT MANAGEMENT
  1185. ---
  1186. ### List agents
  1187. ```python
  1188. RAGFlow.list_agents(
  1189. page: int = 1,
  1190. page_size: int = 30,
  1191. orderby: str = "create_time",
  1192. desc: bool = True,
  1193. id: str = None,
  1194. title: str = None
  1195. ) -> List[Agent]
  1196. ```
  1197. Lists agents.
  1198. #### Parameters
  1199. ##### page: `int`
  1200. Specifies the page on which the agents will be displayed. Defaults to `1`.
  1201. ##### page_size: `int`
  1202. The number of agents on each page. Defaults to `30`.
  1203. ##### orderby: `str`
  1204. The attribute by which the results are sorted. Available options:
  1205. - `"create_time"` (default)
  1206. - `"update_time"`
  1207. ##### desc: `bool`
  1208. Indicates whether the retrieved agents should be sorted in descending order. Defaults to `True`.
  1209. ##### id: `str`
  1210. The ID of the agent to retrieve. Defaults to `None`.
  1211. ##### name: `str`
  1212. The name of the agent to retrieve. Defaults to `None`.
  1213. #### Returns
  1214. - Success: A list of `Agent` objects.
  1215. - Failure: `Exception`.
  1216. #### Examples
  1217. ```python
  1218. from ragflow_sdk import RAGFlow
  1219. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  1220. for agent in rag_object.list_agents():
  1221. print(agent)
  1222. ```
  1223. ---
  1224. ### Create agent
  1225. ```python
  1226. RAGFlow.create_agent(
  1227. title: str,
  1228. dsl: dict,
  1229. description: str | None = None
  1230. ) -> None
  1231. ```
  1232. Create an agent.
  1233. #### Parameters
  1234. ##### title: `str`
  1235. Specifies the title of the agent.
  1236. ##### dsl: `dict`
  1237. Specifies the canvas DSL of the agent.
  1238. ##### description: `str`
  1239. The description of the agent. Defaults to `None`.
  1240. #### Returns
  1241. - Success: Nothing.
  1242. - Failure: `Exception`.
  1243. #### Examples
  1244. ```python
  1245. from ragflow_sdk import RAGFlow
  1246. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  1247. rag_object.create_agent(
  1248. title="Test Agent",
  1249. description="A test agent",
  1250. dsl={
  1251. # ... canvas DSL here ...
  1252. }
  1253. )
  1254. ```
  1255. ---
  1256. ### Update agent
  1257. ```python
  1258. RAGFlow.update_agent(
  1259. agent_id: str,
  1260. title: str | None = None,
  1261. description: str | None = None,
  1262. dsl: dict | None = None
  1263. ) -> None
  1264. ```
  1265. Update an agent.
  1266. #### Parameters
  1267. ##### agent_id: `str`
  1268. Specifies the id of the agent to be updated.
  1269. ##### title: `str`
  1270. Specifies the new title of the agent. `None` if you do not want to update this.
  1271. ##### dsl: `dict`
  1272. Specifies the new canvas DSL of the agent. `None` if you do not want to update this.
  1273. ##### description: `str`
  1274. The new description of the agent. `None` if you do not want to update this.
  1275. #### Returns
  1276. - Success: Nothing.
  1277. - Failure: `Exception`.
  1278. #### Examples
  1279. ```python
  1280. from ragflow_sdk import RAGFlow
  1281. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  1282. rag_object.update_agent(
  1283. agent_id="58af890a2a8911f0a71a11b922ed82d6",
  1284. title="Test Agent",
  1285. description="A test agent",
  1286. dsl={
  1287. # ... canvas DSL here ...
  1288. }
  1289. )
  1290. ```
  1291. ---
  1292. ### Delete agent
  1293. ```python
  1294. RAGFlow.delete_agent(
  1295. agent_id: str
  1296. ) -> None
  1297. ```
  1298. Delete an agent.
  1299. #### Parameters
  1300. ##### agent_id: `str`
  1301. Specifies the id of the agent to be deleted.
  1302. #### Returns
  1303. - Success: Nothing.
  1304. - Failure: `Exception`.
  1305. #### Examples
  1306. ```python
  1307. from ragflow_sdk import RAGFlow
  1308. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  1309. rag_object.delete_agent("58af890a2a8911f0a71a11b922ed82d6")
  1310. ```
  1311. ---