Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

python_api_reference.md 47KB

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