Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  1. # DRAFT Python API Reference
  2. **THE API REFERENCES BELOW ARE STILL UNDER DEVELOPMENT.**
  3. :::tip NOTE
  4. Knowledgebase APIs
  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`
  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. ds = rag.list_datasets(name="kb_1")
  154. ds.update({"embedding_model":"BAAI/bge-zh-v1.5", "parse_method":"manual"})
  155. ```
  156. ---
  157. :::tip API GROUPING
  158. File management inside knowledge base
  159. :::
  160. ## Upload document
  161. ```python
  162. RAGFLOW.upload_document(ds:DataSet, name:str, blob:bytes)-> bool
  163. ```
  164. ### Parameters
  165. #### name
  166. #### blob
  167. ### Returns
  168. ### Examples
  169. ---
  170. ## Retrieve document
  171. ```python
  172. RAGFlow.get_document(id:str=None,name:str=None) -> Document
  173. ```
  174. ### Parameters
  175. #### id: `str`, *Required*
  176. ID of the document to retrieve.
  177. #### name: `str`
  178. Name or title of the document.
  179. ### Returns
  180. A document object containing the following attributes:
  181. #### id: `str`
  182. Id of the retrieved document. Defaults to `""`.
  183. #### thumbnail: `str`
  184. Thumbnail image of the retrieved document. Defaults to `""`.
  185. #### knowledgebase_id: `str`
  186. Knowledge base ID related to the document. Defaults to `""`.
  187. #### parser_method: `str`
  188. Method used to parse the document. Defaults to `""`.
  189. #### parser_config: `ParserConfig`
  190. Configuration object for the parser. Defaults to `None`.
  191. #### source_type: `str`
  192. Source type of the document. Defaults to `""`.
  193. #### type: `str`
  194. Type or category of the document. Defaults to `""`.
  195. #### created_by: `str`
  196. Creator of the document. Defaults to `""`.
  197. #### name: `str`
  198. string
  199. ''
  200. Name or title of the document. Defaults to `""`.
  201. #### size: `int`
  202. Size of the document in bytes or some other unit. Defaults to `0`.
  203. #### token_count: `int`
  204. Number of tokens in the document. Defaults to `""`.
  205. #### chunk_count: `int`
  206. Number of chunks the document is split into. Defaults to `0`.
  207. #### progress: `float`
  208. Current processing progress as a percentage. Defaults to `0.0`.
  209. #### progress_msg: `str`
  210. Message indicating current progress status. Defaults to `""`.
  211. #### process_begin_at: `datetime`
  212. Start time of the document processing. Defaults to `None`.
  213. #### process_duation: `float`
  214. Duration of the processing in seconds or minutes. Defaults to `0.0`.
  215. ### Examples
  216. ```python
  217. from ragflow import RAGFlow
  218. rag = RAGFlow(api_key="xxxxxx", base_url="http://xxx.xx.xx.xxx:9380")
  219. doc = rag.get_document(id="wdfxb5t547d",name='testdocument.txt')
  220. print(doc)
  221. ```
  222. ---
  223. ## Save document settings
  224. ```python
  225. Document.save() -> bool
  226. ```
  227. ### Returns
  228. bool
  229. ### Examples
  230. ```python
  231. from ragflow import RAGFlow
  232. rag = RAGFlow(api_key="xxxxxx", base_url="http://xxx.xx.xx.xxx:9380")
  233. doc = rag.get_document(id="wdfxb5t547d")
  234. doc.parser_method= "manual"
  235. doc.save()
  236. ```
  237. ---
  238. ## Download document
  239. ```python
  240. Document.download() -> bytes
  241. ```
  242. ### Returns
  243. bytes of the document.
  244. ### Examples
  245. ```python
  246. from ragflow import RAGFlow
  247. rag = RAGFlow(api_key="xxxxxx", base_url="http://xxx.xx.xx.xxx:9380")
  248. doc = rag.get_document(id="wdfxb5t547d")
  249. open("~/ragflow.txt", "w+").write(doc.download())
  250. print(doc)
  251. ```
  252. ---
  253. ## List documents
  254. ```python
  255. Dataset.list_docs(keywords: str=None, offset: int=0, limit:int = -1) -> List[Document]
  256. ```
  257. ### Parameters
  258. #### keywords: `str`
  259. List documents whose name has the given keywords. Defaults to `None`.
  260. #### offset: `int`
  261. The beginning number of records for paging. Defaults to `0`.
  262. #### limit: `int`
  263. Records number to return, -1 means all of them. Records number to return, -1 means all of them.
  264. ### Returns
  265. List[Document]
  266. ### Examples
  267. ```python
  268. from ragflow import RAGFlow
  269. rag = RAGFlow(api_key="xxxxxx", base_url="http://xxx.xx.xx.xxx:9380")
  270. ds = rag.create_dataset(name="kb_1")
  271. filename1 = "~/ragflow.txt"
  272. rag.create_document(ds, name=filename1 , blob=open(filename1 , "rb").read())
  273. filename2 = "~/infinity.txt"
  274. rag.create_document(ds, name=filename2 , blob=open(filename2 , "rb").read())
  275. for d in ds.list_docs(keywords="rag", offset=0, limit=12):
  276. print(d)
  277. ```
  278. ---
  279. ## Delete documents
  280. ```python
  281. Document.delete() -> bool
  282. ```
  283. ### Returns
  284. bool
  285. description: delete success or not
  286. ### Examples
  287. ```python
  288. from ragflow import RAGFlow
  289. rag = RAGFlow(api_key="xxxxxx", base_url="http://xxx.xx.xx.xxx:9380")
  290. ds = rag.create_dataset(name="kb_1")
  291. filename1 = "~/ragflow.txt"
  292. rag.create_document(ds, name=filename1 , blob=open(filename1 , "rb").read())
  293. filename2 = "~/infinity.txt"
  294. rag.create_document(ds, name=filename2 , blob=open(filename2 , "rb").read())
  295. for d in ds.list_docs(keywords="rag", offset=0, limit=12):
  296. d.delete()
  297. ```
  298. ---
  299. ## Parse document
  300. ```python
  301. Document.async_parse() -> None
  302. RAGFLOW.async_parse_documents() -> None
  303. ```
  304. ### Parameters
  305. ????????????????????????????????????????????????????
  306. ### Returns
  307. ????????????????????????????????????????????????????
  308. ### Examples
  309. ```python
  310. #document parse and cancel
  311. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  312. ds = rag.create_dataset(name="dataset_name")
  313. name3 = 'ai.pdf'
  314. path = 'test_data/ai.pdf'
  315. rag.create_document(ds, name=name3, blob=open(path, "rb").read())
  316. doc = rag.get_document(name="ai.pdf")
  317. doc.async_parse()
  318. print("Async parsing initiated")
  319. ```
  320. ---
  321. ## Cancel document parsing
  322. ```python
  323. rag.async_cancel_parse_documents(ids)
  324. RAGFLOW.async_cancel_parse_documents()-> None
  325. ```
  326. ### Parameters
  327. #### ids, `list[]`
  328. ### Returns
  329. ?????????????????????????????????????????????????
  330. ### Examples
  331. ```python
  332. #documents parse and cancel
  333. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  334. ds = rag.create_dataset(name="God5")
  335. documents = [
  336. {'name': 'test1.txt', 'path': 'test_data/test1.txt'},
  337. {'name': 'test2.txt', 'path': 'test_data/test2.txt'},
  338. {'name': 'test3.txt', 'path': 'test_data/test3.txt'}
  339. ]
  340. # Create documents in bulk
  341. for doc_info in documents:
  342. with open(doc_info['path'], "rb") as file:
  343. created_doc = rag.create_document(ds, name=doc_info['name'], blob=file.read())
  344. docs = [rag.get_document(name=doc_info['name']) for doc_info in documents]
  345. ids = [doc.id for doc in docs]
  346. rag.async_parse_documents(ids)
  347. print("Async bulk parsing initiated")
  348. for doc in docs:
  349. for progress, msg in doc.join(interval=5, timeout=10):
  350. print(f"{doc.name}: Progress: {progress}, Message: {msg}")
  351. cancel_result = rag.async_cancel_parse_documents(ids)
  352. print("Async bulk parsing cancelled")
  353. ```
  354. ---
  355. ## Join document
  356. ??????????????????
  357. ```python
  358. Document.join(interval=15, timeout=3600) -> iteral[Tuple[float, str]]
  359. ```
  360. ### Parameters
  361. #### interval: `int`
  362. Time interval in seconds for progress report. Defaults to `15`.
  363. #### timeout: `int`
  364. Timeout in seconds. Defaults to `3600`.
  365. ### Returns
  366. iteral[Tuple[float, str]]
  367. ## Add chunk
  368. ```python
  369. Document.add_chunk(content:str) -> Chunk
  370. ```
  371. ### Parameters
  372. #### content: `str`, *Required*
  373. ### Returns
  374. chunk
  375. ### Examples
  376. ```python
  377. from ragflow import RAGFlow
  378. rag = RAGFlow(api_key="xxxxxx", base_url="http://xxx.xx.xx.xxx:9380")
  379. doc = rag.get_document(id="wdfxb5t547d")
  380. chunk = doc.add_chunk(content="xxxxxxx")
  381. ```
  382. ---
  383. ## Delete chunk
  384. ```python
  385. Chunk.delete() -> bool
  386. ```
  387. ### Returns
  388. bool
  389. ### Examples
  390. ```python
  391. from ragflow import RAGFlow
  392. rag = RAGFlow(api_key="xxxxxx", base_url="http://xxx.xx.xx.xxx:9380")
  393. doc = rag.get_document(id="wdfxb5t547d")
  394. chunk = doc.add_chunk(content="xxxxxxx")
  395. chunk.delete()
  396. ```
  397. ---
  398. ## Save chunk contents
  399. ```python
  400. Chunk.save() -> bool
  401. ```
  402. ### Returns
  403. bool
  404. ### Examples
  405. ```python
  406. from ragflow import RAGFlow
  407. rag = RAGFlow(api_key="xxxxxx", base_url="http://xxx.xx.xx.xxx:9380")
  408. doc = rag.get_document(id="wdfxb5t547d")
  409. chunk = doc.add_chunk(content="xxxxxxx")
  410. chunk.content = "sdfx"
  411. chunk.save()
  412. ```
  413. ---
  414. ## Retrieval
  415. ```python
  416. RAGFlow.retrieval(question:str, datasets:List[Dataset], document=List[Document]=None, offset:int=0, limit:int=6, similarity_threshold:float=0.1, vector_similarity_weight:float=0.3, top_k:int=1024) -> List[Chunk]
  417. ```
  418. ### Parameters
  419. #### question: `str`, *Required*
  420. The user query or query keywords. Defaults to `""`.
  421. #### datasets: `List[Dataset]`, *Required*
  422. The scope of datasets.
  423. #### document: `List[Document]`
  424. The scope of document. `None` means no limitation. Defaults to `None`.
  425. #### offset: `int`
  426. The beginning point of retrieved records. Defaults to `0`.
  427. #### limit: `int`
  428. The maximum number of records needed to return. Defaults to `6`.
  429. #### Similarity_threshold: `float`
  430. The minimum similarity score. Defaults to `0.2`.
  431. #### similarity_threshold_weight: `float`
  432. The weight of vector cosine similarity, 1 - x is the term similarity weight. Defaults to `0.3`.
  433. #### top_k: `int`
  434. Number of records engaged in vector cosine computaton. Defaults to `1024`.
  435. ### Returns
  436. List[Chunk]
  437. ### Examples
  438. ```python
  439. from ragflow import RAGFlow
  440. rag = RAGFlow(api_key="xxxxxx", base_url="http://xxx.xx.xx.xxx:9380")
  441. ds = rag.get_dataset(name="ragflow")
  442. name = 'ragflow_test.txt'
  443. path = 'test_data/ragflow_test.txt'
  444. rag.create_document(ds, name=name, blob=open(path, "rb").read())
  445. doc = rag.get_document(name=name)
  446. doc.async_parse()
  447. # Wait for parsing to complete
  448. for progress, msg in doc.join(interval=5, timeout=30):
  449. print(progress, msg)
  450. for c in rag.retrieval(question="What's ragflow?",
  451. datasets=[ds], documents=[doc],
  452. offset=0, limit=6, similarity_threshold=0.1,
  453. vector_similarity_weight=0.3,
  454. top_k=1024
  455. ):
  456. print(c)
  457. ```
  458. ---
  459. :::tip API GROUPING
  460. Chat APIs
  461. :::
  462. ## Create chat
  463. Creates a chat assistant.
  464. ```python
  465. RAGFlow.create_chat(
  466. name: str = "assistant",
  467. avatar: str = "path",
  468. knowledgebases: List[DataSet] = ["kb1"],
  469. llm: Chat.LLM = None,
  470. prompt: Chat.Prompt = None
  471. ) -> Chat
  472. ```
  473. ### Returns
  474. - Success: A `Chat` object representing the chat assistant.
  475. - Failure: `Exception`
  476. #### name: `str`
  477. The name of the chat assistant. Defaults to `"assistant"`.
  478. #### avatar: `str`
  479. Base64 encoding of the avatar. Defaults to `""`.
  480. #### knowledgebases: `list[str]`
  481. The associated knowledge bases. Defaults to `["kb1"]`.
  482. #### llm: `LLM`
  483. 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. This parameter controls the randomness of predictions by the model. A lower temperature makes the model more confident in its responses, while a higher temperature makes it more creative and diverse. 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: `str`
  497. Instructions for LLM's responses, including character design, answer length, and language. Defaults to:
  498. ```
  499. 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.
  500. Here is the knowledge base:
  501. {knowledge}
  502. The above is the knowledge base.
  503. ```
  504. ### Examples
  505. ```python
  506. from ragflow import RAGFlow
  507. rag = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  508. knowledge_base = rag.list_datasets(name="kb_1")
  509. assistant = rag.create_chat("Miss R", knowledgebases=knowledge_base)
  510. ```
  511. ---
  512. ## Update chat
  513. Updates the current chat assistant.
  514. ```python
  515. Chat.update(update_message: dict)
  516. ```
  517. ### Parameters
  518. #### update_message: `dict[str, Any]`, *Required*
  519. - `"name"`: `str` The name of the chat assistant to update.
  520. - `"avatar"`: `str` Base64 encoding of the avatar. Defaults to `""`
  521. - `"knowledgebases"`: `list[str]` Knowledge bases to update.
  522. - `"llm"`: `dict` llm settings
  523. - `"model_name"`, `str` The chat model name.
  524. - `"temperature"`, `float` This parameter controls the randomness of predictions by the model.
  525. - `"top_p"`, `float` Also known as “nucleus sampling”, this parameter sets a threshold to select a smaller set of words to sample from.
  526. - `"presence_penalty"`, `float` This discourages the model from repeating the same information by penalizing words that have already appeared in the conversation.
  527. - `"frequency penalty"`, `float` Similar to the presence penalty, this reduces the model’s tendency to repeat the same words frequently.
  528. - `"max_token"`, `int` This sets the maximum length of the model’s output, measured in the number of tokens (words or pieces of words).
  529. - `"prompt"` : Instructions for LLM's responses, including character design, answer length, and language.
  530. ### Returns
  531. - Success: No value is returned.
  532. - Failure: `Exception`
  533. ### Examples
  534. ```python
  535. from ragflow import RAGFlow
  536. rag = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  537. knowledge_base = rag.list_datasets(name="kb_1")
  538. assistant = rag.create_chat("Miss R", knowledgebases=knowledge_base)
  539. assistant.update({"llm": {"temperature":0.8}})
  540. ```
  541. ---
  542. ## Delete chats
  543. Deletes specified chat assistants.
  544. ```python
  545. RAGFlow.delete_chats(ids: List[str] = None)
  546. ```
  547. ### Parameters
  548. #### ids
  549. IDs of the chat assistants to delete.
  550. ### Returns
  551. - Success: No value is returned.
  552. - Failure: `Exception`
  553. ### Examples
  554. ```python
  555. from ragflow import RAGFlow
  556. rag = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  557. rag.delete_chats(ids=["id_1","id_2"])
  558. ```
  559. ---
  560. ## List chats
  561. ```python
  562. RAGFlow.list_chats(
  563. page: int = 1,
  564. page_size: int = 1024,
  565. orderby: str = "create_time",
  566. desc: bool = True,
  567. id: str = None,
  568. name: str = None
  569. ) -> List[Chat]
  570. ```
  571. ### Parameters
  572. #### page
  573. The current page number to retrieve from the paginated results. Defaults to `1`.
  574. #### page_size
  575. The number of records on each page. Defaults to `1024`.
  576. #### order_by
  577. The attribute by which the results are sorted. Defaults to `"create_time"`.
  578. #### desc
  579. Indicates whether to sort the results in descending order. Defaults to `True`.
  580. #### id: `string`
  581. The ID of the chat to be retrieved. Defaults to `None`.
  582. #### name: `string`
  583. The name of the chat to be retrieved. Defaults to `None`.
  584. ### Returns
  585. - Success: A list of `Chat` objects representing the retrieved knowledge bases.
  586. - Failure: `Exception`.
  587. ### Examples
  588. ```python
  589. from ragflow import RAGFlow
  590. rag = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
  591. for assistant in rag.list_chats():
  592. print(assistant)
  593. ```
  594. ---
  595. :::tip API GROUPING
  596. Chat-session APIs
  597. :::
  598. ## Create session
  599. ```python
  600. Chat.create_session(name: str = "New session") -> Session
  601. ```
  602. ### Returns
  603. A `session` object.
  604. #### id: `str`
  605. The id of the created session is used to identify different sessions.
  606. - id can not be provided in creating
  607. #### name: `str`
  608. The name of the created session. Defaults to `"New session"`.
  609. #### messages: `List[Message]`
  610. The messages of the created session.
  611. - messages cannot be provided.
  612. Defaults:
  613. ??????????????????????????????????????????????????????????????????????????????????????????????
  614. ```
  615. [{"role": "assistant", "content": "Hi! I am your assistant,can I help you?"}]
  616. ```
  617. #### chat_id: `str`
  618. The id of associated chat
  619. - `chat_id` can't be changed
  620. ### Examples
  621. ```python
  622. from ragflow import RAGFlow
  623. rag = RAGFlow(api_key="xxxxxx", base_url="http://xxx.xx.xx.xxx:9380")
  624. assi = rag.list_chats(name="Miss R")
  625. assi = assi[0]
  626. sess = assi.create_session()
  627. ```
  628. ## Update session
  629. ```python
  630. Session.update(update_message:dict)
  631. ```
  632. ### Returns
  633. no return
  634. ### Examples
  635. ```python
  636. from ragflow import RAGFlow
  637. rag = RAGFlow(api_key="xxxxxx", base_url="http://xxx.xx.xx.xxx:9380")
  638. assi = rag.list_chats(name="Miss R")
  639. assi = assi[0]
  640. sess = assi.create_session("new_session")
  641. sess.update({"name": "Updated session"...})
  642. ```
  643. ---
  644. ## Chat
  645. ```python
  646. Session.ask(question: str, stream: bool = False) -> Optional[Message, iter[Message]]
  647. ```
  648. ### Parameters
  649. #### question: `str`, *Required*
  650. The question to start an AI chat. Defaults to `None`. ???????????????????
  651. #### stream: `bool`
  652. The approach of streaming text generation. When stream is True, it outputs results in a streaming fashion; otherwise, it outputs the complete result after the model has finished generating.
  653. ### Returns
  654. [Message, iter[Message]]
  655. #### id: `str`
  656. The id of the message. `id` is automatically generated. Defaults to `None`. ???????????????????
  657. #### content: `str`
  658. The content of the message. Defaults to `"Hi! I am your assistant, can I help you?"`.
  659. #### reference: `List[Chunk]`
  660. The auto-generated reference of the message. Each `chunk` object includes the following attributes:
  661. - **id**: `str`
  662. The id of the chunk. ?????????????????
  663. - **content**: `str`
  664. The content of the chunk. Defaults to `None`. ?????????????????????
  665. - **document_id**: `str`
  666. The ID of the document being referenced. Defaults to `""`.
  667. - **document_name**: `str`
  668. The name of the referenced document being referenced. Defaults to `""`.
  669. - **knowledgebase_id**: `str`
  670. The id of the knowledge base to which the relevant document belongs. Defaults to `""`.
  671. - **image_id**: `str`
  672. The id of the image related to the chunk. Defaults to `""`.
  673. - **similarity**: `float`
  674. A general similarity score, usually a composite score derived from various similarity measures . This score represents the degree of similarity between two objects. The value ranges between 0 and 1, where a value closer to 1 indicates higher similarity. Defaults to `None`. ????????????????????????????????????
  675. - **vector_similarity**: `float`
  676. A similarity score based on vector representations. This score is obtained by converting texts, words, or objects into vectors and then calculating the cosine similarity or other distance measures between these vectors to determine the similarity in vector space. A higher value indicates greater similarity in the vector space. Defaults to `None`. ?????????????????????????????????
  677. - **term_similarity**: `float`
  678. The similarity score based on terms or keywords. This score is calculated by comparing the similarity of key terms between texts or datasets, typically measuring how similar two words or phrases are in meaning or context. A higher value indicates a stronger similarity between terms. Defaults to `None`. ???????????????????
  679. - **position**: `List[string]`
  680. Indicates the position or index of keywords or specific terms within the text. An array is typically used to mark the location of keywords or specific elements, facilitating precise operations or analysis of the text. Defaults to `None`. ??????????????
  681. ### Examples
  682. ```python
  683. from ragflow import RAGFlow
  684. rag = RAGFlow(api_key="xxxxxx", base_url="http://xxx.xx.xx.xxx:9380")
  685. assi = rag.list_chats(name="Miss R")
  686. assi = assi[0]
  687. sess = assi.create_session()
  688. print("\n==================== Miss R =====================\n")
  689. print(assi.get_prologue())
  690. while True:
  691. question = input("\n==================== User =====================\n> ")
  692. print("\n==================== Miss R =====================\n")
  693. cont = ""
  694. for ans in sess.ask(question, stream=True):
  695. print(ans.content[len(cont):], end='', flush=True)
  696. cont = ans.content
  697. ```
  698. ---
  699. ## List sessions
  700. ```python
  701. Chat.list_sessions(
  702. page: int = 1,
  703. page_size: int = 1024,
  704. orderby: str = "create_time",
  705. desc: bool = True,
  706. id: str = None,
  707. name: str = None
  708. ) -> List[Session]
  709. ```
  710. ### Returns
  711. List[Session]
  712. description: the List contains information about multiple assistant object, with each dictionary containing information about one assistant.
  713. ### Examples
  714. ```python
  715. from ragflow import RAGFlow
  716. rag = RAGFlow(api_key="xxxxxx", base_url="http://xxx.xx.xx.xxx:9380")
  717. assi = rag.list_chats(name="Miss R")
  718. assi = assi[0]
  719. for sess in assi.list_sessions():
  720. print(sess)
  721. ```
  722. ### Parameters
  723. #### page: `int`
  724. The current page number to retrieve from the paginated data. This parameter determines which set of records will be fetched.
  725. - `1`
  726. #### page_size: `int`
  727. The number of records to retrieve per page. This controls how many records will be included in each page.
  728. - `1024`
  729. #### orderby: `string`
  730. The field by which the records should be sorted. This specifies the attribute or column used to order the results.
  731. - `"create_time"`
  732. #### desc: `bool`
  733. A boolean flag indicating whether the sorting should be in descending order.
  734. - `True`
  735. #### id: `string`
  736. The ID of the chat to be retrieved.
  737. - `None`
  738. #### name: `string`
  739. The name of the chat to be retrieved.
  740. - `None`
  741. ---
  742. ## Delete session
  743. ```python
  744. Chat.delete_sessions(ids:List[str] = None)
  745. ```
  746. ### Returns
  747. no return
  748. ### Examples
  749. ```python
  750. from ragflow import RAGFlow
  751. rag = RAGFlow(api_key="xxxxxx", base_url="http://xxx.xx.xx.xxx:9380")
  752. assi = rag.list_chats(name="Miss R")
  753. assi = assi[0]
  754. assi.delete_sessions(ids=["id_1","id_2"])
  755. ```
  756. ### Parameters
  757. #### ids: `List[string]`
  758. IDs of the sessions to be deleted.
  759. - `None`