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

python_api_reference.md 38KB

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