You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

session.py 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import re
  17. import json
  18. from api.db import LLMType
  19. from flask import request, Response
  20. from api.db.services.conversation_service import ConversationService, iframe_completion
  21. from api.db.services.conversation_service import completion as rag_completion
  22. from api.db.services.canvas_service import completion as agent_completion
  23. from api.db.services.dialog_service import ask
  24. from agent.canvas import Canvas
  25. from api.db import StatusEnum
  26. from api.db.db_models import APIToken
  27. from api.db.services.api_service import API4ConversationService
  28. from api.db.services.canvas_service import UserCanvasService
  29. from api.db.services.dialog_service import DialogService
  30. from api.db.services.knowledgebase_service import KnowledgebaseService
  31. from api.utils import get_uuid
  32. from api.utils.api_utils import get_error_data_result
  33. from api.utils.api_utils import get_result, token_required
  34. from api.db.services.llm_service import LLMBundle
  35. @manager.route('/chats/<chat_id>/sessions', methods=['POST']) # noqa: F821
  36. @token_required
  37. def create(tenant_id, chat_id):
  38. req = request.json
  39. req["dialog_id"] = chat_id
  40. dia = DialogService.query(tenant_id=tenant_id, id=req["dialog_id"], status=StatusEnum.VALID.value)
  41. if not dia:
  42. return get_error_data_result(message="You do not own the assistant.")
  43. conv = {
  44. "id": get_uuid(),
  45. "dialog_id": req["dialog_id"],
  46. "name": req.get("name", "New session"),
  47. "message": [{"role": "assistant", "content": dia[0].prompt_config.get("prologue")}]
  48. }
  49. if not conv.get("name"):
  50. return get_error_data_result(message="`name` can not be empty.")
  51. ConversationService.save(**conv)
  52. e, conv = ConversationService.get_by_id(conv["id"])
  53. if not e:
  54. return get_error_data_result(message="Fail to create a session!")
  55. conv = conv.to_dict()
  56. conv['messages'] = conv.pop("message")
  57. conv["chat_id"] = conv.pop("dialog_id")
  58. del conv["reference"]
  59. return get_result(data=conv)
  60. @manager.route('/agents/<agent_id>/sessions', methods=['POST']) # noqa: F821
  61. @token_required
  62. def create_agent_session(tenant_id, agent_id):
  63. e, cvs = UserCanvasService.get_by_id(agent_id)
  64. if not e:
  65. return get_error_data_result("Agent not found.")
  66. if not isinstance(cvs.dsl, str):
  67. cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False)
  68. canvas = Canvas(cvs.dsl, tenant_id)
  69. conv = {
  70. "id": get_uuid(),
  71. "dialog_id": cvs.id,
  72. "user_id": tenant_id,
  73. "message": [{"role": "assistant", "content": canvas.get_prologue()}],
  74. "source": "agent",
  75. "dsl": json.loads(cvs.dsl)
  76. }
  77. API4ConversationService.save(**conv)
  78. conv["agent_id"] = conv.pop("dialog_id")
  79. return get_result(data=conv)
  80. @manager.route('/chats/<chat_id>/sessions/<session_id>', methods=['PUT']) # noqa: F821
  81. @token_required
  82. def update(tenant_id, chat_id, session_id):
  83. req = request.json
  84. req["dialog_id"] = chat_id
  85. conv_id = session_id
  86. conv = ConversationService.query(id=conv_id, dialog_id=chat_id)
  87. if not conv:
  88. return get_error_data_result(message="Session does not exist")
  89. if not DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
  90. return get_error_data_result(message="You do not own the session")
  91. if "message" in req or "messages" in req:
  92. return get_error_data_result(message="`message` can not be change")
  93. if "reference" in req:
  94. return get_error_data_result(message="`reference` can not be change")
  95. if "name" in req and not req.get("name"):
  96. return get_error_data_result(message="`name` can not be empty.")
  97. if not ConversationService.update_by_id(conv_id, req):
  98. return get_error_data_result(message="Session updates error")
  99. return get_result()
  100. @manager.route('/chats/<chat_id>/completions', methods=['POST']) # noqa: F821
  101. @token_required
  102. def chat_completion(tenant_id, chat_id):
  103. req = request.json
  104. if req.get("stream", True):
  105. resp = Response(rag_completion(tenant_id, chat_id, **req), mimetype="text/event-stream")
  106. resp.headers.add_header("Cache-control", "no-cache")
  107. resp.headers.add_header("Connection", "keep-alive")
  108. resp.headers.add_header("X-Accel-Buffering", "no")
  109. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  110. return resp
  111. else:
  112. answer = None
  113. for ans in rag_completion(tenant_id, chat_id, **req):
  114. answer = ans
  115. break
  116. return get_result(data=answer)
  117. @manager.route('/agents/<agent_id>/completions', methods=['POST']) # noqa: F821
  118. @token_required
  119. def agent_completions(tenant_id, agent_id):
  120. req = request.json
  121. if req.get("stream", True):
  122. resp = Response(agent_completion(tenant_id, agent_id, **req), mimetype="text/event-stream")
  123. resp.headers.add_header("Cache-control", "no-cache")
  124. resp.headers.add_header("Connection", "keep-alive")
  125. resp.headers.add_header("X-Accel-Buffering", "no")
  126. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  127. return resp
  128. for answer in agent_completion(tenant_id, agent_id, **req):
  129. return get_result(data=answer)
  130. @manager.route('/chats/<chat_id>/sessions', methods=['GET']) # noqa: F821
  131. @token_required
  132. def list_session(tenant_id, chat_id):
  133. if not DialogService.query(tenant_id=tenant_id, id=chat_id, status=StatusEnum.VALID.value):
  134. return get_error_data_result(message=f"You don't own the assistant {chat_id}.")
  135. id = request.args.get("id")
  136. name = request.args.get("name")
  137. page_number = int(request.args.get("page", 1))
  138. items_per_page = int(request.args.get("page_size", 30))
  139. orderby = request.args.get("orderby", "create_time")
  140. if request.args.get("desc") == "False" or request.args.get("desc") == "false":
  141. desc = False
  142. else:
  143. desc = True
  144. convs = ConversationService.get_list(chat_id, page_number, items_per_page, orderby, desc, id, name)
  145. if not convs:
  146. return get_result(data=[])
  147. for conv in convs:
  148. conv['messages'] = conv.pop("message")
  149. infos = conv["messages"]
  150. for info in infos:
  151. if "prompt" in info:
  152. info.pop("prompt")
  153. conv["chat_id"] = conv.pop("dialog_id")
  154. if conv["reference"]:
  155. messages = conv["messages"]
  156. message_num = 0
  157. chunk_num = 0
  158. while message_num < len(messages):
  159. if message_num != 0 and messages[message_num]["role"] != "user":
  160. chunk_list = []
  161. if "chunks" in conv["reference"][chunk_num]:
  162. chunks = conv["reference"][chunk_num]["chunks"]
  163. for chunk in chunks:
  164. new_chunk = {
  165. "id": chunk["chunk_id"],
  166. "content": chunk["content_with_weight"],
  167. "document_id": chunk["doc_id"],
  168. "document_name": chunk["docnm_kwd"],
  169. "dataset_id": chunk["kb_id"],
  170. "image_id": chunk.get("image_id", ""),
  171. "similarity": chunk["similarity"],
  172. "vector_similarity": chunk["vector_similarity"],
  173. "term_similarity": chunk["term_similarity"],
  174. "positions": chunk["positions"],
  175. }
  176. chunk_list.append(new_chunk)
  177. chunk_num += 1
  178. messages[message_num]["reference"] = chunk_list
  179. message_num += 1
  180. del conv["reference"]
  181. return get_result(data=convs)
  182. @manager.route('/agents/<agent_id>/sessions', methods=['GET']) # noqa: F821
  183. @token_required
  184. def list_agent_session(tenant_id, agent_id):
  185. if not UserCanvasService.query(user_id=tenant_id, id=agent_id):
  186. return get_error_data_result(message=f"You don't own the agent {agent_id}.")
  187. id = request.args.get("id")
  188. if not API4ConversationService.query(id=id, user_id=tenant_id):
  189. return get_error_data_result(f"You don't own the session {id}")
  190. page_number = int(request.args.get("page", 1))
  191. items_per_page = int(request.args.get("page_size", 30))
  192. orderby = request.args.get("orderby", "update_time")
  193. if request.args.get("desc") == "False" or request.args.get("desc") == "false":
  194. desc = False
  195. else:
  196. desc = True
  197. convs = API4ConversationService.get_list(agent_id, tenant_id, page_number, items_per_page, orderby, desc, id)
  198. if not convs:
  199. return get_result(data=[])
  200. for conv in convs:
  201. conv['messages'] = conv.pop("message")
  202. infos = conv["messages"]
  203. for info in infos:
  204. if "prompt" in info:
  205. info.pop("prompt")
  206. conv["agent_id"] = conv.pop("dialog_id")
  207. if conv["reference"]:
  208. messages = conv["messages"]
  209. message_num = 0
  210. chunk_num = 0
  211. while message_num < len(messages):
  212. if message_num != 0 and messages[message_num]["role"] != "user":
  213. chunk_list = []
  214. if "chunks" in conv["reference"][chunk_num]:
  215. chunks = conv["reference"][chunk_num]["chunks"]
  216. for chunk in chunks:
  217. new_chunk = {
  218. "id": chunk["chunk_id"],
  219. "content": chunk["content"],
  220. "document_id": chunk["doc_id"],
  221. "document_name": chunk["docnm_kwd"],
  222. "dataset_id": chunk["kb_id"],
  223. "image_id": chunk.get("image_id", ""),
  224. "similarity": chunk["similarity"],
  225. "vector_similarity": chunk["vector_similarity"],
  226. "term_similarity": chunk["term_similarity"],
  227. "positions": chunk["positions"],
  228. }
  229. chunk_list.append(new_chunk)
  230. chunk_num += 1
  231. messages[message_num]["reference"] = chunk_list
  232. message_num += 1
  233. del conv["reference"]
  234. return get_result(data=convs)
  235. @manager.route('/chats/<chat_id>/sessions', methods=["DELETE"]) # noqa: F821
  236. @token_required
  237. def delete(tenant_id, chat_id):
  238. if not DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
  239. return get_error_data_result(message="You don't own the chat")
  240. req = request.json
  241. convs = ConversationService.query(dialog_id=chat_id)
  242. if not req:
  243. ids = None
  244. else:
  245. ids = req.get("ids")
  246. if not ids:
  247. conv_list = []
  248. for conv in convs:
  249. conv_list.append(conv.id)
  250. else:
  251. conv_list = ids
  252. for id in conv_list:
  253. conv = ConversationService.query(id=id, dialog_id=chat_id)
  254. if not conv:
  255. return get_error_data_result(message="The chat doesn't own the session")
  256. ConversationService.delete_by_id(id)
  257. return get_result()
  258. @manager.route('/sessions/ask', methods=['POST']) # noqa: F821
  259. @token_required
  260. def ask_about(tenant_id):
  261. req = request.json
  262. if not req.get("question"):
  263. return get_error_data_result("`question` is required.")
  264. if not req.get("dataset_ids"):
  265. return get_error_data_result("`dataset_ids` is required.")
  266. if not isinstance(req.get("dataset_ids"), list):
  267. return get_error_data_result("`dataset_ids` should be a list.")
  268. req["kb_ids"] = req.pop("dataset_ids")
  269. for kb_id in req["kb_ids"]:
  270. if not KnowledgebaseService.accessible(kb_id, tenant_id):
  271. return get_error_data_result(f"You don't own the dataset {kb_id}.")
  272. kbs = KnowledgebaseService.query(id=kb_id)
  273. kb = kbs[0]
  274. if kb.chunk_num == 0:
  275. return get_error_data_result(f"The dataset {kb_id} doesn't own parsed file")
  276. uid = tenant_id
  277. def stream():
  278. nonlocal req, uid
  279. try:
  280. for ans in ask(req["question"], req["kb_ids"], uid):
  281. yield "data:" + json.dumps({"code": 0, "message": "", "data": ans}, ensure_ascii=False) + "\n\n"
  282. except Exception as e:
  283. yield "data:" + json.dumps({"code": 500, "message": str(e),
  284. "data": {"answer": "**ERROR**: " + str(e), "reference": []}},
  285. ensure_ascii=False) + "\n\n"
  286. yield "data:" + json.dumps({"code": 0, "message": "", "data": True}, ensure_ascii=False) + "\n\n"
  287. resp = Response(stream(), mimetype="text/event-stream")
  288. resp.headers.add_header("Cache-control", "no-cache")
  289. resp.headers.add_header("Connection", "keep-alive")
  290. resp.headers.add_header("X-Accel-Buffering", "no")
  291. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  292. return resp
  293. @manager.route('/sessions/related_questions', methods=['POST']) # noqa: F821
  294. @token_required
  295. def related_questions(tenant_id):
  296. req = request.json
  297. if not req.get("question"):
  298. return get_error_data_result("`question` is required.")
  299. question = req["question"]
  300. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT)
  301. prompt = """
  302. Objective: To generate search terms related to the user's search keywords, helping users find more valuable information.
  303. Instructions:
  304. - Based on the keywords provided by the user, generate 5-10 related search terms.
  305. - Each search term should be directly or indirectly related to the keyword, guiding the user to find more valuable information.
  306. - Use common, general terms as much as possible, avoiding obscure words or technical jargon.
  307. - Keep the term length between 2-4 words, concise and clear.
  308. - DO NOT translate, use the language of the original keywords.
  309. ### Example:
  310. Keywords: Chinese football
  311. Related search terms:
  312. 1. Current status of Chinese football
  313. 2. Reform of Chinese football
  314. 3. Youth training of Chinese football
  315. 4. Chinese football in the Asian Cup
  316. 5. Chinese football in the World Cup
  317. Reason:
  318. - When searching, users often only use one or two keywords, making it difficult to fully express their information needs.
  319. - Generating related search terms can help users dig deeper into relevant information and improve search efficiency.
  320. - At the same time, related terms can also help search engines better understand user needs and return more accurate search results.
  321. """
  322. ans = chat_mdl.chat(prompt, [{"role": "user", "content": f"""
  323. Keywords: {question}
  324. Related search terms:
  325. """}], {"temperature": 0.9})
  326. return get_result(data=[re.sub(r"^[0-9]\. ", "", a) for a in ans.split("\n") if re.match(r"^[0-9]\. ", a)])
  327. @manager.route('/chatbots/<dialog_id>/completions', methods=['POST']) # noqa: F821
  328. def chatbot_completions(dialog_id):
  329. req = request.json
  330. token = request.headers.get('Authorization').split()
  331. if len(token) != 2:
  332. return get_error_data_result(message='Authorization is not valid!"')
  333. token = token[1]
  334. objs = APIToken.query(beta=token)
  335. if not objs:
  336. return get_error_data_result(message='Token is not valid!"')
  337. if "quote" not in req:
  338. req["quote"] = False
  339. if req.get("stream", True):
  340. resp = Response(iframe_completion(objs[0].tenant_id, dialog_id, **req), mimetype="text/event-stream")
  341. resp.headers.add_header("Cache-control", "no-cache")
  342. resp.headers.add_header("Connection", "keep-alive")
  343. resp.headers.add_header("X-Accel-Buffering", "no")
  344. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  345. return resp
  346. for answer in agent_completion(objs[0].tenant_id, dialog_id, **req):
  347. return get_result(data=answer)
  348. @manager.route('/agentbots/<agent_id>/completions', methods=['POST']) # noqa: F821
  349. def agent_bot_completions(agent_id):
  350. req = request.json
  351. token = request.headers.get('Authorization').split()
  352. if len(token) != 2:
  353. return get_error_data_result(message='Authorization is not valid!"')
  354. token = token[1]
  355. objs = APIToken.query(beta=token)
  356. if not objs:
  357. return get_error_data_result(message='Token is not valid!"')
  358. if "quote" not in req:
  359. req["quote"] = False
  360. if req.get("stream", True):
  361. resp = Response(agent_completion(objs[0].tenant_id, agent_id, **req), mimetype="text/event-stream")
  362. resp.headers.add_header("Cache-control", "no-cache")
  363. resp.headers.add_header("Connection", "keep-alive")
  364. resp.headers.add_header("X-Accel-Buffering", "no")
  365. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  366. return resp
  367. for answer in agent_completion(objs[0].tenant_id, agent_id, **req):
  368. return get_result(data=answer)