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

python_api_reference.md 44KB

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