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.5KB

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