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.

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