Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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