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

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