Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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 re
  17. import json
  18. import time
  19. from api.db import LLMType
  20. from api.db.services.conversation_service import ConversationService, iframe_completion
  21. from api.db.services.conversation_service import completion as rag_completion
  22. from api.db.services.canvas_service import completion as agent_completion
  23. from api.db.services.dialog_service import ask, chat
  24. from agent.canvas import Canvas
  25. from api.db import 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
  30. from api.db.services.knowledgebase_service import KnowledgebaseService
  31. from api.utils import get_uuid
  32. from api.utils.api_utils import get_error_data_result, validate_request
  33. from api.utils.api_utils import get_result, token_required
  34. from api.db.services.llm_service import LLMBundle
  35. from api.db.services.file_service import FileService
  36. from flask import jsonify, request, Response
  37. @manager.route('/chats/<chat_id>/sessions', methods=['POST']) # noqa: F821
  38. @token_required
  39. def create(tenant_id, chat_id):
  40. req = request.json
  41. req["dialog_id"] = chat_id
  42. dia = DialogService.query(tenant_id=tenant_id, id=req["dialog_id"], status=StatusEnum.VALID.value)
  43. if not dia:
  44. return get_error_data_result(message="You do not own the assistant.")
  45. conv = {
  46. "id": get_uuid(),
  47. "dialog_id": req["dialog_id"],
  48. "name": req.get("name", "New session"),
  49. "message": [{"role": "assistant", "content": dia[0].prompt_config.get("prologue")}],
  50. "user_id": req.get("user_id", "")
  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. req = request.json
  67. if not request.is_json:
  68. req = request.form
  69. files = request.files
  70. user_id = request.args.get('user_id', '')
  71. e, cvs = UserCanvasService.get_by_id(agent_id)
  72. if not e:
  73. return get_error_data_result("Agent not found.")
  74. if not UserCanvasService.query(user_id=tenant_id, id=agent_id):
  75. return get_error_data_result("You cannot access the agent.")
  76. if not isinstance(cvs.dsl, str):
  77. cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False)
  78. canvas = Canvas(cvs.dsl, tenant_id)
  79. canvas.reset()
  80. query = canvas.get_preset_param()
  81. if query:
  82. for ele in query:
  83. if not ele["optional"]:
  84. if ele["type"] == "file":
  85. if files is None or not files.get(ele["key"]):
  86. return get_error_data_result(f"`{ele['key']}` with type `{ele['type']}` is required")
  87. upload_file = files.get(ele["key"])
  88. file_content = FileService.parse_docs([upload_file], user_id)
  89. file_name = upload_file.filename
  90. ele["value"] = file_name + "\n" + file_content
  91. else:
  92. if req is None or not req.get(ele["key"]):
  93. return get_error_data_result(f"`{ele['key']}` with type `{ele['type']}` is required")
  94. ele["value"] = req[ele["key"]]
  95. else:
  96. if ele["type"] == "file":
  97. if files is not None and files.get(ele["key"]):
  98. upload_file = files.get(ele["key"])
  99. file_content = FileService.parse_docs([upload_file], user_id)
  100. file_name = upload_file.filename
  101. ele["value"] = file_name + "\n" + file_content
  102. else:
  103. if "value" in ele:
  104. ele.pop("value")
  105. else:
  106. if req is not None and req.get(ele["key"]):
  107. ele["value"] = req[ele['key']]
  108. else:
  109. if "value" in ele:
  110. ele.pop("value")
  111. else:
  112. for ans in canvas.run(stream=False):
  113. pass
  114. cvs.dsl = json.loads(str(canvas))
  115. conv = {
  116. "id": get_uuid(),
  117. "dialog_id": cvs.id,
  118. "user_id": user_id,
  119. "message": [{"role": "assistant", "content": canvas.get_prologue()}],
  120. "source": "agent",
  121. "dsl": cvs.dsl
  122. }
  123. API4ConversationService.save(**conv)
  124. conv["agent_id"] = conv.pop("dialog_id")
  125. return get_result(data=conv)
  126. @manager.route('/chats/<chat_id>/sessions/<session_id>', methods=['PUT']) # noqa: F821
  127. @token_required
  128. def update(tenant_id, chat_id, session_id):
  129. req = request.json
  130. req["dialog_id"] = chat_id
  131. conv_id = session_id
  132. conv = ConversationService.query(id=conv_id, dialog_id=chat_id)
  133. if not conv:
  134. return get_error_data_result(message="Session does not exist")
  135. if not DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
  136. return get_error_data_result(message="You do not own the session")
  137. if "message" in req or "messages" in req:
  138. return get_error_data_result(message="`message` can not be change")
  139. if "reference" in req:
  140. return get_error_data_result(message="`reference` can not be change")
  141. if "name" in req and not req.get("name"):
  142. return get_error_data_result(message="`name` can not be empty.")
  143. if not ConversationService.update_by_id(conv_id, req):
  144. return get_error_data_result(message="Session updates error")
  145. return get_result()
  146. @manager.route('/chats/<chat_id>/completions', methods=['POST']) # noqa: F821
  147. @token_required
  148. def chat_completion(tenant_id, chat_id):
  149. req = request.json
  150. if not req:
  151. req = {"question": ""}
  152. if not req.get("session_id"):
  153. req["question"]=""
  154. if not DialogService.query(tenant_id=tenant_id, id=chat_id, status=StatusEnum.VALID.value):
  155. return get_error_data_result(f"You don't own the chat {chat_id}")
  156. if req.get("session_id"):
  157. if not ConversationService.query(id=req["session_id"], dialog_id=chat_id):
  158. return get_error_data_result(f"You don't own the session {req['session_id']}")
  159. if req.get("stream", True):
  160. resp = Response(rag_completion(tenant_id, chat_id, **req), mimetype="text/event-stream")
  161. resp.headers.add_header("Cache-control", "no-cache")
  162. resp.headers.add_header("Connection", "keep-alive")
  163. resp.headers.add_header("X-Accel-Buffering", "no")
  164. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  165. return resp
  166. else:
  167. answer = None
  168. for ans in rag_completion(tenant_id, chat_id, **req):
  169. answer = ans
  170. break
  171. return get_result(data=answer)
  172. @manager.route('chats_openai/<chat_id>/chat/completions', methods=['POST']) # noqa: F821
  173. @validate_request("model", "messages") # noqa: F821
  174. @token_required
  175. def chat_completion_openai_like(tenant_id, chat_id):
  176. """
  177. OpenAI-like chat completion API that simulates the behavior of OpenAI's completions endpoint.
  178. This function allows users to interact with a model and receive responses based on a series of historical messages.
  179. If `stream` is set to True (by default), the response will be streamed in chunks, mimicking the OpenAI-style API.
  180. Set `stream` to False explicitly, the response will be returned in a single complete answer.
  181. Example usage:
  182. curl -X POST https://ragflow_address.com/api/v1/chats_openai/<chat_id>/chat/completions \
  183. -H "Content-Type: application/json" \
  184. -H "Authorization: Bearer $RAGFLOW_API_KEY" \
  185. -d '{
  186. "model": "model",
  187. "messages": [{"role": "user", "content": "Say this is a test!"}],
  188. "stream": true
  189. }'
  190. Alternatively, you can use Python's `OpenAI` client:
  191. from openai import OpenAI
  192. model = "model"
  193. client = OpenAI(api_key="ragflow-api-key", base_url=f"http://ragflow_address/api/v1/chats_openai/<chat_id>")
  194. completion = client.chat.completions.create(
  195. model=model,
  196. messages=[
  197. {"role": "system", "content": "You are a helpful assistant."},
  198. {"role": "user", "content": "Who you are?"},
  199. {"role": "assistant", "content": "I am an AI assistant named..."},
  200. {"role": "user", "content": "Can you tell me how to install neovim"},
  201. ],
  202. stream=True
  203. )
  204. stream = True
  205. if stream:
  206. for chunk in completion:
  207. print(chunk)
  208. else:
  209. print(completion.choices[0].message.content)
  210. """
  211. req = request.json
  212. messages = req.get("messages", [])
  213. # To prevent empty [] input
  214. if len(messages) < 1:
  215. return get_error_data_result("You have to provide messages")
  216. dia = DialogService.query(tenant_id=tenant_id, id=chat_id, status=StatusEnum.VALID.value)
  217. if not dia:
  218. return get_error_data_result(f"You don't own the chat {chat_id}")
  219. dia = dia[0]
  220. # Filter system and assistant messages
  221. msg = None
  222. msg = [m for m in messages if m["role"] != "system" and (m["role"] != "assistant" or msg)]
  223. if req.get("stream", True):
  224. # The value for the usage field on all chunks except for the last one will be null.
  225. # The usage field on the last chunk contains token usage statistics for the entire request.
  226. # The choices field on the last chunk will always be an empty array [].
  227. def streamed_respose_generator(chat_id, dia, msg):
  228. token_used = 0
  229. response = {
  230. "id": f"chatcmpl-{chat_id}",
  231. "choices": [
  232. {
  233. "delta": {
  234. "content": "",
  235. "role": "assistant",
  236. "function_call": None,
  237. "tool_calls": None
  238. },
  239. "finish_reason": None,
  240. "index": 0,
  241. "logprobs": None
  242. }
  243. ],
  244. "created": int(time.time()),
  245. "model": "model",
  246. "object": "chat.completion.chunk",
  247. "system_fingerprint": "",
  248. "usage": None
  249. }
  250. try:
  251. for ans in chat(dia, msg, True):
  252. answer = ans["answer"]
  253. incremental = answer[token_used:]
  254. token_used += len(incremental)
  255. response["choices"][0]["delta"]["content"] = incremental
  256. yield f"data:{json.dumps(response, ensure_ascii=False)}\n\n".encode("utf-8")
  257. except Exception as e:
  258. response["choices"][0]["delta"]["content"] = "**ERROR**: " + str(e)
  259. yield f"data:{json.dumps(response, ensure_ascii=False)}\n\n".encode("utf-8")
  260. # The last chunck
  261. response["choices"][0]["delta"]["content"] = None
  262. response["choices"][0]["finish_reason"] = "stop"
  263. response["usage"] = {
  264. "prompt_tokens": len(msg),
  265. "completion_tokens": token_used,
  266. "total_tokens": len(msg) + token_used
  267. }
  268. yield f"data:{json.dumps(response, ensure_ascii=False)}\n\n".encode("utf-8")
  269. resp = Response(streamed_respose_generator(chat_id, dia, msg), mimetype="text/event-stream")
  270. resp.headers.add_header("Cache-control", "no-cache")
  271. resp.headers.add_header("Connection", "keep-alive")
  272. resp.headers.add_header("X-Accel-Buffering", "no")
  273. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  274. return resp
  275. else:
  276. answer = None
  277. for ans in chat(dia, msg, False):
  278. # focus answer content only
  279. answer = ans
  280. break
  281. response = {
  282. "id": f"chatcmpl-{chat_id}",
  283. "object": "chat.completion",
  284. "created": int(time.time()),
  285. "model": req.get("model", ""),
  286. "usage": {
  287. "prompt_tokens": len(messages),
  288. "completion_tokens": len(answer),
  289. "total_tokens": len(messages) + len(answer),
  290. "completion_tokens_details": {
  291. "reasoning_tokens": len(answer),
  292. "accepted_prediction_tokens": len(answer),
  293. "rejected_prediction_tokens": len(answer)
  294. }
  295. },
  296. "choices": [
  297. {
  298. "message": {
  299. "role": "assistant",
  300. "content": answer["answer"]
  301. },
  302. "logprobs": None,
  303. "finish_reason": "stop",
  304. "index": 0
  305. }
  306. ]
  307. }
  308. return jsonify(response)
  309. @manager.route('/agents/<agent_id>/completions', methods=['POST']) # noqa: F821
  310. @token_required
  311. def agent_completions(tenant_id, agent_id):
  312. req = request.json
  313. cvs = UserCanvasService.query(user_id=tenant_id, id=agent_id)
  314. if not cvs:
  315. return get_error_data_result(f"You don't own the agent {agent_id}")
  316. if req.get("session_id"):
  317. dsl = cvs[0].dsl
  318. if not isinstance(dsl, str):
  319. dsl = json.dumps(dsl)
  320. #canvas = Canvas(dsl, tenant_id)
  321. #if canvas.get_preset_param():
  322. # req["question"] = ""
  323. conv = API4ConversationService.query(id=req["session_id"], dialog_id=agent_id)
  324. if not conv:
  325. return get_error_data_result(f"You don't own the session {req['session_id']}")
  326. else:
  327. req["question"] = ""
  328. if req.get("stream", True):
  329. resp = Response(agent_completion(tenant_id, agent_id, **req), mimetype="text/event-stream")
  330. resp.headers.add_header("Cache-control", "no-cache")
  331. resp.headers.add_header("Connection", "keep-alive")
  332. resp.headers.add_header("X-Accel-Buffering", "no")
  333. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  334. return resp
  335. try:
  336. for answer in agent_completion(tenant_id, agent_id, **req):
  337. return get_result(data=answer)
  338. except Exception as e:
  339. return get_error_data_result(str(e))
  340. @manager.route('/chats/<chat_id>/sessions', methods=['GET']) # noqa: F821
  341. @token_required
  342. def list_session(tenant_id, chat_id):
  343. if not DialogService.query(tenant_id=tenant_id, id=chat_id, status=StatusEnum.VALID.value):
  344. return get_error_data_result(message=f"You don't own the assistant {chat_id}.")
  345. id = request.args.get("id")
  346. name = request.args.get("name")
  347. page_number = int(request.args.get("page", 1))
  348. items_per_page = int(request.args.get("page_size", 30))
  349. orderby = request.args.get("orderby", "create_time")
  350. user_id = request.args.get("user_id")
  351. if request.args.get("desc") == "False" or request.args.get("desc") == "false":
  352. desc = False
  353. else:
  354. desc = True
  355. convs = ConversationService.get_list(chat_id, page_number, items_per_page, orderby, desc, id, name, user_id)
  356. if not convs:
  357. return get_result(data=[])
  358. for conv in convs:
  359. conv['messages'] = conv.pop("message")
  360. infos = conv["messages"]
  361. for info in infos:
  362. if "prompt" in info:
  363. info.pop("prompt")
  364. conv["chat_id"] = conv.pop("dialog_id")
  365. if conv["reference"]:
  366. messages = conv["messages"]
  367. message_num = 0
  368. chunk_num = 0
  369. while message_num < len(messages):
  370. if message_num != 0 and messages[message_num]["role"] != "user":
  371. chunk_list = []
  372. if "chunks" in conv["reference"][chunk_num]:
  373. chunks = conv["reference"][chunk_num]["chunks"]
  374. for chunk in chunks:
  375. new_chunk = {
  376. "id": chunk.get("chunk_id", chunk.get("id")),
  377. "content": chunk.get("content_with_weight", chunk.get("content")),
  378. "document_id": chunk.get("doc_id", chunk.get("document_id")),
  379. "document_name": chunk.get("docnm_kwd", chunk.get("document_name")),
  380. "dataset_id": chunk.get("kb_id", chunk.get("dataset_id")),
  381. "image_id": chunk.get("image_id", chunk.get("img_id")),
  382. "positions": chunk.get("positions", chunk.get("position_int")),
  383. }
  384. chunk_list.append(new_chunk)
  385. chunk_num += 1
  386. messages[message_num]["reference"] = chunk_list
  387. message_num += 1
  388. del conv["reference"]
  389. return get_result(data=convs)
  390. @manager.route('/agents/<agent_id>/sessions', methods=['GET']) # noqa: F821
  391. @token_required
  392. def list_agent_session(tenant_id, agent_id):
  393. if not UserCanvasService.query(user_id=tenant_id, id=agent_id):
  394. return get_error_data_result(message=f"You don't own the agent {agent_id}.")
  395. id = request.args.get("id")
  396. user_id = request.args.get("user_id")
  397. page_number = int(request.args.get("page", 1))
  398. items_per_page = int(request.args.get("page_size", 30))
  399. orderby = request.args.get("orderby", "update_time")
  400. if request.args.get("desc") == "False" or request.args.get("desc") == "false":
  401. desc = False
  402. else:
  403. desc = True
  404. convs = API4ConversationService.get_list(agent_id, tenant_id, page_number, items_per_page, orderby, desc, id, user_id)
  405. if not convs:
  406. return get_result(data=[])
  407. for conv in convs:
  408. conv['messages'] = conv.pop("message")
  409. infos = conv["messages"]
  410. for info in infos:
  411. if "prompt" in info:
  412. info.pop("prompt")
  413. conv["agent_id"] = conv.pop("dialog_id")
  414. if conv["reference"]:
  415. messages = conv["messages"]
  416. message_num = 0
  417. chunk_num = 0
  418. while message_num < len(messages):
  419. if message_num != 0 and messages[message_num]["role"] != "user":
  420. chunk_list = []
  421. if "chunks" in conv["reference"][chunk_num]:
  422. chunks = conv["reference"][chunk_num]["chunks"]
  423. for chunk in chunks:
  424. new_chunk = {
  425. "id": chunk.get("chunk_id", chunk.get("id")),
  426. "content": chunk.get("content_with_weight", chunk.get("content")),
  427. "document_id": chunk.get("doc_id", chunk.get("document_id")),
  428. "document_name": chunk.get("docnm_kwd", chunk.get("document_name")),
  429. "dataset_id": chunk.get("kb_id", chunk.get("dataset_id")),
  430. "image_id": chunk.get("image_id", chunk.get("img_id")),
  431. "positions": chunk.get("positions", chunk.get("position_int")),
  432. }
  433. chunk_list.append(new_chunk)
  434. chunk_num += 1
  435. messages[message_num]["reference"] = chunk_list
  436. message_num += 1
  437. del conv["reference"]
  438. return get_result(data=convs)
  439. @manager.route('/chats/<chat_id>/sessions', methods=["DELETE"]) # noqa: F821
  440. @token_required
  441. def delete(tenant_id, chat_id):
  442. if not DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
  443. return get_error_data_result(message="You don't own the chat")
  444. req = request.json
  445. convs = ConversationService.query(dialog_id=chat_id)
  446. if not req:
  447. ids = None
  448. else:
  449. ids = req.get("ids")
  450. if not ids:
  451. conv_list = []
  452. for conv in convs:
  453. conv_list.append(conv.id)
  454. else:
  455. conv_list = ids
  456. for id in conv_list:
  457. conv = ConversationService.query(id=id, dialog_id=chat_id)
  458. if not conv:
  459. return get_error_data_result(message="The chat doesn't own the session")
  460. ConversationService.delete_by_id(id)
  461. return get_result()
  462. @manager.route('/sessions/ask', methods=['POST']) # noqa: F821
  463. @token_required
  464. def ask_about(tenant_id):
  465. req = request.json
  466. if not req.get("question"):
  467. return get_error_data_result("`question` is required.")
  468. if not req.get("dataset_ids"):
  469. return get_error_data_result("`dataset_ids` is required.")
  470. if not isinstance(req.get("dataset_ids"), list):
  471. return get_error_data_result("`dataset_ids` should be a list.")
  472. req["kb_ids"] = req.pop("dataset_ids")
  473. for kb_id in req["kb_ids"]:
  474. if not KnowledgebaseService.accessible(kb_id, tenant_id):
  475. return get_error_data_result(f"You don't own the dataset {kb_id}.")
  476. kbs = KnowledgebaseService.query(id=kb_id)
  477. kb = kbs[0]
  478. if kb.chunk_num == 0:
  479. return get_error_data_result(f"The dataset {kb_id} doesn't own parsed file")
  480. uid = tenant_id
  481. def stream():
  482. nonlocal req, uid
  483. try:
  484. for ans in ask(req["question"], req["kb_ids"], uid):
  485. yield "data:" + json.dumps({"code": 0, "message": "", "data": ans}, ensure_ascii=False) + "\n\n"
  486. except Exception as e:
  487. yield "data:" + json.dumps({"code": 500, "message": str(e),
  488. "data": {"answer": "**ERROR**: " + str(e), "reference": []}},
  489. ensure_ascii=False) + "\n\n"
  490. yield "data:" + json.dumps({"code": 0, "message": "", "data": True}, ensure_ascii=False) + "\n\n"
  491. resp = Response(stream(), mimetype="text/event-stream")
  492. resp.headers.add_header("Cache-control", "no-cache")
  493. resp.headers.add_header("Connection", "keep-alive")
  494. resp.headers.add_header("X-Accel-Buffering", "no")
  495. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  496. return resp
  497. @manager.route('/sessions/related_questions', methods=['POST']) # noqa: F821
  498. @token_required
  499. def related_questions(tenant_id):
  500. req = request.json
  501. if not req.get("question"):
  502. return get_error_data_result("`question` is required.")
  503. question = req["question"]
  504. chat_mdl = LLMBundle(tenant_id, LLMType.CHAT)
  505. prompt = """
  506. Objective: To generate search terms related to the user's search keywords, helping users find more valuable information.
  507. Instructions:
  508. - Based on the keywords provided by the user, generate 5-10 related search terms.
  509. - Each search term should be directly or indirectly related to the keyword, guiding the user to find more valuable information.
  510. - Use common, general terms as much as possible, avoiding obscure words or technical jargon.
  511. - Keep the term length between 2-4 words, concise and clear.
  512. - DO NOT translate, use the language of the original keywords.
  513. ### Example:
  514. Keywords: Chinese football
  515. Related search terms:
  516. 1. Current status of Chinese football
  517. 2. Reform of Chinese football
  518. 3. Youth training of Chinese football
  519. 4. Chinese football in the Asian Cup
  520. 5. Chinese football in the World Cup
  521. Reason:
  522. - When searching, users often only use one or two keywords, making it difficult to fully express their information needs.
  523. - Generating related search terms can help users dig deeper into relevant information and improve search efficiency.
  524. - At the same time, related terms can also help search engines better understand user needs and return more accurate search results.
  525. """
  526. ans = chat_mdl.chat(prompt, [{"role": "user", "content": f"""
  527. Keywords: {question}
  528. Related search terms:
  529. """}], {"temperature": 0.9})
  530. return get_result(data=[re.sub(r"^[0-9]\. ", "", a) for a in ans.split("\n") if re.match(r"^[0-9]\. ", a)])
  531. @manager.route('/chatbots/<dialog_id>/completions', methods=['POST']) # noqa: F821
  532. def chatbot_completions(dialog_id):
  533. req = request.json
  534. token = request.headers.get('Authorization').split()
  535. if len(token) != 2:
  536. return get_error_data_result(message='Authorization is not valid!"')
  537. token = token[1]
  538. objs = APIToken.query(beta=token)
  539. if not objs:
  540. return get_error_data_result(message='Authentication error: API key is invalid!"')
  541. if "quote" not in req:
  542. req["quote"] = False
  543. if req.get("stream", True):
  544. resp = Response(iframe_completion(dialog_id, **req), mimetype="text/event-stream")
  545. resp.headers.add_header("Cache-control", "no-cache")
  546. resp.headers.add_header("Connection", "keep-alive")
  547. resp.headers.add_header("X-Accel-Buffering", "no")
  548. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  549. return resp
  550. for answer in iframe_completion(dialog_id, **req):
  551. return get_result(data=answer)
  552. @manager.route('/agentbots/<agent_id>/completions', methods=['POST']) # noqa: F821
  553. def agent_bot_completions(agent_id):
  554. req = request.json
  555. token = request.headers.get('Authorization').split()
  556. if len(token) != 2:
  557. return get_error_data_result(message='Authorization is not valid!"')
  558. token = token[1]
  559. objs = APIToken.query(beta=token)
  560. if not objs:
  561. return get_error_data_result(message='Authentication error: API key is invalid!"')
  562. if "quote" not in req:
  563. req["quote"] = False
  564. if req.get("stream", True):
  565. resp = Response(agent_completion(objs[0].tenant_id, agent_id, **req), mimetype="text/event-stream")
  566. resp.headers.add_header("Cache-control", "no-cache")
  567. resp.headers.add_header("Connection", "keep-alive")
  568. resp.headers.add_header("X-Accel-Buffering", "no")
  569. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  570. return resp
  571. for answer in agent_completion(objs[0].tenant_id, agent_id, **req):
  572. return get_result(data=answer)