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

python_api_reference.md 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317
  1. # DRAFT Python API Reference
  2. **THE API REFERENCES BELOW ARE STILL UNDER DEVELOPMENT.**
  3. ---
  4. :::tip NOTE
  5. Dataset Management
  6. :::
  7. ---
  8. ## Create dataset
  9. ```python
  10. RAGFlow.create_dataset(
  11. name: str,
  12. avatar: str = "",
  13. description: str = "",
  14. language: str = "English",
  15. permission: str = "me",
  16. document_count: int = 0,
  17. chunk_count: int = 0,
  18. chunk_method: str = "naive",
  19. parser_config: DataSet.ParserConfig = None
  20. ) -> DataSet
  21. ```
  22. Creates a dataset.
  23. ### Parameters
  24. #### name: `str`, *Required*
  25. The unique name of the dataset to create. It must adhere to the following requirements:
  26. - Permitted characters include:
  27. - English letters (a-z, A-Z)
  28. - Digits (0-9)
  29. - "_" (underscore)
  30. - Must begin with an English letter or underscore.
  31. - Maximum 65,535 characters.
  32. - Case-insensitive.
  33. #### avatar: `str`
  34. Base64 encoding of the avatar. Defaults to `""`
  35. #### description: `str`
  36. A brief description of the dataset to create. Defaults to `""`.
  37. #### language: `str`
  38. The language setting of the dataset to create. Available options:
  39. - `"English"` (Default)
  40. - `"Chinese"`
  41. #### permission
  42. Specifies who can access the dataset to create. You can set it only to `"me"` for now.
  43. #### chunk_method, `str`
  44. The chunking method of the dataset to create. Available options:
  45. - `"naive"`: General (default)
  46. - `"manual`: Manual
  47. - `"qa"`: Q&A
  48. - `"table"`: Table
  49. - `"paper"`: Paper
  50. - `"book"`: Book
  51. - `"laws"`: Laws
  52. - `"presentation"`: Presentation
  53. - `"picture"`: Picture
  54. - `"one"`:One
  55. - `"knowledge_graph"`: Knowledge Graph
  56. - `"email"`: Email
  57. #### parser_config
  58. The parser configuration of the dataset. A `ParserConfig` object contains the following attributes:
  59. - `chunk_token_count`: Defaults to `128`.
  60. - `layout_recognize`: Defaults to `True`.
  61. - `delimiter`: Defaults to `"\n!?。;!?"`.
  62. - `task_page_size`: Defaults to `12`.
  63. ### Returns
  64. - Success: A `dataset` object.
  65. - Failure: `Exception`
  66. ### Examples
  67. ```python
  68. from ragflow import RAGFlow
  69. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  70. dataset = rag_object.create_dataset(name="kb_1")
  71. ```
  72. ---
  73. ## Delete datasets
  74. ```python
  75. RAGFlow.delete_datasets(ids: list[str] = None)
  76. ```
  77. Deletes specified datasets or all datasets in the system.
  78. ### Parameters
  79. #### ids: `list[str]`
  80. The IDs of the datasets to delete. Defaults to `None`. If not specified, all datasets in the system will be deleted.
  81. ### Returns
  82. - Success: No value is returned.
  83. - Failure: `Exception`
  84. ### Examples
  85. ```python
  86. rag_object.delete_datasets(ids=["id_1","id_2"])
  87. ```
  88. ---
  89. ## List datasets
  90. ```python
  91. RAGFlow.list_datasets(
  92. page: int = 1,
  93. page_size: int = 1024,
  94. orderby: str = "create_time",
  95. desc: bool = True,
  96. id: str = None,
  97. name: str = None
  98. ) -> list[DataSet]
  99. ```
  100. Retrieves a list of datasets.
  101. ### Parameters
  102. #### page: `int`
  103. Specifies the page on which the datasets will be displayed. Defaults to `1`.
  104. #### page_size: `int`
  105. The number of datasets on each page. Defaults to `1024`.
  106. #### orderby: `str`
  107. The field by which datasets should be sorted. Available options:
  108. - `"create_time"` (default)
  109. - `"update_time"`
  110. #### desc: `bool`
  111. Indicates whether the retrieved datasets should be sorted in descending order. Defaults to `True`.
  112. #### id: `str`
  113. The ID of the dataset to retrieve. Defaults to `None`.
  114. #### name: `str`
  115. The name of the dataset to retrieve. Defaults to `None`.
  116. ### Returns
  117. - Success: A list of `DataSet` objects.
  118. - Failure: `Exception`.
  119. ### Examples
  120. #### List all datasets
  121. ```python
  122. for dataset in rag_object.list_datasets():
  123. print(dataset)
  124. ```
  125. #### Retrieve a dataset by ID
  126. ```python
  127. dataset = rag_object.list_datasets(id = "id_1")
  128. print(dataset[0])
  129. ```
  130. ---
  131. ## Update dataset
  132. ```python
  133. DataSet.update(update_message: dict)
  134. ```
  135. Updates configurations for the current dataset.
  136. ### Parameters
  137. #### update_message: `dict[str, str|int]`, *Required*
  138. A dictionary representing the attributes to update, with the following keys:
  139. - `"name"`: `str` The name of the dataset to update.
  140. - `"embedding_model"`: `str` The embedding model name to update.
  141. - Ensure that `"chunk_count"` is `0` before updating `"embedding_model"`.
  142. - `"chunk_method"`: `str` The chunking method for the dataset. Available options:
  143. - `"naive"`: General
  144. - `"manual`: Manual
  145. - `"qa"`: Q&A
  146. - `"table"`: Table
  147. - `"paper"`: Paper
  148. - `"book"`: Book
  149. - `"laws"`: Laws
  150. - `"presentation"`: Presentation
  151. - `"picture"`: Picture
  152. - `"one"`:One
  153. - `"knowledge_graph"`: Knowledge Graph
  154. - `"email"`: Email
  155. ### Returns
  156. - Success: No value is returned.
  157. - Failure: `Exception`
  158. ### Examples
  159. ```python
  160. from ragflow import RAGFlow
  161. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  162. dataset = rag_object.list_datasets(name="kb_name")
  163. dataset.update({"embedding_model":"BAAI/bge-zh-v1.5", "chunk_method":"manual"})
  164. ```
  165. ---
  166. :::tip API GROUPING
  167. File Management within Dataset
  168. :::
  169. ---
  170. ## Upload documents
  171. ```python
  172. DataSet.upload_documents(document_list: list[dict])
  173. ```
  174. Uploads documents to the current dataset.
  175. ### Parameters
  176. #### document_list: `list[dict]`, *Required*
  177. A list of dictionaries representing the documents to upload, each containing the following keys:
  178. - `"display_name"`: (Optional) The file name to display in the dataset.
  179. - `"blob"`: (Optional) The binary content of the file to upload.
  180. ### Returns
  181. - Success: No value is returned.
  182. - Failure: `Exception`
  183. ### Examples
  184. ```python
  185. dataset = rag_object.create_dataset(name="kb_name")
  186. dataset.upload_documents([{"display_name": "1.txt", "blob": "<BINARY_CONTENT_OF_THE_DOC>"}, {"display_name": "2.pdf", "blob": "<BINARY_CONTENT_OF_THE_DOC>"}])
  187. ```
  188. ---
  189. ## Update document
  190. ```python
  191. Document.update(update_message:dict)
  192. ```
  193. Updates configurations for the current document.
  194. ### Parameters
  195. #### update_message: `dict[str, str|dict[]]`, *Required*
  196. A dictionary representing the attributes to update, with the following keys:
  197. - `"name"`: `str` The name of the document to update.
  198. - `"parser_config"`: `dict[str, Any]` The parsing configuration for the document:
  199. - `"chunk_token_count"`: Defaults to `128`.
  200. - `"layout_recognize"`: Defaults to `True`.
  201. - `"delimiter"`: Defaults to `'\n!?。;!?'`.
  202. - `"task_page_size"`: Defaults to `12`.
  203. - `"chunk_method"`: `str` The parsing method to apply to the document.
  204. - `"naive"`: General
  205. - `"manual`: Manual
  206. - `"qa"`: Q&A
  207. - `"table"`: Table
  208. - `"paper"`: Paper
  209. - `"book"`: Book
  210. - `"laws"`: Laws
  211. - `"presentation"`: Presentation
  212. - `"picture"`: Picture
  213. - `"one"`: One
  214. - `"knowledge_graph"`: Knowledge Graph
  215. - `"email"`: Email
  216. ### Returns
  217. - Success: No value is returned.
  218. - Failure: `Exception`
  219. ### Examples
  220. ```python
  221. from ragflow import RAGFlow
  222. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  223. dataset = rag_object.list_datasets(id='id')
  224. dataset = dataset[0]
  225. doc = dataset.list_documents(id="wdfxb5t547d")
  226. doc = doc[0]
  227. doc.update([{"parser_config": {"chunk_token_count": 256}}, {"chunk_method": "manual"}])
  228. ```
  229. ---
  230. ## Download document
  231. ```python
  232. Document.download() -> bytes
  233. ```
  234. Downloads the current document.
  235. ### Returns
  236. The downloaded document in bytes.
  237. ### Examples
  238. ```python
  239. from ragflow import RAGFlow
  240. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  241. dataset = rag_object.list_datasets(id="id")
  242. dataset = dataset[0]
  243. doc = dataset.list_documents(id="wdfxb5t547d")
  244. doc = doc[0]
  245. open("~/ragflow.txt", "wb+").write(doc.download())
  246. print(doc)
  247. ```
  248. ---
  249. ## List documents
  250. ```python
  251. Dataset.list_documents(id:str =None, keywords: str=None, offset: int=0, limit:int = 1024,order_by:str = "create_time", desc: bool = True) -> list[Document]
  252. ```
  253. Retrieves a list of documents from the current dataset.
  254. ### Parameters
  255. #### id: `str`
  256. The ID of the document to retrieve. Defaults to `None`.
  257. #### keywords: `str`
  258. The keywords used to match document titles. Defaults to `None`.
  259. #### offset: `int`
  260. The starting index for the documents to retrieve. Typically used in confunction with `limit`. Defaults to `0`.
  261. #### limit: `int`
  262. The maximum number of documents to retrieve. Defaults to `1024`. A value of `-1` indicates that all documents should be returned.
  263. #### orderby: `str`
  264. The field by which documents should be sorted. Available options:
  265. - `"create_time"` (default)
  266. - `"update_time"`
  267. #### desc: `bool`
  268. Indicates whether the retrieved documents should be sorted in descending order. Defaults to `True`.
  269. ### Returns
  270. - Success: A list of `Document` objects.
  271. - Failure: `Exception`.
  272. A `Document` object contains the following attributes:
  273. - `id`: The document ID. Defaults to `""`.
  274. - `name`: The document name. Defaults to `""`.
  275. - `thumbnail`: The thumbnail image of the document. Defaults to `None`.
  276. - `knowledgebase_id`: The dataset ID associated with the document. Defaults to `None`.
  277. - `chunk_method` The chunk method name. Defaults to `""`. ?????naive??????
  278. - `parser_config`: `ParserConfig` Configuration object for the parser. Defaults to `{"pages": [[1, 1000000]]}`.
  279. - `source_type`: The source type of the document. Defaults to `"local"`.
  280. - `type`: Type or category of the document???????????. Defaults to `""`.
  281. - `created_by`: `str` The creator of the document. Defaults to `""`.
  282. - `size`: `int` The document size in bytes. Defaults to `0`.
  283. - `token_count`: `int` The number of tokens in the document. Defaults to `0`.
  284. - `chunk_count`: `int` The number of chunks in the document. Defaults to `0`.
  285. - `progress`: `float` The current processing progress as a percentage. Defaults to `0.0`.
  286. - `progress_msg`: `str` A message indicating the current progress status. Defaults to `""`.
  287. - `process_begin_at`: `datetime` The start time of document processing. Defaults to `None`.
  288. - `process_duation`: `float` Duration of the processing in seconds or minutes.??????? Defaults to `0.0`.
  289. - `run`: `str` ?????????????????? Defaults to `"0"`.
  290. - `status`: `str` ??????????????????? Defaults to `"1"`.
  291. ### Examples
  292. ```python
  293. from ragflow import RAGFlow
  294. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  295. dataset = rag_object.create_dataset(name="kb_1")
  296. filename1 = "~/ragflow.txt"
  297. blob = open(filename1 , "rb").read()
  298. dataset.upload_documents([{"name":filename1,"blob":blob}])
  299. for doc in dataset.list_documents(keywords="rag", offset=0, limit=12):
  300. print(doc)
  301. ```
  302. ---
  303. ## Delete documents
  304. ```python
  305. DataSet.delete_documents(ids: list[str] = None)
  306. ```
  307. Deletes documents by ID.
  308. ### Parameters
  309. #### ids: `list[list]`
  310. The IDs of the documents to delete. Defaults to `None`. If not specified, all documents in the dataset will be deleted.
  311. ### Returns
  312. - Success: No value is returned.
  313. - Failure: `Exception`
  314. ### Examples
  315. ```python
  316. from ragflow import RAGFlow
  317. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  318. dataset = rag_object.list_datasets(name="kb_1")
  319. dataset = dataset[0]
  320. dataset.delete_documents(ids=["id_1","id_2"])
  321. ```
  322. ---
  323. ## Parse documents
  324. ```python
  325. DataSet.async_parse_documents(document_ids:list[str]) -> None
  326. ```
  327. Parses documents in the current dataset.
  328. ### Parameters
  329. #### document_ids: `list[str]`, *Required*
  330. The IDs of the documents to parse.
  331. ### Returns
  332. - Success: No value is returned.????????????????????
  333. - Failure: `Exception`
  334. ### Examples
  335. ```python
  336. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  337. dataset = rag_object.create_dataset(name="dataset_name")
  338. documents = [
  339. {'name': 'test1.txt', 'blob': open('./test_data/test1.txt',"rb").read()},
  340. {'name': 'test2.txt', 'blob': open('./test_data/test2.txt',"rb").read()},
  341. {'name': 'test3.txt', 'blob': open('./test_data/test3.txt',"rb").read()}
  342. ]
  343. dataset.upload_documents(documents)
  344. documents = dataset.list_documents(keywords="test")
  345. ids = []
  346. for document in documents:
  347. ids.append(document.id)
  348. dataset.async_parse_documents(ids)
  349. print("Async bulk parsing initiated.")
  350. ```
  351. ---
  352. ## Stop parsing documents
  353. ```python
  354. DataSet.async_cancel_parse_documents(document_ids:list[str])-> None
  355. ```
  356. Stops parsing specified documents.
  357. ### Parameters
  358. #### document_ids: `list[str]`, *Required*
  359. The IDs of the documents for which parsing should be stopped.
  360. ### Returns
  361. - Success: No value is returned.
  362. - Failure: `Exception`
  363. ### Examples
  364. ```python
  365. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  366. dataset = rag_object.create_dataset(name="dataset_name")
  367. documents = [
  368. {'name': 'test1.txt', 'blob': open('./test_data/test1.txt',"rb").read()},
  369. {'name': 'test2.txt', 'blob': open('./test_data/test2.txt',"rb").read()},
  370. {'name': 'test3.txt', 'blob': open('./test_data/test3.txt',"rb").read()}
  371. ]
  372. dataset.upload_documents(documents)
  373. documents = dataset.list_documents(keywords="test")
  374. ids = []
  375. for document in documents:
  376. ids.append(document.id)
  377. dataset.async_parse_documents(ids)
  378. print("Async bulk parsing initiated.")
  379. dataset.async_cancel_parse_documents(ids)
  380. print("Async bulk parsing cancelled.")
  381. ```
  382. ---
  383. ## Add chunk
  384. ```python
  385. Document.add_chunk(content:str) -> Chunk ?????????????????????
  386. ```
  387. Adds a chunk to the current document.
  388. ### Parameters
  389. #### content: `str`, *Required*
  390. The text content of the chunk.
  391. #### important_keywords: `list[str]` ??????????????????????
  392. The key terms or phrases to tag with the chunk.
  393. ### Returns
  394. - Success: A `Chunk` object.
  395. - Failure: `Exception`.
  396. A `Chunk` object contains the following attributes:
  397. - `id`: `str`
  398. - `content`: `str` Content of the chunk.
  399. - `important_keywords`: `list[str]` A list of key terms or phrases to tag with the chunk.
  400. - `create_time`: `str` The time when the chunk was created (added to the document).
  401. - `create_timestamp`: `float` The timestamp representing the creation time of the chunk, expressed in seconds since January 1, 1970.
  402. - `knowledgebase_id`: `str` The ID of the associated dataset.
  403. - `document_name`: `str` The name of the associated document.
  404. - `document_id`: `str` The ID of the associated document.
  405. - `available`: `int`???? The chunk's availability status in the dataset. Value options:
  406. - `0`: Unavailable
  407. - `1`: Available
  408. ### Examples
  409. ```python
  410. from ragflow import RAGFlow
  411. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  412. dataset = rag_object.list_datasets(id="123")
  413. dtaset = dataset[0]
  414. doc = dataset.list_documents(id="wdfxb5t547d")
  415. doc = doc[0]
  416. chunk = doc.add_chunk(content="xxxxxxx")
  417. ```
  418. ---
  419. ## List chunks
  420. ```python
  421. Document.list_chunks(keywords: str = None, offset: int = 0, limit: int = -1, id : str = None) -> list[Chunk]
  422. ```
  423. Retrieves a list of chunks from the current document.
  424. ### Parameters
  425. #### keywords: `str`
  426. The keywords used to match chunk content. Defaults to `None`
  427. #### offset: `int`
  428. The starting index for the chunks to retrieve. Defaults to `1`??????
  429. #### limit
  430. The maximum number of chunks to retrieve. Default: `30`?????????
  431. #### id
  432. The ID of the chunk to retrieve. Default: `None`
  433. ### Returns
  434. - Success: A list of `Chunk` objects.
  435. - Failure: `Exception`.
  436. ### Examples
  437. ```python
  438. from ragflow import RAGFlow
  439. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  440. dataset = rag_object.list_datasets("123")
  441. dataset = dataset[0]
  442. dataset.async_parse_documents(["wdfxb5t547d"])
  443. for chunk in doc.list_chunks(keywords="rag", offset=0, limit=12):
  444. print(chunk)
  445. ```
  446. ---
  447. ## Delete chunks
  448. ```python
  449. Document.delete_chunks(chunk_ids: list[str])
  450. ```
  451. Deletes chunks by ID.
  452. ### Parameters
  453. #### chunk_ids: `list[str]`
  454. The IDs of the chunks to delete. Defaults to `None`. If not specified, all chunks of the current document will be deleted.
  455. ### Returns
  456. - Success: No value is returned.
  457. - Failure: `Exception`
  458. ### Examples
  459. ```python
  460. from ragflow import RAGFlow
  461. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  462. dataset = rag_object.list_datasets(id="123")
  463. dataset = dataset[0]
  464. doc = dataset.list_documents(id="wdfxb5t547d")
  465. doc = doc[0]
  466. chunk = doc.add_chunk(content="xxxxxxx")
  467. doc.delete_chunks(["id_1","id_2"])
  468. ```
  469. ---
  470. ## Update chunk
  471. ```python
  472. Chunk.update(update_message: dict)
  473. ```
  474. Updates content or configurations for the current chunk.
  475. ### Parameters
  476. #### update_message: `dict[str, str|list[str]|int]` *Required*
  477. A dictionary representing the attributes to update, with the following keys:
  478. - `"content"`: `str` Content of the chunk.
  479. - `"important_keywords"`: `list[str]` A list of key terms or phrases to tag with the chunk.
  480. - `"available"`: `int` The chunk's availability status in the dataset. Value options:
  481. - `0`: Unavailable
  482. - `1`: Available
  483. ### Returns
  484. - Success: No value is returned.
  485. - Failure: `Exception`
  486. ### Examples
  487. ```python
  488. from ragflow import RAGFlow
  489. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  490. dataset = rag_object.list_datasets(id="123")
  491. dataset = dataset[0]
  492. doc = dataset.list_documents(id="wdfxb5t547d")
  493. doc = doc[0]
  494. chunk = doc.add_chunk(content="xxxxxxx")
  495. chunk.update({"content":"sdfx..."})
  496. ```
  497. ---
  498. ## Retrieve chunks
  499. ```python
  500. RAGFlow.retrieve(question:str="", datasets:list[str]=None, document=list[str]=None, offset:int=1, limit: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]
  501. ```
  502. ???????
  503. ### Parameters
  504. #### question: `str` *Required*
  505. The user query or query keywords. Defaults to `""`.
  506. #### datasets: `list[str]`, *Required*?????
  507. The datasets to search from.
  508. #### document: `list[str]`
  509. The documents to search from. `None` means no limitation. Defaults to `None`.
  510. #### offset: `int`
  511. The starting index for the documents to retrieve. Defaults to `0`??????.
  512. #### limit: `int`
  513. The maximum number of chunks to retrieve. Defaults to `6`.???????????????
  514. #### Similarity_threshold: `float`
  515. The minimum similarity score. Defaults to `0.2`.
  516. #### similarity_threshold_weight: `float`
  517. 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.
  518. #### top_k: `int`
  519. The number of chunks engaged in vector cosine computaton. Defaults to `1024`.
  520. #### rerank_id: `str`
  521. The ID of the rerank model. Defaults to `None`.
  522. #### keyword: `bool`
  523. Indicates whether keyword-based matching is enabled:
  524. - `True`: Enabled.
  525. - `False`: Disabled (default).
  526. #### highlight: `bool`
  527. Specifying whether to enable highlighting of matched terms in the results (True) or not (False).
  528. ### Returns
  529. - Success: A list of `Chunk` objects representing the document chunks.
  530. - Failure: `Exception`
  531. ### Examples
  532. ```python
  533. from ragflow import RAGFlow
  534. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  535. dataset = rag_object.list_datasets(name="ragflow")
  536. dataset = dataset[0]
  537. name = 'ragflow_test.txt'
  538. path = './test_data/ragflow_test.txt'
  539. rag_object.create_document(dataset, name=name, blob=open(path, "rb").read())
  540. doc = dataset.list_documents(name=name)
  541. doc = doc[0]
  542. dataset.async_parse_documents([doc.id])
  543. for c in rag_object.retrieve(question="What's ragflow?",
  544. datasets=[dataset.id], documents=[doc.id],
  545. offset=1, limit=30, similarity_threshold=0.2,
  546. vector_similarity_weight=0.3,
  547. top_k=1024
  548. ):
  549. print(c)
  550. ```
  551. ---
  552. :::tip API GROUPING
  553. Chat Assistant Management
  554. :::
  555. ---
  556. ## Create chat assistant
  557. ```python
  558. RAGFlow.create_chat(
  559. name: str,
  560. avatar: str = "",
  561. knowledgebases: list[str] = [],
  562. llm: Chat.LLM = None,
  563. prompt: Chat.Prompt = None
  564. ) -> Chat
  565. ```
  566. Creates a chat assistant.
  567. ### Parameters
  568. The following shows the attributes of a `Chat` object:
  569. #### name: `str`, *Required*????????
  570. The name of the chat assistant. Defaults to `"assistant"`.
  571. #### avatar: `str`
  572. Base64 encoding of the avatar. Defaults to `""`.
  573. #### knowledgebases: `list[str]`
  574. The IDs of the associated datasets. Defaults to `[""]`.
  575. #### llm: `Chat.LLM`
  576. The llm of the created chat. Defaults to `None`. When the value is `None`, a dictionary with the following values will be generated as the default.
  577. An `LLM` object contains the following attributes:
  578. - `model_name`, `str`
  579. The chat model name. If it is `None`, the user's default chat model will be returned.
  580. - `temperature`, `float`
  581. Controls the randomness of the model's predictions. A lower temperature increases the model's conficence in its responses; a higher temperature increases creativity and diversity. Defaults to `0.1`.
  582. - `top_p`, `float`
  583. 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`
  584. - `presence_penalty`, `float`
  585. This discourages the model from repeating the same information by penalizing words that have already appeared in the conversation. Defaults to `0.2`.
  586. - `frequency penalty`, `float`
  587. Similar to the presence penalty, this reduces the model’s tendency to repeat the same words frequently. Defaults to `0.7`.
  588. - `max_token`, `int`
  589. This sets the maximum length of the model’s output, measured in the number of tokens (words or pieces of words). Defaults to `512`.
  590. #### prompt: `Chat.Prompt`
  591. Instructions for the LLM to follow. A `Prompt` object contains the following attributes:
  592. - `"similarity_threshold"`: `float` A similarity score to evaluate distance between two lines of text. It's weighted keywords similarity and vector cosine similarity. If the similarity between query and chunk is less than this threshold, the chunk will be filtered out. Defaults to `0.2`.
  593. - `"keywords_similarity_weight"`: `float` It's weighted keywords similarity and vector cosine similarity or rerank score (0~1). Defaults to `0.7`.
  594. - `"top_n"`: `int` Not all the chunks whose similarity score is above the 'similarity threshold' will be feed to LLMs. LLM can only see these 'Top N' chunks. Defaults to `8`.
  595. - `"variables"`: `list[dict[]]` If you use dialog APIs, the variables might help you chat with your clients with different strategies. The variables are used to fill in the 'System' part in prompt in order to give LLM a hint. The 'knowledge' is a very special variable which will be filled-in with the retrieved chunks. All the variables in 'System' should be curly bracketed. Defaults to `[{"key": "knowledge", "optional": True}]`
  596. - `"rerank_model"`: `str` If it is not specified, vector cosine similarity will be used; otherwise, reranking score will be used. Defaults to `""`.
  597. - `"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`.
  598. - `"opener"`: `str` The opening greeting for the user. Defaults to `"Hi! I am your assistant, can I help you?"`.
  599. - `"show_quote`: `bool` Indicates whether the source of text should be displayed Defaults to `True`.
  600. - `"prompt"`: `str` The prompt content. Defaults to `You are an intelligent assistant. Please summarize the content of the dataset to answer the question. Please list the data in the knowledge base and answer in detail. When all knowledge base content is irrelevant to the question, your answer must include the sentence "The answer you are looking for is not found in the knowledge base!" Answers need to consider chat history.
  601. Here is the knowledge base:
  602. {knowledge}
  603. The above is the knowledge base.`.
  604. ### Returns
  605. - Success: A `Chat` object representing the chat assistant.
  606. - Failure: `Exception`
  607. ### Examples
  608. ```python
  609. from ragflow import RAGFlow
  610. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  611. datasets = rag_object.list_datasets(name="kb_1")
  612. dataset_ids = []
  613. for dataset in datasets:
  614. dataset_ids.append(dataset.id)
  615. assistant = rag_object.create_chat("Miss R", knowledgebases=dataset_ids)
  616. ```
  617. ---
  618. ## Update chat assistant
  619. ```python
  620. Chat.update(update_message: dict)
  621. ```
  622. Updates configurations for the current chat assistant.
  623. ### Parameters
  624. #### update_message: `dict[str, str|list[str]|dict[]]`, *Required*
  625. A dictionary representing the attributes to update, with the following keys:
  626. - `"name"`: `str` The name of the chat assistant to update.
  627. - `"avatar"`: `str` Base64 encoding of the avatar. Defaults to `""`
  628. - `"knowledgebases"`: `list[str]` The datasets to update.
  629. - `"llm"`: `dict` The LLM settings:
  630. - `"model_name"`, `str` The chat model name.
  631. - `"temperature"`, `float` Controls the randomness of the model's predictions.
  632. - `"top_p"`, `float` Also known as “nucleus sampling”, this parameter sets a threshold to select a smaller set of words to sample from.
  633. - `"presence_penalty"`, `float` This discourages the model from repeating the same information by penalizing words that have appeared in the conversation.
  634. - `"frequency penalty"`, `float` Similar to presence penalty, this reduces the model’s tendency to repeat the same words.
  635. - `"max_token"`, `int` This sets the maximum length of the model’s output, measured in the number of tokens (words or pieces of words).
  636. - `"prompt"` : Instructions for the LLM to follow.
  637. - `"similarity_threshold"`: `float` A score to evaluate distance between two lines of text. It's weighted keywords similarity and vector cosine similarity. If the similarity between query and chunk is less than this threshold, the chunk will be filtered out. Defaults to `0.2`.
  638. - `"keywords_similarity_weight"`: `float` It's weighted keywords similarity and vector cosine similarity or rerank score (0~1). Defaults to `0.7`.
  639. - `"top_n"`: `int` Not all the chunks whose similarity score is above the 'similarity threshold' will be feed to LLMs. LLM can only see these 'Top N' chunks. Defaults to `8`.
  640. - `"variables"`: `list[dict[]]` If you use dialog APIs, the variables might help you chat with your clients with different strategies. The variables are used to fill in the 'System' part in prompt in order to give LLM a hint. The 'knowledge' is a very special variable which will be filled-in with the retrieved chunks. All the variables in 'System' should be curly bracketed. Defaults to `[{"key": "knowledge", "optional": True}]`
  641. - `"rerank_model"`: `str` If it is not specified, vector cosine similarity will be used; otherwise, reranking score will be used. Defaults to `""`.
  642. - `"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`.
  643. - `"opener"`: `str` The opening greeting for the user. Defaults to `"Hi! I am your assistant, can I help you?"`.
  644. - `"show_quote`: `bool` Indicates whether the source of text should be displayed Defaults to `True`.
  645. - `"prompt"`: `str` The prompt content. Defaults to `You are an intelligent assistant. Please summarize the content of the knowledge base to answer the question. Please list the data in the knowledge base and answer in detail. When all knowledge base content is irrelevant to the question, your answer must include the sentence "The answer you are looking for is not found in the knowledge base!" Answers need to consider chat history.
  646. Here is the knowledge base:
  647. {knowledge}
  648. The above is the knowledge base.`.
  649. ### Returns
  650. - Success: No value is returned.
  651. - Failure: `Exception`
  652. ### Examples
  653. ```python
  654. from ragflow import RAGFlow
  655. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  656. datasets = rag_object.list_datasets(name="kb_1")
  657. assistant = rag_object.create_chat("Miss R", knowledgebases=datasets)
  658. assistant.update({"name": "Stefan", "llm": {"temperature": 0.8}, "prompt": {"top_n": 8}})
  659. ```
  660. ---
  661. ## Delete chat assistants
  662. ```python
  663. RAGFlow.delete_chats(ids: list[str] = None)
  664. ```
  665. Deletes chat assistants by ID.
  666. ### Parameters
  667. #### ids: `list[str]`
  668. The IDs of the chat assistants to delete. Defaults to `None`. If not specified, all chat assistants in the system will be deleted.
  669. ### Returns
  670. - Success: No value is returned.
  671. - Failure: `Exception`
  672. ### Examples
  673. ```python
  674. from ragflow import RAGFlow
  675. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  676. rag_object.delete_chats(ids=["id_1","id_2"])
  677. ```
  678. ---
  679. ## List chat assistants
  680. ```python
  681. RAGFlow.list_chats(
  682. page: int = 1,
  683. page_size: int = 1024,
  684. orderby: str = "create_time",
  685. desc: bool = True,
  686. id: str = None,
  687. name: str = None
  688. ) -> list[Chat]
  689. ```
  690. Retrieves a list of chat assistants.
  691. ### Parameters
  692. #### page: `int`
  693. Specifies the page on which the chat assistants will be displayed. Defaults to `1`.
  694. #### page_size: `int`
  695. The number of chat assistants on each page. Defaults to `1024`.
  696. #### orderby: `str`
  697. The attribute by which the results are sorted. Available options:
  698. - `"create_time"` (default)
  699. - `"update_time"`
  700. #### desc: `bool`
  701. Indicates whether the retrieved chat assistants should be sorted in descending order. Defaults to `True`.
  702. #### id: `str`
  703. The ID of the chat assistant to retrieve. Defaults to `None`.
  704. #### name: `str`
  705. The name of the chat assistant to retrieve. Defaults to `None`.
  706. ### Returns
  707. - Success: A list of `Chat` objects.
  708. - Failure: `Exception`.
  709. ### Examples
  710. ```python
  711. from ragflow import RAGFlow
  712. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  713. for assistant in rag_object.list_chats():
  714. print(assistant)
  715. ```
  716. ---
  717. :::tip API GROUPING
  718. Chat Session APIs
  719. :::
  720. ---
  721. ## Create session
  722. ```python
  723. Chat.create_session(name: str = "New session") -> Session
  724. ```
  725. Creates a chat session.
  726. ### Parameters
  727. #### name: `str`
  728. The name of the chat session to create.
  729. ### Returns
  730. - Success: A `Session` object containing the following attributes:
  731. - `id`: `str` The auto-generated unique identifier of the created session.
  732. - `name`: `str` The name of the created session.
  733. - `message`: `list[Message]` The messages of the created session assistant. Default: `[{"role": "assistant", "content": "Hi! I am your assistant,can I help you?"}]`
  734. - `chat_id`: `str` The ID of the associated chat assistant.
  735. - Failure: `Exception`
  736. ### Examples
  737. ```python
  738. from ragflow import RAGFlow
  739. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  740. assistant = rag_object.list_chats(name="Miss R")
  741. assistant = assistant[0]
  742. session = assistant.create_session()
  743. ```
  744. ---
  745. ## Update session
  746. ```python
  747. Session.update(update_message: dict)
  748. ```
  749. Updates the current session name.
  750. ### Parameters
  751. #### update_message: `dict[str, Any]`, *Required*
  752. A dictionary representing the attributes to update, with only one key:
  753. - `"name"`: `str` The name of the session to update.
  754. ### Returns
  755. - Success: No value is returned.
  756. - Failure: `Exception`
  757. ### Examples
  758. ```python
  759. from ragflow import RAGFlow
  760. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  761. assistant = rag_object.list_chats(name="Miss R")
  762. assistant = assistant[0]
  763. session = assistant.create_session("session_name")
  764. session.update({"name": "updated_name"})
  765. ```
  766. ---
  767. ## List sessions
  768. ```python
  769. Chat.list_sessions(
  770. page: int = 1,
  771. page_size: int = 1024,
  772. orderby: str = "create_time",
  773. desc: bool = True,
  774. id: str = None,
  775. name: str = None
  776. ) -> list[Session]
  777. ```
  778. Lists sessions associated with the current chat assistant.
  779. ### Parameters
  780. #### page: `int`
  781. Specifies the page on which the sessions will be displayed. Defaults to `1`.
  782. #### page_size: `int`
  783. The number of sessions on each page. Defaults to `1024`.
  784. #### orderby: `str`
  785. The field by which sessions should be sorted. Available options:
  786. - `"create_time"` (default)
  787. - `"update_time"`
  788. #### desc: `bool`
  789. Indicates whether the retrieved sessions should be sorted in descending order. Defaults to `True`.
  790. #### id: `str`
  791. The ID of the chat session to retrieve. Defaults to `None`.
  792. #### name: `str`
  793. The name of the chat session to retrieve. Defaults to `None`.
  794. ### Returns
  795. - Success: A list of `Session` objects associated with the current chat assistant.
  796. - Failure: `Exception`.
  797. ### Examples
  798. ```python
  799. from ragflow import RAGFlow
  800. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  801. assistant = rag_object.list_chats(name="Miss R")
  802. assistant = assistant[0]
  803. for session in assistant.list_sessions():
  804. print(session)
  805. ```
  806. ---
  807. ## Delete sessions
  808. ```python
  809. Chat.delete_sessions(ids:list[str] = None)
  810. ```
  811. Deletes sessions by ID.
  812. ### Parameters
  813. #### ids: `list[str]`
  814. The IDs of the sessions to delete. Defaults to `None`. If not specified, all sessions associated with the current chat assistant will be deleted.
  815. ### Returns
  816. - Success: No value is returned.
  817. - Failure: `Exception`
  818. ### Examples
  819. ```python
  820. from ragflow import RAGFlow
  821. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  822. assistant = rag_object.list_chats(name="Miss R")
  823. assistant = assistant[0]
  824. assistant.delete_sessions(ids=["id_1","id_2"])
  825. ```
  826. ---
  827. ## Chat
  828. ```python
  829. Session.ask(question: str, stream: bool = False) -> Optional[Message, iter[Message]]
  830. ```
  831. Asks a question to start a conversation.
  832. ### Parameters
  833. #### question: `str` *Required*
  834. The question to start an AI chat.
  835. #### stream: `str`
  836. Indicates whether to output responses in a streaming way:
  837. - `True`: Enable streaming.
  838. - `False`: (Default) Disable streaming.
  839. ### Returns
  840. - A `Message` object containing the response to the question if `stream` is set to `False`
  841. - An iterator containing multiple `message` objects (`iter[Message]`) if `stream` is set to `True`
  842. The following shows the attributes of a `Message` object:
  843. #### id: `str`
  844. The auto-generated message ID.
  845. #### content: `str`
  846. The content of the message. Defaults to `"Hi! I am your assistant, can I help you?"`.
  847. #### reference: `list[Chunk]`
  848. A list of `Chunk` objects representing references to the message, each containing the following attributes:
  849. - `id` `str`
  850. The chunk ID.
  851. - `content` `str`
  852. The content of the chunk.
  853. - `image_id` `str`
  854. The ID of the snapshot of the chunk.
  855. - `document_id` `str`
  856. The ID of the referenced document.
  857. - `document_name` `str`
  858. The name of the referenced document.
  859. - `position` `list[str]`
  860. The location information of the chunk within the referenced document.
  861. - `knowledgebase_id` `str`
  862. The ID of the dataset to which the referenced document belongs.
  863. - `similarity` `float`
  864. A composite similarity score of the chunk ranging from `0` to `1`, with a higher value indicating greater similarity.
  865. - `vector_similarity` `float`
  866. A vector similarity score of the chunk ranging from `0` to `1`, with a higher value indicating greater similarity between vector embeddings.
  867. - `term_similarity` `float`
  868. A keyword similarity score of the chunk ranging from `0` to `1`, with a higher value indicating greater similarity between keywords.
  869. ### Examples
  870. ```python
  871. from ragflow import RAGFlow
  872. rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  873. assistant = rag_object.list_chats(name="Miss R")
  874. assistant = assistant[0]
  875. session = assistant.create_session()
  876. print("\n==================== Miss R =====================\n")
  877. print(assistant.get_prologue())
  878. while True:
  879. question = input("\n==================== User =====================\n> ")
  880. print("\n==================== Miss R =====================\n")
  881. cont = ""
  882. for ans in session.ask(question, stream=True):
  883. print(answer.content[len(cont):], end='', flush=True)
  884. cont = answer.content
  885. ```