You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

session.py 35KB

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