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.

datasource_engine.py 8.4KB

6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. import json
  2. from collections.abc import Generator, Iterable
  3. from mimetypes import guess_type
  4. from typing import Any, Optional, cast
  5. from yarl import URL
  6. from core.app.entities.app_invoke_entities import InvokeFrom
  7. from core.callback_handler.workflow_tool_callback_handler import DifyWorkflowCallbackHandler
  8. from core.datasource.__base.datasource_plugin import DatasourcePlugin
  9. from core.datasource.entities.datasource_entities import (
  10. DatasourceInvokeMessage,
  11. DatasourceInvokeMessageBinary,
  12. )
  13. from core.file import FileType
  14. from core.file.models import FileTransferMethod
  15. from extensions.ext_database import db
  16. from models.enums import CreatedByRole
  17. from models.model import Message, MessageFile
  18. class DatasourceEngine:
  19. """
  20. Datasource runtime engine take care of the datasource executions.
  21. """
  22. @staticmethod
  23. def invoke_first_step(
  24. datasource: DatasourcePlugin,
  25. datasource_parameters: dict[str, Any],
  26. user_id: str,
  27. workflow_tool_callback: DifyWorkflowCallbackHandler,
  28. conversation_id: Optional[str] = None,
  29. app_id: Optional[str] = None,
  30. message_id: Optional[str] = None,
  31. ) -> Generator[DatasourceInvokeMessage, None, None]:
  32. """
  33. Workflow invokes the datasource with the given arguments.
  34. """
  35. try:
  36. # hit the callback handler
  37. workflow_tool_callback.on_datasource_start(datasource_name=datasource.entity.identity.name,
  38. datasource_inputs=datasource_parameters)
  39. if datasource.runtime and datasource.runtime.runtime_parameters:
  40. datasource_parameters = {**datasource.runtime.runtime_parameters, **datasource_parameters}
  41. response = datasource._invoke_first_step(
  42. user_id=user_id,
  43. datasource_parameters=datasource_parameters,
  44. conversation_id=conversation_id,
  45. app_id=app_id,
  46. message_id=message_id,
  47. )
  48. # hit the callback handler
  49. response = workflow_tool_callback.on_datasource_end(
  50. datasource_name=datasource.entity.identity.name,
  51. datasource_inputs=datasource_parameters,
  52. datasource_outputs=response,
  53. )
  54. return response
  55. except Exception as e:
  56. workflow_tool_callback.on_tool_error(e)
  57. raise e
  58. @staticmethod
  59. def invoke_second_step(
  60. datasource: DatasourcePlugin,
  61. datasource_parameters: dict[str, Any],
  62. user_id: str,
  63. workflow_tool_callback: DifyWorkflowCallbackHandler,
  64. ) -> Generator[DatasourceInvokeMessage, None, None]:
  65. """
  66. Workflow invokes the datasource with the given arguments.
  67. """
  68. try:
  69. response = datasource._invoke_second_step(
  70. user_id=user_id,
  71. datasource_parameters=datasource_parameters,
  72. )
  73. return response
  74. except Exception as e:
  75. workflow_tool_callback.on_tool_error(e)
  76. raise e
  77. @staticmethod
  78. def _convert_datasource_response_to_str(datasource_response: list[DatasourceInvokeMessage]) -> str:
  79. """
  80. Handle datasource response
  81. """
  82. result = ""
  83. for response in datasource_response:
  84. if response.type == DatasourceInvokeMessage.MessageType.TEXT:
  85. result += cast(DatasourceInvokeMessage.TextMessage, response.message).text
  86. elif response.type == DatasourceInvokeMessage.MessageType.LINK:
  87. result += (
  88. f"result link: {cast(DatasourceInvokeMessage.TextMessage, response.message).text}."
  89. + " please tell user to check it."
  90. )
  91. elif response.type in {DatasourceInvokeMessage.MessageType.IMAGE_LINK, DatasourceInvokeMessage.MessageType.IMAGE}:
  92. result += (
  93. "image has been created and sent to user already, "
  94. + "you do not need to create it, just tell the user to check it now."
  95. )
  96. elif response.type == DatasourceInvokeMessage.MessageType.JSON:
  97. result = json.dumps(
  98. cast(DatasourceInvokeMessage.JsonMessage, response.message).json_object, ensure_ascii=False
  99. )
  100. else:
  101. result += str(response.message)
  102. return result
  103. @staticmethod
  104. def _extract_datasource_response_binary_and_text(
  105. datasource_response: list[DatasourceInvokeMessage],
  106. ) -> Generator[DatasourceInvokeMessageBinary, None, None]:
  107. """
  108. Extract datasource response binary
  109. """
  110. for response in datasource_response:
  111. if response.type in {DatasourceInvokeMessage.MessageType.IMAGE_LINK, DatasourceInvokeMessage.MessageType.IMAGE}:
  112. mimetype = None
  113. if not response.meta:
  114. raise ValueError("missing meta data")
  115. if response.meta.get("mime_type"):
  116. mimetype = response.meta.get("mime_type")
  117. else:
  118. try:
  119. url = URL(cast(DatasourceInvokeMessage.TextMessage, response.message).text)
  120. extension = url.suffix
  121. guess_type_result, _ = guess_type(f"a{extension}")
  122. if guess_type_result:
  123. mimetype = guess_type_result
  124. except Exception:
  125. pass
  126. if not mimetype:
  127. mimetype = "image/jpeg"
  128. yield DatasourceInvokeMessageBinary(
  129. mimetype=response.meta.get("mime_type", "image/jpeg"),
  130. url=cast(DatasourceInvokeMessage.TextMessage, response.message).text,
  131. )
  132. elif response.type == DatasourceInvokeMessage.MessageType.BLOB:
  133. if not response.meta:
  134. raise ValueError("missing meta data")
  135. yield DatasourceInvokeMessageBinary(
  136. mimetype=response.meta.get("mime_type", "application/octet-stream"),
  137. url=cast(DatasourceInvokeMessage.TextMessage, response.message).text,
  138. )
  139. elif response.type == DatasourceInvokeMessage.MessageType.LINK:
  140. # check if there is a mime type in meta
  141. if response.meta and "mime_type" in response.meta:
  142. yield DatasourceInvokeMessageBinary(
  143. mimetype=response.meta.get("mime_type", "application/octet-stream")
  144. if response.meta
  145. else "application/octet-stream",
  146. url=cast(DatasourceInvokeMessage.TextMessage, response.message).text,
  147. )
  148. @staticmethod
  149. def _create_message_files(
  150. datasource_messages: Iterable[DatasourceInvokeMessageBinary],
  151. agent_message: Message,
  152. invoke_from: InvokeFrom,
  153. user_id: str,
  154. ) -> list[str]:
  155. """
  156. Create message file
  157. :return: message file ids
  158. """
  159. result = []
  160. for message in datasource_messages:
  161. if "image" in message.mimetype:
  162. file_type = FileType.IMAGE
  163. elif "video" in message.mimetype:
  164. file_type = FileType.VIDEO
  165. elif "audio" in message.mimetype:
  166. file_type = FileType.AUDIO
  167. elif "text" in message.mimetype or "pdf" in message.mimetype:
  168. file_type = FileType.DOCUMENT
  169. else:
  170. file_type = FileType.CUSTOM
  171. # extract tool file id from url
  172. tool_file_id = message.url.split("/")[-1].split(".")[0]
  173. message_file = MessageFile(
  174. message_id=agent_message.id,
  175. type=file_type,
  176. transfer_method=FileTransferMethod.TOOL_FILE,
  177. belongs_to="assistant",
  178. url=message.url,
  179. upload_file_id=tool_file_id,
  180. created_by_role=(
  181. CreatedByRole.ACCOUNT
  182. if invoke_from in {InvokeFrom.EXPLORE, InvokeFrom.DEBUGGER}
  183. else CreatedByRole.END_USER
  184. ),
  185. created_by=user_id,
  186. )
  187. db.session.add(message_file)
  188. db.session.commit()
  189. db.session.refresh(message_file)
  190. result.append(message_file.id)
  191. db.session.close()
  192. return result