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.

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