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

session.py 29KB

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