選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

session.py 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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. response = {
  235. "id": f"chatcmpl-{chat_id}",
  236. "choices": [
  237. {
  238. "delta": {
  239. "content": "",
  240. "role": "assistant",
  241. "function_call": None,
  242. "tool_calls": None
  243. },
  244. "finish_reason": None,
  245. "index": 0,
  246. "logprobs": None
  247. }
  248. ],
  249. "created": int(time.time()),
  250. "model": "model",
  251. "object": "chat.completion.chunk",
  252. "system_fingerprint": "",
  253. "usage": None
  254. }
  255. try:
  256. for ans in chat(dia, msg, True):
  257. answer = ans["answer"]
  258. incremental = answer[token_used:]
  259. token_used += len(incremental)
  260. response["choices"][0]["delta"]["content"] = incremental
  261. yield f"data:{json.dumps(response, ensure_ascii=False)}\n\n"
  262. except Exception as e:
  263. response["choices"][0]["delta"]["content"] = "**ERROR**: " + str(e)
  264. yield f"data:{json.dumps(response, ensure_ascii=False)}\n\n"
  265. # The last chunk
  266. response["choices"][0]["delta"]["content"] = None
  267. response["choices"][0]["finish_reason"] = "stop"
  268. response["usage"] = {
  269. "prompt_tokens": len(prompt),
  270. "completion_tokens": token_used,
  271. "total_tokens": len(prompt) + token_used
  272. }
  273. yield f"data:{json.dumps(response, ensure_ascii=False)}\n\n"
  274. yield "data:[DONE]\n\n"
  275. resp = Response(streamed_response_generator(chat_id, dia, msg), mimetype="text/event-stream")
  276. resp.headers.add_header("Cache-control", "no-cache")
  277. resp.headers.add_header("Connection", "keep-alive")
  278. resp.headers.add_header("X-Accel-Buffering", "no")
  279. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  280. return resp
  281. else:
  282. answer = None
  283. for ans in chat(dia, msg, False):
  284. # focus answer content only
  285. answer = ans
  286. break
  287. content = answer["answer"]
  288. response = {
  289. "id": f"chatcmpl-{chat_id}",
  290. "object": "chat.completion",
  291. "created": int(time.time()),
  292. "model": req.get("model", ""),
  293. "usage": {
  294. "prompt_tokens": len(prompt),
  295. "completion_tokens": len(content),
  296. "total_tokens": len(prompt) + len(content),
  297. "completion_tokens_details": {
  298. "reasoning_tokens": context_token_used,
  299. "accepted_prediction_tokens": len(content),
  300. "rejected_prediction_tokens": 0 # 0 for simplicity
  301. }
  302. },
  303. "choices": [
  304. {
  305. "message": {
  306. "role": "assistant",
  307. "content": content
  308. },
  309. "logprobs": None,
  310. "finish_reason": "stop",
  311. "index": 0
  312. }
  313. ]
  314. }
  315. return jsonify(response)
  316. @manager.route('/agents/<agent_id>/completions', methods=['POST']) # noqa: F821
  317. @token_required
  318. def agent_completions(tenant_id, agent_id):
  319. req = request.json
  320. cvs = UserCanvasService.query(user_id=tenant_id, id=agent_id)
  321. if not cvs:
  322. return get_error_data_result(f"You don't own the agent {agent_id}")
  323. if req.get("session_id"):
  324. dsl = cvs[0].dsl
  325. if not isinstance(dsl, str):
  326. dsl = json.dumps(dsl)
  327. #canvas = Canvas(dsl, tenant_id)
  328. #if canvas.get_preset_param():
  329. # req["question"] = ""
  330. conv = API4ConversationService.query(id=req["session_id"], dialog_id=agent_id)
  331. if not conv:
  332. return get_error_data_result(f"You don't own the session {req['session_id']}")
  333. # If an update to UserCanvas is detected, update the API4Conversation.dsl
  334. sync_dsl = req.get("sync_dsl", False)
  335. if sync_dsl is True and cvs[0].update_time > conv[0].update_time:
  336. current_dsl = conv[0].dsl
  337. new_dsl = json.loads(dsl)
  338. state_fields = ["history", "messages", "path", "reference"]
  339. states = {field: current_dsl.get(field, []) for field in state_fields}
  340. current_dsl.update(new_dsl)
  341. current_dsl.update(states)
  342. API4ConversationService.update_by_id(req["session_id"], {
  343. "dsl": current_dsl
  344. })
  345. else:
  346. req["question"] = ""
  347. if req.get("stream", True):
  348. resp = Response(agent_completion(tenant_id, agent_id, **req), mimetype="text/event-stream")
  349. resp.headers.add_header("Cache-control", "no-cache")
  350. resp.headers.add_header("Connection", "keep-alive")
  351. resp.headers.add_header("X-Accel-Buffering", "no")
  352. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  353. return resp
  354. try:
  355. for answer in agent_completion(tenant_id, agent_id, **req):
  356. return get_result(data=answer)
  357. except Exception as e:
  358. return get_error_data_result(str(e))
  359. @manager.route('/chats/<chat_id>/sessions', methods=['GET']) # noqa: F821
  360. @token_required
  361. def list_session(tenant_id, chat_id):
  362. if not DialogService.query(tenant_id=tenant_id, id=chat_id, status=StatusEnum.VALID.value):
  363. return get_error_data_result(message=f"You don't own the assistant {chat_id}.")
  364. id = request.args.get("id")
  365. name = request.args.get("name")
  366. page_number = int(request.args.get("page", 1))
  367. items_per_page = int(request.args.get("page_size", 30))
  368. orderby = request.args.get("orderby", "create_time")
  369. user_id = request.args.get("user_id")
  370. if request.args.get("desc") == "False" or request.args.get("desc") == "false":
  371. desc = False
  372. else:
  373. desc = True
  374. convs = ConversationService.get_list(chat_id, page_number, items_per_page, orderby, desc, id, name, user_id)
  375. if not convs:
  376. return get_result(data=[])
  377. for conv in convs:
  378. conv['messages'] = conv.pop("message")
  379. infos = conv["messages"]
  380. for info in infos:
  381. if "prompt" in info:
  382. info.pop("prompt")
  383. conv["chat_id"] = conv.pop("dialog_id")
  384. if conv["reference"]:
  385. messages = conv["messages"]
  386. message_num = 0
  387. chunk_num = 0
  388. while message_num < len(messages):
  389. if message_num != 0 and messages[message_num]["role"] != "user":
  390. chunk_list = []
  391. if "chunks" in conv["reference"][chunk_num]:
  392. chunks = conv["reference"][chunk_num]["chunks"]
  393. for chunk in chunks:
  394. new_chunk = {
  395. "id": chunk.get("chunk_id", chunk.get("id")),
  396. "content": chunk.get("content_with_weight", chunk.get("content")),
  397. "document_id": chunk.get("doc_id", chunk.get("document_id")),
  398. "document_name": chunk.get("docnm_kwd", chunk.get("document_name")),
  399. "dataset_id": chunk.get("kb_id", chunk.get("dataset_id")),
  400. "image_id": chunk.get("image_id", chunk.get("img_id")),
  401. "positions": chunk.get("positions", chunk.get("position_int")),
  402. }
  403. chunk_list.append(new_chunk)
  404. chunk_num += 1
  405. messages[message_num]["reference"] = chunk_list
  406. message_num += 1
  407. del conv["reference"]
  408. return get_result(data=convs)
  409. @manager.route('/agents/<agent_id>/sessions', methods=['GET']) # noqa: F821
  410. @token_required
  411. def list_agent_session(tenant_id, agent_id):
  412. if not UserCanvasService.query(user_id=tenant_id, id=agent_id):
  413. return get_error_data_result(message=f"You don't own the agent {agent_id}.")
  414. id = request.args.get("id")
  415. user_id = request.args.get("user_id")
  416. page_number = int(request.args.get("page", 1))
  417. items_per_page = int(request.args.get("page_size", 30))
  418. orderby = request.args.get("orderby", "update_time")
  419. if request.args.get("desc") == "False" or request.args.get("desc") == "false":
  420. desc = False
  421. else:
  422. desc = True
  423. # dsl defaults to True in all cases except for False and false
  424. include_dsl = request.args.get("dsl") != "False" and request.args.get("dsl") != "false"
  425. convs = API4ConversationService.get_list(agent_id, tenant_id, page_number, items_per_page, orderby, desc, id,
  426. user_id, include_dsl)
  427. if not convs:
  428. return get_result(data=[])
  429. for conv in convs:
  430. conv['messages'] = conv.pop("message")
  431. infos = conv["messages"]
  432. for info in infos:
  433. if "prompt" in info:
  434. info.pop("prompt")
  435. conv["agent_id"] = conv.pop("dialog_id")
  436. if conv["reference"]:
  437. messages = conv["messages"]
  438. message_num = 0
  439. chunk_num = 0
  440. while message_num < len(messages):
  441. if message_num != 0 and messages[message_num]["role"] != "user":
  442. chunk_list = []
  443. if "chunks" in conv["reference"][chunk_num]:
  444. chunks = conv["reference"][chunk_num]["chunks"]
  445. for chunk in chunks:
  446. new_chunk = {
  447. "id": chunk.get("chunk_id", chunk.get("id")),
  448. "content": chunk.get("content_with_weight", chunk.get("content")),
  449. "document_id": chunk.get("doc_id", chunk.get("document_id")),
  450. "document_name": chunk.get("docnm_kwd", chunk.get("document_name")),
  451. "dataset_id": chunk.get("kb_id", chunk.get("dataset_id")),
  452. "image_id": chunk.get("image_id", chunk.get("img_id")),
  453. "positions": chunk.get("positions", chunk.get("position_int")),
  454. }
  455. chunk_list.append(new_chunk)
  456. chunk_num += 1
  457. messages[message_num]["reference"] = chunk_list
  458. message_num += 1
  459. del conv["reference"]
  460. return get_result(data=convs)
  461. @manager.route('/chats/<chat_id>/sessions', methods=["DELETE"]) # noqa: F821
  462. @token_required
  463. def delete(tenant_id, chat_id):
  464. if not DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
  465. return get_error_data_result(message="You don't own the chat")
  466. req = request.json
  467. convs = ConversationService.query(dialog_id=chat_id)
  468. if not req:
  469. ids = None
  470. else:
  471. ids = req.get("ids")
  472. if not ids:
  473. conv_list = []
  474. for conv in convs:
  475. conv_list.append(conv.id)
  476. else:
  477. conv_list = ids
  478. for id in conv_list:
  479. conv = ConversationService.query(id=id, dialog_id=chat_id)
  480. if not conv:
  481. return get_error_data_result(message="The chat doesn't own the session")
  482. ConversationService.delete_by_id(id)
  483. return get_result()
  484. @manager.route('/agents/<agent_id>/sessions', methods=["DELETE"]) # noqa: F821
  485. @token_required
  486. def delete_agent_session(tenant_id, agent_id):
  487. req = request.json
  488. cvs = UserCanvasService.query(user_id=tenant_id, id=agent_id)
  489. if not cvs:
  490. return get_error_data_result(f"You don't own the agent {agent_id}")
  491. convs = API4ConversationService.query(dialog_id=agent_id)
  492. if not convs:
  493. return get_error_data_result(f"Agent {agent_id} has no sessions")
  494. if not req:
  495. ids = None
  496. else:
  497. ids = req.get("ids")
  498. if not ids:
  499. conv_list = []
  500. for conv in convs:
  501. conv_list.append(conv.id)
  502. else:
  503. conv_list = ids
  504. for session_id in conv_list:
  505. conv = API4ConversationService.query(id=session_id, dialog_id=agent_id)
  506. if not conv:
  507. return get_error_data_result(f"The agent doesn't own the session ${session_id}")
  508. API4ConversationService.delete_by_id(session_id)
  509. return get_result()
  510. @manager.route('/sessions/ask', methods=['POST']) # noqa: F821
  511. @token_required
  512. def ask_about(tenant_id):
  513. req = request.json
  514. if not req.get("question"):
  515. return get_error_data_result("`question` is required.")
  516. if not req.get("dataset_ids"):
  517. return get_error_data_result("`dataset_ids` is required.")
  518. if not isinstance(req.get("dataset_ids"), list):
  519. return get_error_data_result("`dataset_ids` should be a list.")
  520. req["kb_ids"] = req.pop("dataset_ids")
  521. for kb_id in req["kb_ids"]:
  522. if not KnowledgebaseService.accessible(kb_id, tenant_id):
  523. return get_error_data_result(f"You don't own the dataset {kb_id}.")
  524. kbs = KnowledgebaseService.query(id=kb_id)
  525. kb = kbs[0]
  526. if kb.chunk_num == 0:
  527. return get_error_data_result(f"The dataset {kb_id} doesn't own parsed file")
  528. uid = tenant_id
  529. def stream():
  530. nonlocal req, uid
  531. try:
  532. for ans in ask(req["question"], req["kb_ids"], uid):
  533. yield "data:" + json.dumps({"code": 0, "message": "", "data": ans}, ensure_ascii=False) + "\n\n"
  534. except Exception as e:
  535. yield "data:" + json.dumps({"code": 500, "message": str(e),
  536. "data": {"answer": "**ERROR**: " + str(e), "reference": []}},
  537. ensure_ascii=False) + "\n\n"
  538. yield "data:" + json.dumps({"code": 0, "message": "", "data": True}, ensure_ascii=False) + "\n\n"
  539. resp = Response(stream(), mimetype="text/event-stream")
  540. resp.headers.add_header("Cache-control", "no-cache")
  541. resp.headers.add_header("Connection", "keep-alive")
  542. resp.headers.add_header("X-Accel-Buffering", "no")
  543. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  544. return resp
  545. @manager.route('/sessions/related_questions', methods=['POST']) # noqa: F821
  546. @token_required
  547. def related_questions(tenant_id):
  548. req = request.json
  549. if not req.get("question"):
  550. return get_error_data_result("`question` is required.")
  551. question = req["question"]
  552. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT)
  553. prompt = """
  554. Objective: To generate search terms related to the user's search keywords, helping users find more valuable information.
  555. Instructions:
  556. - Based on the keywords provided by the user, generate 5-10 related search terms.
  557. - Each search term should be directly or indirectly related to the keyword, guiding the user to find more valuable information.
  558. - Use common, general terms as much as possible, avoiding obscure words or technical jargon.
  559. - Keep the term length between 2-4 words, concise and clear.
  560. - DO NOT translate, use the language of the original keywords.
  561. ### Example:
  562. Keywords: Chinese football
  563. Related search terms:
  564. 1. Current status of Chinese football
  565. 2. Reform of Chinese football
  566. 3. Youth training of Chinese football
  567. 4. Chinese football in the Asian Cup
  568. 5. Chinese football in the World Cup
  569. Reason:
  570. - When searching, users often only use one or two keywords, making it difficult to fully express their information needs.
  571. - Generating related search terms can help users dig deeper into relevant information and improve search efficiency.
  572. - At the same time, related terms can also help search engines better understand user needs and return more accurate search results.
  573. """
  574. ans = chat_mdl.chat(prompt, [{"role": "user", "content": f"""
  575. Keywords: {question}
  576. Related search terms:
  577. """}], {"temperature": 0.9})
  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)