您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

canvas_service.py 6.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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 traceback
  18. from uuid import uuid4
  19. from agent.canvas import Canvas
  20. from api.db.db_models import DB, CanvasTemplate, UserCanvas, API4Conversation
  21. from api.db.services.api_service import API4ConversationService
  22. from api.db.services.common_service import CommonService
  23. from api.db.services.conversation_service import structure_answer
  24. from api.utils import get_uuid
  25. class CanvasTemplateService(CommonService):
  26. model = CanvasTemplate
  27. class UserCanvasService(CommonService):
  28. model = UserCanvas
  29. @classmethod
  30. @DB.connection_context()
  31. def get_list(cls, tenant_id,
  32. page_number, items_per_page, orderby, desc, id, title):
  33. agents = cls.model.select()
  34. if id:
  35. agents = agents.where(cls.model.id == id)
  36. if title:
  37. agents = agents.where(cls.model.title == title)
  38. agents = agents.where(cls.model.user_id == tenant_id)
  39. if desc:
  40. agents = agents.order_by(cls.model.getter_by(orderby).desc())
  41. else:
  42. agents = agents.order_by(cls.model.getter_by(orderby).asc())
  43. agents = agents.paginate(page_number, items_per_page)
  44. return list(agents.dicts())
  45. def completion(tenant_id, agent_id, question, session_id=None, stream=True, **kwargs):
  46. e, cvs = UserCanvasService.get_by_id(agent_id)
  47. assert e, "Agent not found."
  48. assert cvs.user_id == tenant_id, "You do not own the agent."
  49. if not isinstance(cvs.dsl,str):
  50. cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False)
  51. canvas = Canvas(cvs.dsl, tenant_id)
  52. canvas.reset()
  53. message_id = str(uuid4())
  54. if not session_id:
  55. query = canvas.get_preset_param()
  56. if query:
  57. for ele in query:
  58. if not ele["optional"]:
  59. if not kwargs.get(ele["key"]):
  60. assert False, f"`{ele['key']}` is required"
  61. ele["value"] = kwargs[ele["key"]]
  62. if ele["optional"]:
  63. if kwargs.get(ele["key"]):
  64. ele["value"] = kwargs[ele['key']]
  65. else:
  66. if "value" in ele:
  67. ele.pop("value")
  68. cvs.dsl = json.loads(str(canvas))
  69. temp_dsl = cvs.dsl
  70. UserCanvasService.update_by_id(agent_id, cvs.to_dict())
  71. else:
  72. temp_dsl = json.loads(cvs.dsl)
  73. session_id = get_uuid()
  74. conv = {
  75. "id": session_id,
  76. "dialog_id": cvs.id,
  77. "user_id": kwargs.get("user_id", ""),
  78. "source": "agent",
  79. "dsl": temp_dsl
  80. }
  81. API4ConversationService.save(**conv)
  82. conv = API4Conversation(**conv)
  83. else:
  84. e, conv = API4ConversationService.get_by_id(session_id)
  85. assert e, "Session not found!"
  86. canvas = Canvas(json.dumps(conv.dsl), tenant_id)
  87. canvas.messages.append({"role": "user", "content": question, "id": message_id})
  88. canvas.add_user_input(question)
  89. if not conv.message:
  90. conv.message = []
  91. conv.message.append({
  92. "role": "user",
  93. "content": question,
  94. "id": message_id
  95. })
  96. if not conv.reference:
  97. conv.reference = []
  98. conv.reference.append({"chunks": [], "doc_aggs": []})
  99. final_ans = {"reference": [], "content": ""}
  100. if stream:
  101. try:
  102. for ans in canvas.run(stream=stream):
  103. if ans.get("running_status"):
  104. yield "data:" + json.dumps({"code": 0, "message": "",
  105. "data": {"answer": ans["content"],
  106. "running_status": True}},
  107. ensure_ascii=False) + "\n\n"
  108. continue
  109. for k in ans.keys():
  110. final_ans[k] = ans[k]
  111. ans = {"answer": ans["content"], "reference": ans.get("reference", [])}
  112. ans = structure_answer(conv, ans, message_id, session_id)
  113. yield "data:" + json.dumps({"code": 0, "message": "", "data": ans},
  114. ensure_ascii=False) + "\n\n"
  115. canvas.messages.append({"role": "assistant", "content": final_ans["content"], "id": message_id})
  116. canvas.history.append(("assistant", final_ans["content"]))
  117. if final_ans.get("reference"):
  118. canvas.reference.append(final_ans["reference"])
  119. conv.dsl = json.loads(str(canvas))
  120. API4ConversationService.append_message(conv.id, conv.to_dict())
  121. except Exception as e:
  122. traceback.print_exc()
  123. conv.dsl = json.loads(str(canvas))
  124. API4ConversationService.append_message(conv.id, conv.to_dict())
  125. yield "data:" + json.dumps({"code": 500, "message": str(e),
  126. "data": {"answer": "**ERROR**: " + str(e), "reference": []}},
  127. ensure_ascii=False) + "\n\n"
  128. yield "data:" + json.dumps({"code": 0, "message": "", "data": True}, ensure_ascii=False) + "\n\n"
  129. else:
  130. for answer in canvas.run(stream=False):
  131. if answer.get("running_status"):
  132. continue
  133. final_ans["content"] = "\n".join(answer["content"]) if "content" in answer else ""
  134. canvas.messages.append({"role": "assistant", "content": final_ans["content"], "id": message_id})
  135. if final_ans.get("reference"):
  136. canvas.reference.append(final_ans["reference"])
  137. conv.dsl = json.loads(str(canvas))
  138. result = {"answer": final_ans["content"], "reference": final_ans.get("reference", [])}
  139. result = structure_answer(conv, result, message_id, session_id)
  140. API4ConversationService.append_message(conv.id, conv.to_dict())
  141. yield result
  142. break