Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. from api.db.services.file_service import FileService
  36. @manager.route('/chats/<chat_id>/sessions', methods=['POST']) # noqa: F821
  37. @token_required
  38. def create(tenant_id, chat_id):
  39. req = request.json
  40. req["dialog_id"] = chat_id
  41. dia = DialogService.query(tenant_id=tenant_id, id=req["dialog_id"], status=StatusEnum.VALID.value)
  42. if not dia:
  43. return get_error_data_result(message="You do not own the assistant.")
  44. conv = {
  45. "id": get_uuid(),
  46. "dialog_id": req["dialog_id"],
  47. "name": req.get("name", "New session"),
  48. "message": [{"role": "assistant", "content": dia[0].prompt_config.get("prologue")}],
  49. "user_id": req.get("user_id", "")
  50. }
  51. if not conv.get("name"):
  52. return get_error_data_result(message="`name` can not be empty.")
  53. ConversationService.save(**conv)
  54. e, conv = ConversationService.get_by_id(conv["id"])
  55. if not e:
  56. return get_error_data_result(message="Fail to create a session!")
  57. conv = conv.to_dict()
  58. conv['messages'] = conv.pop("message")
  59. conv["chat_id"] = conv.pop("dialog_id")
  60. del conv["reference"]
  61. return get_result(data=conv)
  62. @manager.route('/agents/<agent_id>/sessions', methods=['POST']) # noqa: F821
  63. @token_required
  64. def create_agent_session(tenant_id, agent_id):
  65. req = request.json
  66. if not request.is_json:
  67. req = request.form
  68. files = request.files
  69. user_id = request.args.get('user_id', '')
  70. e, cvs = UserCanvasService.get_by_id(agent_id)
  71. if not e:
  72. return get_error_data_result("Agent not found.")
  73. if not UserCanvasService.query(user_id=tenant_id, id=agent_id):
  74. return get_error_data_result("You cannot access the agent.")
  75. if not isinstance(cvs.dsl, str):
  76. cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False)
  77. canvas = Canvas(cvs.dsl, tenant_id)
  78. canvas.reset()
  79. query = canvas.get_preset_param()
  80. if query:
  81. for ele in query:
  82. if not ele["optional"]:
  83. if ele["type"] == "file":
  84. if files is None or not files.get(ele["key"]):
  85. return get_error_data_result(f"`{ele['key']}` with type `{ele['type']}` is required")
  86. upload_file = files.get(ele["key"])
  87. file_content = FileService.parse_docs([upload_file], user_id)
  88. file_name = upload_file.filename
  89. ele["value"] = file_name + "\n" + file_content
  90. else:
  91. if req is None or not req.get(ele["key"]):
  92. return get_error_data_result(f"`{ele['key']}` with type `{ele['type']}` is required")
  93. ele["value"] = req[ele["key"]]
  94. else:
  95. if ele["type"] == "file":
  96. if files is not None and files.get(ele["key"]):
  97. upload_file = files.get(ele["key"])
  98. file_content = FileService.parse_docs([upload_file], user_id)
  99. file_name = upload_file.filename
  100. ele["value"] = file_name + "\n" + file_content
  101. else:
  102. if "value" in ele:
  103. ele.pop("value")
  104. else:
  105. if req is not None and req.get(ele["key"]):
  106. ele["value"] = req[ele['key']]
  107. else:
  108. if "value" in ele:
  109. ele.pop("value")
  110. else:
  111. for ans in canvas.run(stream=False):
  112. pass
  113. cvs.dsl = json.loads(str(canvas))
  114. conv = {
  115. "id": get_uuid(),
  116. "dialog_id": cvs.id,
  117. "user_id": user_id,
  118. "message": [{"role": "assistant", "content": canvas.get_prologue()}],
  119. "source": "agent",
  120. "dsl": cvs.dsl
  121. }
  122. API4ConversationService.save(**conv)
  123. conv["agent_id"] = conv.pop("dialog_id")
  124. return get_result(data=conv)
  125. @manager.route('/chats/<chat_id>/sessions/<session_id>', methods=['PUT']) # noqa: F821
  126. @token_required
  127. def update(tenant_id, chat_id, session_id):
  128. req = request.json
  129. req["dialog_id"] = chat_id
  130. conv_id = session_id
  131. conv = ConversationService.query(id=conv_id, dialog_id=chat_id)
  132. if not conv:
  133. return get_error_data_result(message="Session does not exist")
  134. if not DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
  135. return get_error_data_result(message="You do not own the session")
  136. if "message" in req or "messages" in req:
  137. return get_error_data_result(message="`message` can not be change")
  138. if "reference" in req:
  139. return get_error_data_result(message="`reference` can not be change")
  140. if "name" in req and not req.get("name"):
  141. return get_error_data_result(message="`name` can not be empty.")
  142. if not ConversationService.update_by_id(conv_id, req):
  143. return get_error_data_result(message="Session updates error")
  144. return get_result()
  145. @manager.route('/chats/<chat_id>/completions', methods=['POST']) # noqa: F821
  146. @token_required
  147. def chat_completion(tenant_id, chat_id):
  148. req = request.json
  149. if not req:
  150. req = {"question": ""}
  151. if not req.get("session_id"):
  152. req["question"]=""
  153. if not DialogService.query(tenant_id=tenant_id, id=chat_id, status=StatusEnum.VALID.value):
  154. return get_error_data_result(f"You don't own the chat {chat_id}")
  155. if req.get("session_id"):
  156. if not ConversationService.query(id=req["session_id"], dialog_id=chat_id):
  157. return get_error_data_result(f"You don't own the session {req['session_id']}")
  158. if req.get("stream", True):
  159. resp = Response(rag_completion(tenant_id, chat_id, **req), mimetype="text/event-stream")
  160. resp.headers.add_header("Cache-control", "no-cache")
  161. resp.headers.add_header("Connection", "keep-alive")
  162. resp.headers.add_header("X-Accel-Buffering", "no")
  163. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  164. return resp
  165. else:
  166. answer = None
  167. for ans in rag_completion(tenant_id, chat_id, **req):
  168. answer = ans
  169. break
  170. return get_result(data=answer)
  171. @manager.route('/agents/<agent_id>/completions', methods=['POST']) # noqa: F821
  172. @token_required
  173. def agent_completions(tenant_id, agent_id):
  174. req = request.json
  175. cvs = UserCanvasService.query(user_id=tenant_id, id=agent_id)
  176. if not cvs:
  177. return get_error_data_result(f"You don't own the agent {agent_id}")
  178. if req.get("session_id"):
  179. dsl = cvs[0].dsl
  180. if not isinstance(dsl, str):
  181. dsl = json.dumps(dsl)
  182. #canvas = Canvas(dsl, tenant_id)
  183. #if canvas.get_preset_param():
  184. # req["question"] = ""
  185. conv = API4ConversationService.query(id=req["session_id"], dialog_id=agent_id)
  186. if not conv:
  187. return get_error_data_result(f"You don't own the session {req['session_id']}")
  188. else:
  189. req["question"] = ""
  190. if req.get("stream", True):
  191. resp = Response(agent_completion(tenant_id, agent_id, **req), mimetype="text/event-stream")
  192. resp.headers.add_header("Cache-control", "no-cache")
  193. resp.headers.add_header("Connection", "keep-alive")
  194. resp.headers.add_header("X-Accel-Buffering", "no")
  195. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  196. return resp
  197. try:
  198. for answer in agent_completion(tenant_id, agent_id, **req):
  199. return get_result(data=answer)
  200. except Exception as e:
  201. return get_error_data_result(str(e))
  202. @manager.route('/chats/<chat_id>/sessions', methods=['GET']) # noqa: F821
  203. @token_required
  204. def list_session(tenant_id, chat_id):
  205. if not DialogService.query(tenant_id=tenant_id, id=chat_id, status=StatusEnum.VALID.value):
  206. return get_error_data_result(message=f"You don't own the assistant {chat_id}.")
  207. id = request.args.get("id")
  208. name = request.args.get("name")
  209. page_number = int(request.args.get("page", 1))
  210. items_per_page = int(request.args.get("page_size", 30))
  211. orderby = request.args.get("orderby", "create_time")
  212. user_id = request.args.get("user_id")
  213. if request.args.get("desc") == "False" or request.args.get("desc") == "false":
  214. desc = False
  215. else:
  216. desc = True
  217. convs = ConversationService.get_list(chat_id, page_number, items_per_page, orderby, desc, id, name, user_id)
  218. if not convs:
  219. return get_result(data=[])
  220. for conv in convs:
  221. conv['messages'] = conv.pop("message")
  222. infos = conv["messages"]
  223. for info in infos:
  224. if "prompt" in info:
  225. info.pop("prompt")
  226. conv["chat_id"] = conv.pop("dialog_id")
  227. if conv["reference"]:
  228. messages = conv["messages"]
  229. message_num = 0
  230. chunk_num = 0
  231. while message_num < len(messages):
  232. if message_num != 0 and messages[message_num]["role"] != "user":
  233. chunk_list = []
  234. if "chunks" in conv["reference"][chunk_num]:
  235. chunks = conv["reference"][chunk_num]["chunks"]
  236. for chunk in chunks:
  237. new_chunk = {
  238. "id": chunk.get("chunk_id", chunk.get("id")),
  239. "content": chunk.get("content_with_weight", chunk.get("content")),
  240. "document_id": chunk.get("doc_id", chunk.get("document_id")),
  241. "document_name": chunk.get("docnm_kwd", chunk.get("document_name")),
  242. "dataset_id": chunk.get("kb_id", chunk.get("dataset_id")),
  243. "image_id": chunk.get("image_id", chunk.get("img_id")),
  244. "positions": chunk.get("positions", chunk.get("position_int")),
  245. }
  246. chunk_list.append(new_chunk)
  247. chunk_num += 1
  248. messages[message_num]["reference"] = chunk_list
  249. message_num += 1
  250. del conv["reference"]
  251. return get_result(data=convs)
  252. @manager.route('/agents/<agent_id>/sessions', methods=['GET']) # noqa: F821
  253. @token_required
  254. def list_agent_session(tenant_id, agent_id):
  255. if not UserCanvasService.query(user_id=tenant_id, id=agent_id):
  256. return get_error_data_result(message=f"You don't own the agent {agent_id}.")
  257. id = request.args.get("id")
  258. user_id = request.args.get("user_id")
  259. page_number = int(request.args.get("page", 1))
  260. items_per_page = int(request.args.get("page_size", 30))
  261. orderby = request.args.get("orderby", "update_time")
  262. if request.args.get("desc") == "False" or request.args.get("desc") == "false":
  263. desc = False
  264. else:
  265. desc = True
  266. convs = API4ConversationService.get_list(agent_id, tenant_id, page_number, items_per_page, orderby, desc, id, user_id)
  267. if not convs:
  268. return get_result(data=[])
  269. for conv in convs:
  270. conv['messages'] = conv.pop("message")
  271. infos = conv["messages"]
  272. for info in infos:
  273. if "prompt" in info:
  274. info.pop("prompt")
  275. conv["agent_id"] = conv.pop("dialog_id")
  276. if conv["reference"]:
  277. messages = conv["messages"]
  278. message_num = 0
  279. chunk_num = 0
  280. while message_num < len(messages):
  281. if message_num != 0 and messages[message_num]["role"] != "user":
  282. chunk_list = []
  283. if "chunks" in conv["reference"][chunk_num]:
  284. chunks = conv["reference"][chunk_num]["chunks"]
  285. for chunk in chunks:
  286. new_chunk = {
  287. "id": chunk.get("chunk_id", chunk.get("id")),
  288. "content": chunk.get("content_with_weight", chunk.get("content")),
  289. "document_id": chunk.get("doc_id", chunk.get("document_id")),
  290. "document_name": chunk.get("docnm_kwd", chunk.get("document_name")),
  291. "dataset_id": chunk.get("kb_id", chunk.get("dataset_id")),
  292. "image_id": chunk.get("image_id", chunk.get("img_id")),
  293. "positions": chunk.get("positions", chunk.get("position_int")),
  294. }
  295. chunk_list.append(new_chunk)
  296. chunk_num += 1
  297. messages[message_num]["reference"] = chunk_list
  298. message_num += 1
  299. del conv["reference"]
  300. return get_result(data=convs)
  301. @manager.route('/chats/<chat_id>/sessions', methods=["DELETE"]) # noqa: F821
  302. @token_required
  303. def delete(tenant_id, chat_id):
  304. if not DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
  305. return get_error_data_result(message="You don't own the chat")
  306. req = request.json
  307. convs = ConversationService.query(dialog_id=chat_id)
  308. if not req:
  309. ids = None
  310. else:
  311. ids = req.get("ids")
  312. if not ids:
  313. conv_list = []
  314. for conv in convs:
  315. conv_list.append(conv.id)
  316. else:
  317. conv_list = ids
  318. for id in conv_list:
  319. conv = ConversationService.query(id=id, dialog_id=chat_id)
  320. if not conv:
  321. return get_error_data_result(message="The chat doesn't own the session")
  322. ConversationService.delete_by_id(id)
  323. return get_result()
  324. @manager.route('/sessions/ask', methods=['POST']) # noqa: F821
  325. @token_required
  326. def ask_about(tenant_id):
  327. req = request.json
  328. if not req.get("question"):
  329. return get_error_data_result("`question` is required.")
  330. if not req.get("dataset_ids"):
  331. return get_error_data_result("`dataset_ids` is required.")
  332. if not isinstance(req.get("dataset_ids"), list):
  333. return get_error_data_result("`dataset_ids` should be a list.")
  334. req["kb_ids"] = req.pop("dataset_ids")
  335. for kb_id in req["kb_ids"]:
  336. if not KnowledgebaseService.accessible(kb_id, tenant_id):
  337. return get_error_data_result(f"You don't own the dataset {kb_id}.")
  338. kbs = KnowledgebaseService.query(id=kb_id)
  339. kb = kbs[0]
  340. if kb.chunk_num == 0:
  341. return get_error_data_result(f"The dataset {kb_id} doesn't own parsed file")
  342. uid = tenant_id
  343. def stream():
  344. nonlocal req, uid
  345. try:
  346. for ans in ask(req["question"], req["kb_ids"], uid):
  347. yield "data:" + json.dumps({"code": 0, "message": "", "data": ans}, ensure_ascii=False) + "\n\n"
  348. except Exception as e:
  349. yield "data:" + json.dumps({"code": 500, "message": str(e),
  350. "data": {"answer": "**ERROR**: " + str(e), "reference": []}},
  351. ensure_ascii=False) + "\n\n"
  352. yield "data:" + json.dumps({"code": 0, "message": "", "data": True}, ensure_ascii=False) + "\n\n"
  353. resp = Response(stream(), mimetype="text/event-stream")
  354. resp.headers.add_header("Cache-control", "no-cache")
  355. resp.headers.add_header("Connection", "keep-alive")
  356. resp.headers.add_header("X-Accel-Buffering", "no")
  357. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  358. return resp
  359. @manager.route('/sessions/related_questions', methods=['POST']) # noqa: F821
  360. @token_required
  361. def related_questions(tenant_id):
  362. req = request.json
  363. if not req.get("question"):
  364. return get_error_data_result("`question` is required.")
  365. question = req["question"]
  366. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT)
  367. prompt = """
  368. Objective: To generate search terms related to the user's search keywords, helping users find more valuable information.
  369. Instructions:
  370. - Based on the keywords provided by the user, generate 5-10 related search terms.
  371. - Each search term should be directly or indirectly related to the keyword, guiding the user to find more valuable information.
  372. - Use common, general terms as much as possible, avoiding obscure words or technical jargon.
  373. - Keep the term length between 2-4 words, concise and clear.
  374. - DO NOT translate, use the language of the original keywords.
  375. ### Example:
  376. Keywords: Chinese football
  377. Related search terms:
  378. 1. Current status of Chinese football
  379. 2. Reform of Chinese football
  380. 3. Youth training of Chinese football
  381. 4. Chinese football in the Asian Cup
  382. 5. Chinese football in the World Cup
  383. Reason:
  384. - When searching, users often only use one or two keywords, making it difficult to fully express their information needs.
  385. - Generating related search terms can help users dig deeper into relevant information and improve search efficiency.
  386. - At the same time, related terms can also help search engines better understand user needs and return more accurate search results.
  387. """
  388. ans = chat_mdl.chat(prompt, [{"role": "user", "content": f"""
  389. Keywords: {question}
  390. Related search terms:
  391. """}], {"temperature": 0.9})
  392. return get_result(data=[re.sub(r"^[0-9]\. ", "", a) for a in ans.split("\n") if re.match(r"^[0-9]\. ", a)])
  393. @manager.route('/chatbots/<dialog_id>/completions', methods=['POST']) # noqa: F821
  394. def chatbot_completions(dialog_id):
  395. req = request.json
  396. token = request.headers.get('Authorization').split()
  397. if len(token) != 2:
  398. return get_error_data_result(message='Authorization is not valid!"')
  399. token = token[1]
  400. objs = APIToken.query(beta=token)
  401. if not objs:
  402. return get_error_data_result(message='Authentication error: API key is invalid!"')
  403. if "quote" not in req:
  404. req["quote"] = False
  405. if req.get("stream", True):
  406. resp = Response(iframe_completion(dialog_id, **req), mimetype="text/event-stream")
  407. resp.headers.add_header("Cache-control", "no-cache")
  408. resp.headers.add_header("Connection", "keep-alive")
  409. resp.headers.add_header("X-Accel-Buffering", "no")
  410. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  411. return resp
  412. for answer in iframe_completion(dialog_id, **req):
  413. return get_result(data=answer)
  414. @manager.route('/agentbots/<agent_id>/completions', methods=['POST']) # noqa: F821
  415. def agent_bot_completions(agent_id):
  416. req = request.json
  417. token = request.headers.get('Authorization').split()
  418. if len(token) != 2:
  419. return get_error_data_result(message='Authorization is not valid!"')
  420. token = token[1]
  421. objs = APIToken.query(beta=token)
  422. if not objs:
  423. return get_error_data_result(message='Authentication error: API key is invalid!"')
  424. if "quote" not in req:
  425. req["quote"] = False
  426. if req.get("stream", True):
  427. resp = Response(agent_completion(objs[0].tenant_id, agent_id, **req), mimetype="text/event-stream")
  428. resp.headers.add_header("Cache-control", "no-cache")
  429. resp.headers.add_header("Connection", "keep-alive")
  430. resp.headers.add_header("X-Accel-Buffering", "no")
  431. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  432. return resp
  433. for answer in agent_completion(objs[0].tenant_id, agent_id, **req):
  434. return get_result(data=answer)