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

session.py 29KB

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