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.

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