Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

python_api_reference.md 31KB

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