選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

canvas_service.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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 logging
  18. import time
  19. from uuid import uuid4
  20. from agent.canvas import Canvas
  21. from api.db import TenantPermission
  22. from api.db.db_models import DB, CanvasTemplate, User, UserCanvas, API4Conversation
  23. from api.db.services.api_service import API4ConversationService
  24. from api.db.services.common_service import CommonService
  25. from api.utils import get_uuid
  26. from api.utils.api_utils import get_data_openai
  27. import tiktoken
  28. from peewee import fn
  29. class CanvasTemplateService(CommonService):
  30. model = CanvasTemplate
  31. class UserCanvasService(CommonService):
  32. model = UserCanvas
  33. @classmethod
  34. @DB.connection_context()
  35. def get_list(cls, tenant_id,
  36. page_number, items_per_page, orderby, desc, id, title):
  37. agents = cls.model.select()
  38. if id:
  39. agents = agents.where(cls.model.id == id)
  40. if title:
  41. agents = agents.where(cls.model.title == title)
  42. agents = agents.where(cls.model.user_id == tenant_id)
  43. if desc:
  44. agents = agents.order_by(cls.model.getter_by(orderby).desc())
  45. else:
  46. agents = agents.order_by(cls.model.getter_by(orderby).asc())
  47. agents = agents.paginate(page_number, items_per_page)
  48. return list(agents.dicts())
  49. @classmethod
  50. @DB.connection_context()
  51. def get_by_tenant_id(cls, pid):
  52. try:
  53. fields = [
  54. cls.model.id,
  55. cls.model.avatar,
  56. cls.model.title,
  57. cls.model.dsl,
  58. cls.model.description,
  59. cls.model.permission,
  60. cls.model.update_time,
  61. cls.model.user_id,
  62. cls.model.create_time,
  63. cls.model.create_date,
  64. cls.model.update_date,
  65. User.nickname,
  66. User.avatar.alias('tenant_avatar'),
  67. ]
  68. agents = cls.model.select(*fields) \
  69. .join(User, on=(cls.model.user_id == User.id)) \
  70. .where(cls.model.id == pid)
  71. # obj = cls.model.query(id=pid)[0]
  72. return True, agents.dicts()[0]
  73. except Exception as e:
  74. logging.exception(e)
  75. return False, None
  76. @classmethod
  77. @DB.connection_context()
  78. def get_by_tenant_ids(cls, joined_tenant_ids, user_id,
  79. page_number, items_per_page,
  80. orderby, desc, keywords,
  81. ):
  82. fields = [
  83. cls.model.id,
  84. cls.model.avatar,
  85. cls.model.title,
  86. cls.model.dsl,
  87. cls.model.description,
  88. cls.model.permission,
  89. User.nickname,
  90. User.avatar.alias('tenant_avatar'),
  91. cls.model.update_time
  92. ]
  93. if keywords:
  94. agents = cls.model.select(*fields).join(User, on=(cls.model.user_id == User.id)).where(
  95. ((cls.model.user_id.in_(joined_tenant_ids) & (cls.model.permission ==
  96. TenantPermission.TEAM.value)) | (
  97. cls.model.user_id == user_id)),
  98. (fn.LOWER(cls.model.title).contains(keywords.lower()))
  99. )
  100. else:
  101. agents = cls.model.select(*fields).join(User, on=(cls.model.user_id == User.id)).where(
  102. ((cls.model.user_id.in_(joined_tenant_ids) & (cls.model.permission ==
  103. TenantPermission.TEAM.value)) | (
  104. cls.model.user_id == user_id))
  105. )
  106. if desc:
  107. agents = agents.order_by(cls.model.getter_by(orderby).desc())
  108. else:
  109. agents = agents.order_by(cls.model.getter_by(orderby).asc())
  110. count = agents.count()
  111. agents = agents.paginate(page_number, items_per_page)
  112. return list(agents.dicts()), count
  113. @classmethod
  114. @DB.connection_context()
  115. def accessible(cls, canvas_id, tenant_id):
  116. from api.db.services.user_service import UserTenantService
  117. e, c = UserCanvasService.get_by_tenant_id(canvas_id)
  118. if not e:
  119. return False
  120. tids = [t.tenant_id for t in UserTenantService.query(user_id=tenant_id)]
  121. if c["user_id"] != canvas_id and c["user_id"] not in tids:
  122. return False
  123. return True
  124. def completion(tenant_id, agent_id, session_id=None, **kwargs):
  125. query = kwargs.get("query", "") or kwargs.get("question", "")
  126. files = kwargs.get("files", [])
  127. inputs = kwargs.get("inputs", {})
  128. user_id = kwargs.get("user_id", "")
  129. if session_id:
  130. e, conv = API4ConversationService.get_by_id(session_id)
  131. assert e, "Session not found!"
  132. if not conv.message:
  133. conv.message = []
  134. if not isinstance(conv.dsl, str):
  135. conv.dsl = json.dumps(conv.dsl, ensure_ascii=False)
  136. canvas = Canvas(conv.dsl, tenant_id, agent_id)
  137. else:
  138. e, cvs = UserCanvasService.get_by_id(agent_id)
  139. assert e, "Agent not found."
  140. assert cvs.user_id == tenant_id, "You do not own the agent."
  141. if not isinstance(cvs.dsl, str):
  142. cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False)
  143. session_id=get_uuid()
  144. canvas = Canvas(cvs.dsl, tenant_id, agent_id)
  145. canvas.reset()
  146. conv = {
  147. "id": session_id,
  148. "dialog_id": cvs.id,
  149. "user_id": user_id,
  150. "message": [],
  151. "source": "agent",
  152. "dsl": cvs.dsl
  153. }
  154. API4ConversationService.save(**conv)
  155. conv = API4Conversation(**conv)
  156. message_id = str(uuid4())
  157. conv.message.append({
  158. "role": "user",
  159. "content": query,
  160. "id": message_id
  161. })
  162. txt = ""
  163. for ans in canvas.run(query=query, files=files, user_id=user_id, inputs=inputs):
  164. ans["session_id"] = session_id
  165. if ans["event"] == "message":
  166. txt += ans["data"]["content"]
  167. yield "data:" + json.dumps(ans, ensure_ascii=False) + "\n\n"
  168. conv.message.append({"role": "assistant", "content": txt, "created_at": time.time(), "id": message_id})
  169. conv.reference = canvas.get_reference()
  170. conv.errors = canvas.error
  171. conv.dsl = str(canvas)
  172. conv = conv.to_dict()
  173. API4ConversationService.append_message(conv["id"], conv)
  174. def completionOpenAI(tenant_id, agent_id, question, session_id=None, stream=True, **kwargs):
  175. tiktokenenc = tiktoken.get_encoding("cl100k_base")
  176. prompt_tokens = len(tiktokenenc.encode(str(question)))
  177. user_id = kwargs.get("user_id", "")
  178. if stream:
  179. completion_tokens = 0
  180. try:
  181. for ans in completion(
  182. tenant_id=tenant_id,
  183. agent_id=agent_id,
  184. session_id=session_id,
  185. query=question,
  186. user_id=user_id,
  187. **kwargs
  188. ):
  189. if isinstance(ans, str):
  190. try:
  191. ans = json.loads(ans[5:]) # remove "data:"
  192. except Exception as e:
  193. logging.exception(f"Agent OpenAI-Compatible completionOpenAI parse answer failed: {e}")
  194. continue
  195. if ans.get("event") != "message":
  196. continue
  197. content_piece = ans["data"]["content"]
  198. completion_tokens += len(tiktokenenc.encode(content_piece))
  199. yield "data: " + json.dumps(
  200. get_data_openai(
  201. id=session_id or str(uuid4()),
  202. model=agent_id,
  203. content=content_piece,
  204. prompt_tokens=prompt_tokens,
  205. completion_tokens=completion_tokens,
  206. stream=True
  207. ),
  208. ensure_ascii=False
  209. ) + "\n\n"
  210. yield "data: [DONE]\n\n"
  211. except Exception as e:
  212. yield "data: " + json.dumps(
  213. get_data_openai(
  214. id=session_id or str(uuid4()),
  215. model=agent_id,
  216. content=f"**ERROR**: {str(e)}",
  217. finish_reason="stop",
  218. prompt_tokens=prompt_tokens,
  219. completion_tokens=len(tiktokenenc.encode(f"**ERROR**: {str(e)}")),
  220. stream=True
  221. ),
  222. ensure_ascii=False
  223. ) + "\n\n"
  224. yield "data: [DONE]\n\n"
  225. else:
  226. try:
  227. all_content = ""
  228. for ans in completion(
  229. tenant_id=tenant_id,
  230. agent_id=agent_id,
  231. session_id=session_id,
  232. query=question,
  233. user_id=user_id,
  234. **kwargs
  235. ):
  236. if isinstance(ans, str):
  237. ans = json.loads(ans[5:])
  238. if ans.get("event") != "message":
  239. continue
  240. all_content += ans["data"]["content"]
  241. completion_tokens = len(tiktokenenc.encode(all_content))
  242. yield get_data_openai(
  243. id=session_id or str(uuid4()),
  244. model=agent_id,
  245. prompt_tokens=prompt_tokens,
  246. completion_tokens=completion_tokens,
  247. content=all_content,
  248. finish_reason="stop",
  249. param=None
  250. )
  251. except Exception as e:
  252. yield get_data_openai(
  253. id=session_id or str(uuid4()),
  254. model=agent_id,
  255. prompt_tokens=prompt_tokens,
  256. completion_tokens=len(tiktokenenc.encode(f"**ERROR**: {str(e)}")),
  257. content=f"**ERROR**: {str(e)}",
  258. finish_reason="stop",
  259. param=None
  260. )