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

python_api_reference.md 49KB

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