您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

session.py 30KB

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