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 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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 json
  17. import re
  18. import time
  19. from flask import Response, jsonify, request
  20. from agent.canvas import Canvas
  21. from api.db import LLMType, StatusEnum
  22. from api.db.db_models import APIToken
  23. from api.db.services.api_service import API4ConversationService
  24. from api.db.services.canvas_service import UserCanvasService
  25. from api.db.services.canvas_service import completion as agent_completion
  26. from api.db.services.conversation_service import ConversationService, iframe_completion
  27. from api.db.services.conversation_service import completion as rag_completion
  28. from api.db.services.dialog_service import DialogService, ask, chat
  29. from api.db.services.file_service import FileService
  30. from api.db.services.knowledgebase_service import KnowledgebaseService
  31. from api.db.services.llm_service import LLMBundle
  32. from api.utils import get_uuid
  33. from api.utils.api_utils import get_error_data_result, get_result, token_required, validate_request
  34. @manager.route("/chats/<chat_id>/sessions", methods=["POST"]) # noqa: F821
  35. @token_required
  36. def create(tenant_id, chat_id):
  37. req = request.json
  38. req["dialog_id"] = chat_id
  39. dia = DialogService.query(tenant_id=tenant_id, id=req["dialog_id"], status=StatusEnum.VALID.value)
  40. if not dia:
  41. return get_error_data_result(message="You do not own the assistant.")
  42. conv = {
  43. "id": get_uuid(),
  44. "dialog_id": req["dialog_id"],
  45. "name": req.get("name", "New session"),
  46. "message": [{"role": "assistant", "content": dia[0].prompt_config.get("prologue")}],
  47. "user_id": req.get("user_id", ""),
  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. req = request.json
  64. if not request.is_json:
  65. req = request.form
  66. files = request.files
  67. user_id = request.args.get("user_id", "")
  68. e, cvs = UserCanvasService.get_by_id(agent_id)
  69. if not e:
  70. return get_error_data_result("Agent not found.")
  71. if not UserCanvasService.query(user_id=tenant_id, id=agent_id):
  72. return get_error_data_result("You cannot access the agent.")
  73. if not isinstance(cvs.dsl, str):
  74. cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False)
  75. canvas = Canvas(cvs.dsl, tenant_id)
  76. canvas.reset()
  77. query = canvas.get_preset_param()
  78. if query:
  79. for ele in query:
  80. if not ele["optional"]:
  81. if ele["type"] == "file":
  82. if files is None or not files.get(ele["key"]):
  83. return get_error_data_result(f"`{ele['key']}` with type `{ele['type']}` is required")
  84. upload_file = files.get(ele["key"])
  85. file_content = FileService.parse_docs([upload_file], user_id)
  86. file_name = upload_file.filename
  87. ele["value"] = file_name + "\n" + file_content
  88. else:
  89. if req is None or not req.get(ele["key"]):
  90. return get_error_data_result(f"`{ele['key']}` with type `{ele['type']}` is required")
  91. ele["value"] = req[ele["key"]]
  92. else:
  93. if ele["type"] == "file":
  94. if files is not None and files.get(ele["key"]):
  95. upload_file = files.get(ele["key"])
  96. file_content = FileService.parse_docs([upload_file], user_id)
  97. file_name = upload_file.filename
  98. ele["value"] = file_name + "\n" + file_content
  99. else:
  100. if "value" in ele:
  101. ele.pop("value")
  102. else:
  103. if req is not None and req.get(ele["key"]):
  104. ele["value"] = req[ele["key"]]
  105. else:
  106. if "value" in ele:
  107. ele.pop("value")
  108. for ans in canvas.run(stream=False):
  109. pass
  110. cvs.dsl = json.loads(str(canvas))
  111. conv = {"id": get_uuid(), "dialog_id": cvs.id, "user_id": user_id, "message": [{"role": "assistant", "content": canvas.get_prologue()}], "source": "agent", "dsl": cvs.dsl}
  112. API4ConversationService.save(**conv)
  113. conv["agent_id"] = conv.pop("dialog_id")
  114. return get_result(data=conv)
  115. @manager.route("/chats/<chat_id>/sessions/<session_id>", methods=["PUT"]) # noqa: F821
  116. @token_required
  117. def update(tenant_id, chat_id, session_id):
  118. req = request.json
  119. req["dialog_id"] = chat_id
  120. conv_id = session_id
  121. conv = ConversationService.query(id=conv_id, dialog_id=chat_id)
  122. if not conv:
  123. return get_error_data_result(message="Session does not exist")
  124. if not DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
  125. return get_error_data_result(message="You do not own the session")
  126. if "message" in req or "messages" in req:
  127. return get_error_data_result(message="`message` can not be change")
  128. if "reference" in req:
  129. return get_error_data_result(message="`reference` can not be change")
  130. if "name" in req and not req.get("name"):
  131. return get_error_data_result(message="`name` can not be empty.")
  132. if not ConversationService.update_by_id(conv_id, req):
  133. return get_error_data_result(message="Session updates error")
  134. return get_result()
  135. @manager.route("/chats/<chat_id>/completions", methods=["POST"]) # noqa: F821
  136. @token_required
  137. def chat_completion(tenant_id, chat_id):
  138. req = request.json
  139. if not req:
  140. req = {"question": ""}
  141. if not req.get("session_id"):
  142. req["question"] = ""
  143. if not DialogService.query(tenant_id=tenant_id, id=chat_id, status=StatusEnum.VALID.value):
  144. return get_error_data_result(f"You don't own the chat {chat_id}")
  145. if req.get("session_id"):
  146. if not ConversationService.query(id=req["session_id"], dialog_id=chat_id):
  147. return get_error_data_result(f"You don't own the session {req['session_id']}")
  148. if req.get("stream", True):
  149. resp = Response(rag_completion(tenant_id, chat_id, **req), mimetype="text/event-stream")
  150. resp.headers.add_header("Cache-control", "no-cache")
  151. resp.headers.add_header("Connection", "keep-alive")
  152. resp.headers.add_header("X-Accel-Buffering", "no")
  153. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  154. return resp
  155. else:
  156. answer = None
  157. for ans in rag_completion(tenant_id, chat_id, **req):
  158. answer = ans
  159. break
  160. return get_result(data=answer)
  161. @manager.route("/chats_openai/<chat_id>/chat/completions", methods=["POST"]) # noqa: F821
  162. @validate_request("model", "messages") # noqa: F821
  163. @token_required
  164. def chat_completion_openai_like(tenant_id, chat_id):
  165. """
  166. OpenAI-like chat completion API that simulates the behavior of OpenAI's completions endpoint.
  167. This function allows users to interact with a model and receive responses based on a series of historical messages.
  168. If `stream` is set to True (by default), the response will be streamed in chunks, mimicking the OpenAI-style API.
  169. Set `stream` to False explicitly, the response will be returned in a single complete answer.
  170. Example usage:
  171. curl -X POST https://ragflow_address.com/api/v1/chats_openai/<chat_id>/chat/completions \
  172. -H "Content-Type: application/json" \
  173. -H "Authorization: Bearer $RAGFLOW_API_KEY" \
  174. -d '{
  175. "model": "model",
  176. "messages": [{"role": "user", "content": "Say this is a test!"}],
  177. "stream": true
  178. }'
  179. Alternatively, you can use Python's `OpenAI` client:
  180. from openai import OpenAI
  181. model = "model"
  182. client = OpenAI(api_key="ragflow-api-key", base_url=f"http://ragflow_address/api/v1/chats_openai/<chat_id>")
  183. completion = client.chat.completions.create(
  184. model=model,
  185. messages=[
  186. {"role": "system", "content": "You are a helpful assistant."},
  187. {"role": "user", "content": "Who are you?"},
  188. {"role": "assistant", "content": "I am an AI assistant named..."},
  189. {"role": "user", "content": "Can you tell me how to install neovim"},
  190. ],
  191. stream=True
  192. )
  193. stream = True
  194. if stream:
  195. for chunk in completion:
  196. print(chunk)
  197. else:
  198. print(completion.choices[0].message.content)
  199. """
  200. req = request.json
  201. messages = req.get("messages", [])
  202. # To prevent empty [] input
  203. if len(messages) < 1:
  204. return get_error_data_result("You have to provide messages.")
  205. if messages[-1]["role"] != "user":
  206. return get_error_data_result("The last content of this conversation is not from user.")
  207. prompt = messages[-1]["content"]
  208. # Treat context tokens as reasoning tokens
  209. context_token_used = sum(len(message["content"]) for message in messages)
  210. dia = DialogService.query(tenant_id=tenant_id, id=chat_id, status=StatusEnum.VALID.value)
  211. if not dia:
  212. return get_error_data_result(f"You don't own the chat {chat_id}")
  213. dia = dia[0]
  214. # Filter system and non-sense assistant messages
  215. msg = None
  216. msg = [m for m in messages if m["role"] != "system" and (m["role"] != "assistant" or msg)]
  217. if req.get("stream", True):
  218. # The value for the usage field on all chunks except for the last one will be null.
  219. # The usage field on the last chunk contains token usage statistics for the entire request.
  220. # The choices field on the last chunk will always be an empty array [].
  221. def streamed_response_generator(chat_id, dia, msg):
  222. token_used = 0
  223. answer_cache = ""
  224. reasoning_cache = ""
  225. response = {
  226. "id": f"chatcmpl-{chat_id}",
  227. "choices": [{"delta": {"content": "", "role": "assistant", "function_call": None, "tool_calls": None, "reasoning_content": ""}, "finish_reason": None, "index": 0, "logprobs": None}],
  228. "created": int(time.time()),
  229. "model": "model",
  230. "object": "chat.completion.chunk",
  231. "system_fingerprint": "",
  232. "usage": None,
  233. }
  234. try:
  235. for ans in chat(dia, msg, True):
  236. answer = ans["answer"]
  237. reasoning_match = re.search(r"<think>(.*?)</think>", answer, flags=re.DOTALL)
  238. if reasoning_match:
  239. reasoning_part = reasoning_match.group(1)
  240. content_part = answer[reasoning_match.end() :]
  241. else:
  242. reasoning_part = ""
  243. content_part = answer
  244. reasoning_incremental = ""
  245. if reasoning_part:
  246. if reasoning_part.startswith(reasoning_cache):
  247. reasoning_incremental = reasoning_part.replace(reasoning_cache, "", 1)
  248. else:
  249. reasoning_incremental = reasoning_part
  250. reasoning_cache = reasoning_part
  251. content_incremental = ""
  252. if content_part:
  253. if content_part.startswith(answer_cache):
  254. content_incremental = content_part.replace(answer_cache, "", 1)
  255. else:
  256. content_incremental = content_part
  257. answer_cache = content_part
  258. token_used += len(reasoning_incremental) + len(content_incremental)
  259. if not any([reasoning_incremental, content_incremental]):
  260. continue
  261. if reasoning_incremental:
  262. response["choices"][0]["delta"]["reasoning_content"] = reasoning_incremental
  263. else:
  264. response["choices"][0]["delta"]["reasoning_content"] = None
  265. if content_incremental:
  266. response["choices"][0]["delta"]["content"] = content_incremental
  267. else:
  268. response["choices"][0]["delta"]["content"] = None
  269. yield f"data:{json.dumps(response, ensure_ascii=False)}\n\n"
  270. except Exception as e:
  271. response["choices"][0]["delta"]["content"] = "**ERROR**: " + str(e)
  272. yield f"data:{json.dumps(response, ensure_ascii=False)}\n\n"
  273. # The last chunk
  274. response["choices"][0]["delta"]["content"] = None
  275. response["choices"][0]["delta"]["reasoning_content"] = None
  276. response["choices"][0]["finish_reason"] = "stop"
  277. response["usage"] = {"prompt_tokens": len(prompt), "completion_tokens": token_used, "total_tokens": len(prompt) + token_used}
  278. yield f"data:{json.dumps(response, ensure_ascii=False)}\n\n"
  279. yield "data:[DONE]\n\n"
  280. resp = Response(streamed_response_generator(chat_id, dia, msg), mimetype="text/event-stream")
  281. resp.headers.add_header("Cache-control", "no-cache")
  282. resp.headers.add_header("Connection", "keep-alive")
  283. resp.headers.add_header("X-Accel-Buffering", "no")
  284. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  285. return resp
  286. else:
  287. answer = None
  288. for ans in chat(dia, msg, False):
  289. # focus answer content only
  290. answer = ans
  291. break
  292. content = answer["answer"]
  293. response = {
  294. "id": f"chatcmpl-{chat_id}",
  295. "object": "chat.completion",
  296. "created": int(time.time()),
  297. "model": req.get("model", ""),
  298. "usage": {
  299. "prompt_tokens": len(prompt),
  300. "completion_tokens": len(content),
  301. "total_tokens": len(prompt) + len(content),
  302. "completion_tokens_details": {
  303. "reasoning_tokens": context_token_used,
  304. "accepted_prediction_tokens": len(content),
  305. "rejected_prediction_tokens": 0, # 0 for simplicity
  306. },
  307. },
  308. "choices": [{"message": {"role": "assistant", "content": content}, "logprobs": None, "finish_reason": "stop", "index": 0}],
  309. }
  310. return jsonify(response)
  311. @manager.route("/agents/<agent_id>/completions", methods=["POST"]) # noqa: F821
  312. @token_required
  313. def agent_completions(tenant_id, agent_id):
  314. req = request.json
  315. cvs = UserCanvasService.query(user_id=tenant_id, id=agent_id)
  316. if not cvs:
  317. return get_error_data_result(f"You don't own the agent {agent_id}")
  318. if req.get("session_id"):
  319. dsl = cvs[0].dsl
  320. if not isinstance(dsl, str):
  321. dsl = json.dumps(dsl)
  322. # canvas = Canvas(dsl, tenant_id)
  323. # if canvas.get_preset_param():
  324. # req["question"] = ""
  325. conv = API4ConversationService.query(id=req["session_id"], dialog_id=agent_id)
  326. if not conv:
  327. return get_error_data_result(f"You don't own the session {req['session_id']}")
  328. # If an update to UserCanvas is detected, update the API4Conversation.dsl
  329. sync_dsl = req.get("sync_dsl", False)
  330. if sync_dsl is True and cvs[0].update_time > conv[0].update_time:
  331. current_dsl = conv[0].dsl
  332. new_dsl = json.loads(dsl)
  333. state_fields = ["history", "messages", "path", "reference"]
  334. states = {field: current_dsl.get(field, []) for field in state_fields}
  335. current_dsl.update(new_dsl)
  336. current_dsl.update(states)
  337. API4ConversationService.update_by_id(req["session_id"], {"dsl": current_dsl})
  338. else:
  339. req["question"] = ""
  340. if req.get("stream", True):
  341. resp = Response(agent_completion(tenant_id, agent_id, **req), mimetype="text/event-stream")
  342. resp.headers.add_header("Cache-control", "no-cache")
  343. resp.headers.add_header("Connection", "keep-alive")
  344. resp.headers.add_header("X-Accel-Buffering", "no")
  345. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  346. return resp
  347. try:
  348. for answer in agent_completion(tenant_id, agent_id, **req):
  349. return get_result(data=answer)
  350. except Exception as e:
  351. return get_error_data_result(str(e))
  352. @manager.route("/chats/<chat_id>/sessions", methods=["GET"]) # noqa: F821
  353. @token_required
  354. def list_session(tenant_id, chat_id):
  355. if not DialogService.query(tenant_id=tenant_id, id=chat_id, status=StatusEnum.VALID.value):
  356. return get_error_data_result(message=f"You don't own the assistant {chat_id}.")
  357. id = request.args.get("id")
  358. name = request.args.get("name")
  359. page_number = int(request.args.get("page", 1))
  360. items_per_page = int(request.args.get("page_size", 30))
  361. orderby = request.args.get("orderby", "create_time")
  362. user_id = request.args.get("user_id")
  363. if request.args.get("desc") == "False" or request.args.get("desc") == "false":
  364. desc = False
  365. else:
  366. desc = True
  367. convs = ConversationService.get_list(chat_id, page_number, items_per_page, orderby, desc, id, name, user_id)
  368. if not convs:
  369. return get_result(data=[])
  370. for conv in convs:
  371. conv["messages"] = conv.pop("message")
  372. infos = conv["messages"]
  373. for info in infos:
  374. if "prompt" in info:
  375. info.pop("prompt")
  376. conv["chat_id"] = conv.pop("dialog_id")
  377. if conv["reference"]:
  378. messages = conv["messages"]
  379. message_num = 0
  380. chunk_num = 0
  381. while message_num < len(messages):
  382. if message_num != 0 and messages[message_num]["role"] != "user":
  383. chunk_list = []
  384. if "chunks" in conv["reference"][chunk_num]:
  385. chunks = conv["reference"][chunk_num]["chunks"]
  386. for chunk in chunks:
  387. new_chunk = {
  388. "id": chunk.get("chunk_id", chunk.get("id")),
  389. "content": chunk.get("content_with_weight", chunk.get("content")),
  390. "document_id": chunk.get("doc_id", chunk.get("document_id")),
  391. "document_name": chunk.get("docnm_kwd", chunk.get("document_name")),
  392. "dataset_id": chunk.get("kb_id", chunk.get("dataset_id")),
  393. "image_id": chunk.get("image_id", chunk.get("img_id")),
  394. "positions": chunk.get("positions", chunk.get("position_int")),
  395. }
  396. chunk_list.append(new_chunk)
  397. chunk_num += 1
  398. messages[message_num]["reference"] = chunk_list
  399. message_num += 1
  400. del conv["reference"]
  401. return get_result(data=convs)
  402. @manager.route("/agents/<agent_id>/sessions", methods=["GET"]) # noqa: F821
  403. @token_required
  404. def list_agent_session(tenant_id, agent_id):
  405. if not UserCanvasService.query(user_id=tenant_id, id=agent_id):
  406. return get_error_data_result(message=f"You don't own the agent {agent_id}.")
  407. id = request.args.get("id")
  408. user_id = request.args.get("user_id")
  409. page_number = int(request.args.get("page", 1))
  410. items_per_page = int(request.args.get("page_size", 30))
  411. orderby = request.args.get("orderby", "update_time")
  412. if request.args.get("desc") == "False" or request.args.get("desc") == "false":
  413. desc = False
  414. else:
  415. desc = True
  416. # dsl defaults to True in all cases except for False and false
  417. include_dsl = request.args.get("dsl") != "False" and request.args.get("dsl") != "false"
  418. convs = API4ConversationService.get_list(agent_id, tenant_id, page_number, items_per_page, orderby, desc, id, user_id, include_dsl)
  419. if not convs:
  420. return get_result(data=[])
  421. for conv in convs:
  422. conv["messages"] = conv.pop("message")
  423. infos = conv["messages"]
  424. for info in infos:
  425. if "prompt" in info:
  426. info.pop("prompt")
  427. conv["agent_id"] = conv.pop("dialog_id")
  428. if conv["reference"]:
  429. messages = conv["messages"]
  430. message_num = 0
  431. chunk_num = 0
  432. while message_num < len(messages):
  433. if message_num != 0 and messages[message_num]["role"] != "user":
  434. chunk_list = []
  435. if "chunks" in conv["reference"][chunk_num]:
  436. chunks = conv["reference"][chunk_num]["chunks"]
  437. for chunk in chunks:
  438. new_chunk = {
  439. "id": chunk.get("chunk_id", chunk.get("id")),
  440. "content": chunk.get("content_with_weight", chunk.get("content")),
  441. "document_id": chunk.get("doc_id", chunk.get("document_id")),
  442. "document_name": chunk.get("docnm_kwd", chunk.get("document_name")),
  443. "dataset_id": chunk.get("kb_id", chunk.get("dataset_id")),
  444. "image_id": chunk.get("image_id", chunk.get("img_id")),
  445. "positions": chunk.get("positions", chunk.get("position_int")),
  446. }
  447. chunk_list.append(new_chunk)
  448. chunk_num += 1
  449. messages[message_num]["reference"] = chunk_list
  450. message_num += 1
  451. del conv["reference"]
  452. return get_result(data=convs)
  453. @manager.route("/chats/<chat_id>/sessions", methods=["DELETE"]) # noqa: F821
  454. @token_required
  455. def delete(tenant_id, chat_id):
  456. if not DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
  457. return get_error_data_result(message="You don't own the chat")
  458. req = request.json
  459. convs = ConversationService.query(dialog_id=chat_id)
  460. if not req:
  461. ids = None
  462. else:
  463. ids = req.get("ids")
  464. if not ids:
  465. conv_list = []
  466. for conv in convs:
  467. conv_list.append(conv.id)
  468. else:
  469. conv_list = ids
  470. for id in conv_list:
  471. conv = ConversationService.query(id=id, dialog_id=chat_id)
  472. if not conv:
  473. return get_error_data_result(message="The chat doesn't own the session")
  474. ConversationService.delete_by_id(id)
  475. return get_result()
  476. @manager.route("/agents/<agent_id>/sessions", methods=["DELETE"]) # noqa: F821
  477. @token_required
  478. def delete_agent_session(tenant_id, agent_id):
  479. req = request.json
  480. cvs = UserCanvasService.query(user_id=tenant_id, id=agent_id)
  481. if not cvs:
  482. return get_error_data_result(f"You don't own the agent {agent_id}")
  483. convs = API4ConversationService.query(dialog_id=agent_id)
  484. if not convs:
  485. return get_error_data_result(f"Agent {agent_id} has no sessions")
  486. if not req:
  487. ids = None
  488. else:
  489. ids = req.get("ids")
  490. if not ids:
  491. conv_list = []
  492. for conv in convs:
  493. conv_list.append(conv.id)
  494. else:
  495. conv_list = ids
  496. for session_id in conv_list:
  497. conv = API4ConversationService.query(id=session_id, dialog_id=agent_id)
  498. if not conv:
  499. return get_error_data_result(f"The agent doesn't own the session ${session_id}")
  500. API4ConversationService.delete_by_id(session_id)
  501. return get_result()
  502. @manager.route("/sessions/ask", methods=["POST"]) # noqa: F821
  503. @token_required
  504. def ask_about(tenant_id):
  505. req = request.json
  506. if not req.get("question"):
  507. return get_error_data_result("`question` is required.")
  508. if not req.get("dataset_ids"):
  509. return get_error_data_result("`dataset_ids` is required.")
  510. if not isinstance(req.get("dataset_ids"), list):
  511. return get_error_data_result("`dataset_ids` should be a list.")
  512. req["kb_ids"] = req.pop("dataset_ids")
  513. for kb_id in req["kb_ids"]:
  514. if not KnowledgebaseService.accessible(kb_id, tenant_id):
  515. return get_error_data_result(f"You don't own the dataset {kb_id}.")
  516. kbs = KnowledgebaseService.query(id=kb_id)
  517. kb = kbs[0]
  518. if kb.chunk_num == 0:
  519. return get_error_data_result(f"The dataset {kb_id} doesn't own parsed file")
  520. uid = tenant_id
  521. def stream():
  522. nonlocal req, uid
  523. try:
  524. for ans in ask(req["question"], req["kb_ids"], uid):
  525. yield "data:" + json.dumps({"code": 0, "message": "", "data": ans}, ensure_ascii=False) + "\n\n"
  526. except Exception as e:
  527. yield "data:" + json.dumps({"code": 500, "message": str(e), "data": {"answer": "**ERROR**: " + str(e), "reference": []}}, ensure_ascii=False) + "\n\n"
  528. yield "data:" + json.dumps({"code": 0, "message": "", "data": True}, ensure_ascii=False) + "\n\n"
  529. resp = Response(stream(), mimetype="text/event-stream")
  530. resp.headers.add_header("Cache-control", "no-cache")
  531. resp.headers.add_header("Connection", "keep-alive")
  532. resp.headers.add_header("X-Accel-Buffering", "no")
  533. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  534. return resp
  535. @manager.route("/sessions/related_questions", methods=["POST"]) # noqa: F821
  536. @token_required
  537. def related_questions(tenant_id):
  538. req = request.json
  539. if not req.get("question"):
  540. return get_error_data_result("`question` is required.")
  541. question = req["question"]
  542. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT)
  543. prompt = """
  544. Objective: To generate search terms related to the user's search keywords, helping users find more valuable information.
  545. Instructions:
  546. - Based on the keywords provided by the user, generate 5-10 related search terms.
  547. - Each search term should be directly or indirectly related to the keyword, guiding the user to find more valuable information.
  548. - Use common, general terms as much as possible, avoiding obscure words or technical jargon.
  549. - Keep the term length between 2-4 words, concise and clear.
  550. - DO NOT translate, use the language of the original keywords.
  551. ### Example:
  552. Keywords: Chinese football
  553. Related search terms:
  554. 1. Current status of Chinese football
  555. 2. Reform of Chinese football
  556. 3. Youth training of Chinese football
  557. 4. Chinese football in the Asian Cup
  558. 5. Chinese football in the World Cup
  559. Reason:
  560. - When searching, users often only use one or two keywords, making it difficult to fully express their information needs.
  561. - Generating related search terms can help users dig deeper into relevant information and improve search efficiency.
  562. - At the same time, related terms can also help search engines better understand user needs and return more accurate search results.
  563. """
  564. ans = chat_mdl.chat(
  565. prompt,
  566. [
  567. {
  568. "role": "user",
  569. "content": f"""
  570. Keywords: {question}
  571. Related search terms:
  572. """,
  573. }
  574. ],
  575. {"temperature": 0.9},
  576. )
  577. return get_result(data=[re.sub(r"^[0-9]\. ", "", a) for a in ans.split("\n") if re.match(r"^[0-9]\. ", a)])
  578. @manager.route("/chatbots/<dialog_id>/completions", methods=["POST"]) # noqa: F821
  579. def chatbot_completions(dialog_id):
  580. req = request.json
  581. token = request.headers.get("Authorization").split()
  582. if len(token) != 2:
  583. return get_error_data_result(message='Authorization is not valid!"')
  584. token = token[1]
  585. objs = APIToken.query(beta=token)
  586. if not objs:
  587. return get_error_data_result(message='Authentication error: API key is invalid!"')
  588. if "quote" not in req:
  589. req["quote"] = False
  590. if req.get("stream", True):
  591. resp = Response(iframe_completion(dialog_id, **req), mimetype="text/event-stream")
  592. resp.headers.add_header("Cache-control", "no-cache")
  593. resp.headers.add_header("Connection", "keep-alive")
  594. resp.headers.add_header("X-Accel-Buffering", "no")
  595. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  596. return resp
  597. for answer in iframe_completion(dialog_id, **req):
  598. return get_result(data=answer)
  599. @manager.route("/agentbots/<agent_id>/completions", methods=["POST"]) # noqa: F821
  600. def agent_bot_completions(agent_id):
  601. req = request.json
  602. token = request.headers.get("Authorization").split()
  603. if len(token) != 2:
  604. return get_error_data_result(message='Authorization is not valid!"')
  605. token = token[1]
  606. objs = APIToken.query(beta=token)
  607. if not objs:
  608. return get_error_data_result(message='Authentication error: API key is invalid!"')
  609. if "quote" not in req:
  610. req["quote"] = False
  611. if req.get("stream", True):
  612. resp = Response(agent_completion(objs[0].tenant_id, agent_id, **req), mimetype="text/event-stream")
  613. resp.headers.add_header("Cache-control", "no-cache")
  614. resp.headers.add_header("Connection", "keep-alive")
  615. resp.headers.add_header("X-Accel-Buffering", "no")
  616. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  617. return resp
  618. for answer in agent_completion(objs[0].tenant_id, agent_id, **req):
  619. return get_result(data=answer)