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.

canvas_service.py 6.6KB

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