Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

session.py 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  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. import tiktoken
  20. from flask import Response, jsonify, request
  21. from api.db.services.conversation_service import ConversationService, iframe_completion
  22. from api.db.services.conversation_service import completion as rag_completion
  23. from api.db.services.canvas_service import completion as agent_completion, completionOpenAI
  24. from agent.canvas import Canvas
  25. from api.db import LLMType, 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, ask, chat
  30. from api.db.services.file_service import FileService
  31. from api.db.services.knowledgebase_service import KnowledgebaseService
  32. from api.utils import get_uuid
  33. from api.utils.api_utils import get_result, token_required, get_data_openai, get_error_data_result, validate_request
  34. from api.db.services.llm_service import LLMBundle
  35. @manager.route("/chats/<chat_id>/sessions", methods=["POST"]) # noqa: F821
  36. @token_required
  37. def create(tenant_id, chat_id):
  38. req = request.json
  39. req["dialog_id"] = chat_id
  40. dia = DialogService.query(tenant_id=tenant_id, id=req["dialog_id"], status=StatusEnum.VALID.value)
  41. if not dia:
  42. return get_error_data_result(message="You do not own the assistant.")
  43. conv = {
  44. "id": get_uuid(),
  45. "dialog_id": req["dialog_id"],
  46. "name": req.get("name", "New session"),
  47. "message": [{"role": "assistant", "content": dia[0].prompt_config.get("prologue")}],
  48. "user_id": req.get("user_id", ""),
  49. }
  50. if not conv.get("name"):
  51. return get_error_data_result(message="`name` can not be empty.")
  52. ConversationService.save(**conv)
  53. e, conv = ConversationService.get_by_id(conv["id"])
  54. if not e:
  55. return get_error_data_result(message="Fail to create a session!")
  56. conv = conv.to_dict()
  57. conv["messages"] = conv.pop("message")
  58. conv["chat_id"] = conv.pop("dialog_id")
  59. del conv["reference"]
  60. return get_result(data=conv)
  61. @manager.route("/agents/<agent_id>/sessions", methods=["POST"]) # noqa: F821
  62. @token_required
  63. def create_agent_session(tenant_id, agent_id):
  64. req = request.json
  65. if not request.is_json:
  66. req = request.form
  67. files = request.files
  68. user_id = request.args.get("user_id", "")
  69. e, cvs = UserCanvasService.get_by_id(agent_id)
  70. if not e:
  71. return get_error_data_result("Agent not found.")
  72. if not UserCanvasService.query(user_id=tenant_id, id=agent_id):
  73. return get_error_data_result("You cannot access the agent.")
  74. if not isinstance(cvs.dsl, str):
  75. cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False)
  76. canvas = Canvas(cvs.dsl, tenant_id)
  77. canvas.reset()
  78. query = canvas.get_preset_param()
  79. if query:
  80. for ele in query:
  81. if not ele["optional"]:
  82. if ele["type"] == "file":
  83. if files is None or not files.get(ele["key"]):
  84. return get_error_data_result(f"`{ele['key']}` with type `{ele['type']}` is required")
  85. upload_file = files.get(ele["key"])
  86. file_content = FileService.parse_docs([upload_file], user_id)
  87. file_name = upload_file.filename
  88. ele["value"] = file_name + "\n" + file_content
  89. else:
  90. if req is None or not req.get(ele["key"]):
  91. return get_error_data_result(f"`{ele['key']}` with type `{ele['type']}` is required")
  92. ele["value"] = req[ele["key"]]
  93. else:
  94. if ele["type"] == "file":
  95. if files is not None and files.get(ele["key"]):
  96. upload_file = files.get(ele["key"])
  97. file_content = FileService.parse_docs([upload_file], user_id)
  98. file_name = upload_file.filename
  99. ele["value"] = file_name + "\n" + file_content
  100. else:
  101. if "value" in ele:
  102. ele.pop("value")
  103. else:
  104. if req is not None and req.get(ele["key"]):
  105. ele["value"] = req[ele["key"]]
  106. else:
  107. if "value" in ele:
  108. ele.pop("value")
  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_openai/<agent_id>/chat/completions', methods=['POST']) # noqa: F821
  313. @validate_request("model", "messages") # noqa: F821
  314. @token_required
  315. def agents_completion_openai_compatibility (tenant_id, agent_id):
  316. req = request.json
  317. tiktokenenc = tiktoken.get_encoding("cl100k_base")
  318. messages = req.get("messages", [])
  319. if not messages:
  320. return get_error_data_result("You must provide at least one message.")
  321. if not UserCanvasService.query(user_id=tenant_id, id=agent_id):
  322. return get_error_data_result(f"You don't own the agent {agent_id}")
  323. filtered_messages = [m for m in messages if m["role"] in ["user", "assistant"]]
  324. prompt_tokens = sum(len(tiktokenenc.encode(m["content"])) for m in filtered_messages)
  325. if not filtered_messages:
  326. return jsonify(get_data_openai(
  327. id=agent_id,
  328. content="No valid messages found (user or assistant).",
  329. finish_reason="stop",
  330. model=req.get("model", ""),
  331. completion_tokens=len(tiktokenenc.encode("No valid messages found (user or assistant).")),
  332. prompt_tokens=prompt_tokens,
  333. ))
  334. # Get the last user message as the question
  335. question = next((m["content"] for m in reversed(messages) if m["role"] == "user"), "")
  336. if req.get("stream", True):
  337. return Response(completionOpenAI(tenant_id, agent_id, question, session_id=req.get("id", ""), stream=True), mimetype="text/event-stream")
  338. else:
  339. # For non-streaming, just return the response directly
  340. response = next(completionOpenAI(tenant_id, agent_id, question, session_id=req.get("id", ""), stream=False))
  341. return jsonify(response)
  342. @manager.route("/agents/<agent_id>/completions", methods=["POST"]) # noqa: F821
  343. @token_required
  344. def agent_completions(tenant_id, agent_id):
  345. req = request.json
  346. cvs = UserCanvasService.query(user_id=tenant_id, id=agent_id)
  347. if not cvs:
  348. return get_error_data_result(f"You don't own the agent {agent_id}")
  349. if req.get("session_id"):
  350. dsl = cvs[0].dsl
  351. if not isinstance(dsl, str):
  352. dsl = json.dumps(dsl)
  353. conv = API4ConversationService.query(id=req["session_id"], dialog_id=agent_id)
  354. if not conv:
  355. return get_error_data_result(f"You don't own the session {req['session_id']}")
  356. # If an update to UserCanvas is detected, update the API4Conversation.dsl
  357. sync_dsl = req.get("sync_dsl", False)
  358. if sync_dsl is True and cvs[0].update_time > conv[0].update_time:
  359. current_dsl = conv[0].dsl
  360. new_dsl = json.loads(dsl)
  361. state_fields = ["history", "messages", "path", "reference"]
  362. states = {field: current_dsl.get(field, []) for field in state_fields}
  363. current_dsl.update(new_dsl)
  364. current_dsl.update(states)
  365. API4ConversationService.update_by_id(req["session_id"], {"dsl": current_dsl})
  366. else:
  367. req["question"] = ""
  368. if req.get("stream", True):
  369. resp = Response(agent_completion(tenant_id, agent_id, **req), mimetype="text/event-stream")
  370. resp.headers.add_header("Cache-control", "no-cache")
  371. resp.headers.add_header("Connection", "keep-alive")
  372. resp.headers.add_header("X-Accel-Buffering", "no")
  373. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  374. return resp
  375. try:
  376. for answer in agent_completion(tenant_id, agent_id, **req):
  377. return get_result(data=answer)
  378. except Exception as e:
  379. return get_error_data_result(str(e))
  380. @manager.route("/chats/<chat_id>/sessions", methods=["GET"]) # noqa: F821
  381. @token_required
  382. def list_session(tenant_id, chat_id):
  383. if not DialogService.query(tenant_id=tenant_id, id=chat_id, status=StatusEnum.VALID.value):
  384. return get_error_data_result(message=f"You don't own the assistant {chat_id}.")
  385. id = request.args.get("id")
  386. name = request.args.get("name")
  387. page_number = int(request.args.get("page", 1))
  388. items_per_page = int(request.args.get("page_size", 30))
  389. orderby = request.args.get("orderby", "create_time")
  390. user_id = request.args.get("user_id")
  391. if request.args.get("desc") == "False" or request.args.get("desc") == "false":
  392. desc = False
  393. else:
  394. desc = True
  395. convs = ConversationService.get_list(chat_id, page_number, items_per_page, orderby, desc, id, name, user_id)
  396. if not convs:
  397. return get_result(data=[])
  398. for conv in convs:
  399. conv["messages"] = conv.pop("message")
  400. infos = conv["messages"]
  401. for info in infos:
  402. if "prompt" in info:
  403. info.pop("prompt")
  404. conv["chat_id"] = conv.pop("dialog_id")
  405. if conv["reference"]:
  406. messages = conv["messages"]
  407. message_num = 0
  408. chunk_num = 0
  409. while message_num < len(messages):
  410. if message_num != 0 and messages[message_num]["role"] != "user":
  411. chunk_list = []
  412. if "chunks" in conv["reference"][chunk_num]:
  413. chunks = conv["reference"][chunk_num]["chunks"]
  414. for chunk in chunks:
  415. new_chunk = {
  416. "id": chunk.get("chunk_id", chunk.get("id")),
  417. "content": chunk.get("content_with_weight", chunk.get("content")),
  418. "document_id": chunk.get("doc_id", chunk.get("document_id")),
  419. "document_name": chunk.get("docnm_kwd", chunk.get("document_name")),
  420. "dataset_id": chunk.get("kb_id", chunk.get("dataset_id")),
  421. "image_id": chunk.get("image_id", chunk.get("img_id")),
  422. "positions": chunk.get("positions", chunk.get("position_int")),
  423. }
  424. chunk_list.append(new_chunk)
  425. chunk_num += 1
  426. messages[message_num]["reference"] = chunk_list
  427. message_num += 1
  428. del conv["reference"]
  429. return get_result(data=convs)
  430. @manager.route("/agents/<agent_id>/sessions", methods=["GET"]) # noqa: F821
  431. @token_required
  432. def list_agent_session(tenant_id, agent_id):
  433. if not UserCanvasService.query(user_id=tenant_id, id=agent_id):
  434. return get_error_data_result(message=f"You don't own the agent {agent_id}.")
  435. id = request.args.get("id")
  436. user_id = request.args.get("user_id")
  437. page_number = int(request.args.get("page", 1))
  438. items_per_page = int(request.args.get("page_size", 30))
  439. orderby = request.args.get("orderby", "update_time")
  440. if request.args.get("desc") == "False" or request.args.get("desc") == "false":
  441. desc = False
  442. else:
  443. desc = True
  444. # dsl defaults to True in all cases except for False and false
  445. include_dsl = request.args.get("dsl") != "False" and request.args.get("dsl") != "false"
  446. convs = API4ConversationService.get_list(agent_id, tenant_id, page_number, items_per_page, orderby, desc, id, user_id, include_dsl)
  447. if not convs:
  448. return get_result(data=[])
  449. for conv in convs:
  450. conv["messages"] = conv.pop("message")
  451. infos = conv["messages"]
  452. for info in infos:
  453. if "prompt" in info:
  454. info.pop("prompt")
  455. conv["agent_id"] = conv.pop("dialog_id")
  456. if conv["reference"]:
  457. messages = conv["messages"]
  458. message_num = 0
  459. chunk_num = 0
  460. while message_num < len(messages):
  461. if message_num != 0 and messages[message_num]["role"] != "user":
  462. chunk_list = []
  463. if "chunks" in conv["reference"][chunk_num]:
  464. chunks = conv["reference"][chunk_num]["chunks"]
  465. for chunk in chunks:
  466. new_chunk = {
  467. "id": chunk.get("chunk_id", chunk.get("id")),
  468. "content": chunk.get("content_with_weight", chunk.get("content")),
  469. "document_id": chunk.get("doc_id", chunk.get("document_id")),
  470. "document_name": chunk.get("docnm_kwd", chunk.get("document_name")),
  471. "dataset_id": chunk.get("kb_id", chunk.get("dataset_id")),
  472. "image_id": chunk.get("image_id", chunk.get("img_id")),
  473. "positions": chunk.get("positions", chunk.get("position_int")),
  474. }
  475. chunk_list.append(new_chunk)
  476. chunk_num += 1
  477. messages[message_num]["reference"] = chunk_list
  478. message_num += 1
  479. del conv["reference"]
  480. return get_result(data=convs)
  481. @manager.route("/chats/<chat_id>/sessions", methods=["DELETE"]) # noqa: F821
  482. @token_required
  483. def delete(tenant_id, chat_id):
  484. if not DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
  485. return get_error_data_result(message="You don't own the chat")
  486. req = request.json
  487. convs = ConversationService.query(dialog_id=chat_id)
  488. if not req:
  489. ids = None
  490. else:
  491. ids = req.get("ids")
  492. if not ids:
  493. conv_list = []
  494. for conv in convs:
  495. conv_list.append(conv.id)
  496. else:
  497. conv_list = ids
  498. for id in conv_list:
  499. conv = ConversationService.query(id=id, dialog_id=chat_id)
  500. if not conv:
  501. return get_error_data_result(message="The chat doesn't own the session")
  502. ConversationService.delete_by_id(id)
  503. return get_result()
  504. @manager.route("/agents/<agent_id>/sessions", methods=["DELETE"]) # noqa: F821
  505. @token_required
  506. def delete_agent_session(tenant_id, agent_id):
  507. req = request.json
  508. cvs = UserCanvasService.query(user_id=tenant_id, id=agent_id)
  509. if not cvs:
  510. return get_error_data_result(f"You don't own the agent {agent_id}")
  511. convs = API4ConversationService.query(dialog_id=agent_id)
  512. if not convs:
  513. return get_error_data_result(f"Agent {agent_id} has no sessions")
  514. if not req:
  515. ids = None
  516. else:
  517. ids = req.get("ids")
  518. if not ids:
  519. conv_list = []
  520. for conv in convs:
  521. conv_list.append(conv.id)
  522. else:
  523. conv_list = ids
  524. for session_id in conv_list:
  525. conv = API4ConversationService.query(id=session_id, dialog_id=agent_id)
  526. if not conv:
  527. return get_error_data_result(f"The agent doesn't own the session ${session_id}")
  528. API4ConversationService.delete_by_id(session_id)
  529. return get_result()
  530. @manager.route("/sessions/ask", methods=["POST"]) # noqa: F821
  531. @token_required
  532. def ask_about(tenant_id):
  533. req = request.json
  534. if not req.get("question"):
  535. return get_error_data_result("`question` is required.")
  536. if not req.get("dataset_ids"):
  537. return get_error_data_result("`dataset_ids` is required.")
  538. if not isinstance(req.get("dataset_ids"), list):
  539. return get_error_data_result("`dataset_ids` should be a list.")
  540. req["kb_ids"] = req.pop("dataset_ids")
  541. for kb_id in req["kb_ids"]:
  542. if not KnowledgebaseService.accessible(kb_id, tenant_id):
  543. return get_error_data_result(f"You don't own the dataset {kb_id}.")
  544. kbs = KnowledgebaseService.query(id=kb_id)
  545. kb = kbs[0]
  546. if kb.chunk_num == 0:
  547. return get_error_data_result(f"The dataset {kb_id} doesn't own parsed file")
  548. uid = tenant_id
  549. def stream():
  550. nonlocal req, uid
  551. try:
  552. for ans in ask(req["question"], req["kb_ids"], uid):
  553. yield "data:" + json.dumps({"code": 0, "message": "", "data": ans}, ensure_ascii=False) + "\n\n"
  554. except Exception as e:
  555. yield "data:" + json.dumps({"code": 500, "message": str(e), "data": {"answer": "**ERROR**: " + str(e), "reference": []}}, ensure_ascii=False) + "\n\n"
  556. yield "data:" + json.dumps({"code": 0, "message": "", "data": True}, ensure_ascii=False) + "\n\n"
  557. resp = Response(stream(), mimetype="text/event-stream")
  558. resp.headers.add_header("Cache-control", "no-cache")
  559. resp.headers.add_header("Connection", "keep-alive")
  560. resp.headers.add_header("X-Accel-Buffering", "no")
  561. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  562. return resp
  563. @manager.route("/sessions/related_questions", methods=["POST"]) # noqa: F821
  564. @token_required
  565. def related_questions(tenant_id):
  566. req = request.json
  567. if not req.get("question"):
  568. return get_error_data_result("`question` is required.")
  569. question = req["question"]
  570. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT)
  571. prompt = """
  572. Objective: To generate search terms related to the user's search keywords, helping users find more valuable information.
  573. Instructions:
  574. - Based on the keywords provided by the user, generate 5-10 related search terms.
  575. - Each search term should be directly or indirectly related to the keyword, guiding the user to find more valuable information.
  576. - Use common, general terms as much as possible, avoiding obscure words or technical jargon.
  577. - Keep the term length between 2-4 words, concise and clear.
  578. - DO NOT translate, use the language of the original keywords.
  579. ### Example:
  580. Keywords: Chinese football
  581. Related search terms:
  582. 1. Current status of Chinese football
  583. 2. Reform of Chinese football
  584. 3. Youth training of Chinese football
  585. 4. Chinese football in the Asian Cup
  586. 5. Chinese football in the World Cup
  587. Reason:
  588. - When searching, users often only use one or two keywords, making it difficult to fully express their information needs.
  589. - Generating related search terms can help users dig deeper into relevant information and improve search efficiency.
  590. - At the same time, related terms can also help search engines better understand user needs and return more accurate search results.
  591. """
  592. ans = chat_mdl.chat(
  593. prompt,
  594. [
  595. {
  596. "role": "user",
  597. "content": f"""
  598. Keywords: {question}
  599. Related search terms:
  600. """,
  601. }
  602. ],
  603. {"temperature": 0.9},
  604. )
  605. return get_result(data=[re.sub(r"^[0-9]\. ", "", a) for a in ans.split("\n") if re.match(r"^[0-9]\. ", a)])
  606. @manager.route("/chatbots/<dialog_id>/completions", methods=["POST"]) # noqa: F821
  607. def chatbot_completions(dialog_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(iframe_completion(dialog_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 iframe_completion(dialog_id, **req):
  626. return get_result(data=answer)
  627. @manager.route("/agentbots/<agent_id>/completions", methods=["POST"]) # noqa: F821
  628. def agent_bot_completions(agent_id):
  629. req = request.json
  630. token = request.headers.get("Authorization").split()
  631. if len(token) != 2:
  632. return get_error_data_result(message='Authorization is not valid!"')
  633. token = token[1]
  634. objs = APIToken.query(beta=token)
  635. if not objs:
  636. return get_error_data_result(message='Authentication error: API key is invalid!"')
  637. if "quote" not in req:
  638. req["quote"] = False
  639. if req.get("stream", True):
  640. resp = Response(agent_completion(objs[0].tenant_id, agent_id, **req), mimetype="text/event-stream")
  641. resp.headers.add_header("Cache-control", "no-cache")
  642. resp.headers.add_header("Connection", "keep-alive")
  643. resp.headers.add_header("X-Accel-Buffering", "no")
  644. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  645. return resp
  646. for answer in agent_completion(objs[0].tenant_id, agent_id, **req):
  647. return get_result(data=answer)