app_invoke_entities.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. from collections.abc import Mapping, Sequence
  2. from enum import StrEnum
  3. from typing import Any, Optional
  4. from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validator
  5. from constants import UUID_NIL
  6. from core.app.app_config.entities import EasyUIBasedAppConfig, WorkflowUIBasedAppConfig
  7. from core.entities.provider_configuration import ProviderModelBundle
  8. from core.file import File, FileUploadConfig
  9. from core.model_runtime.entities.model_entities import AIModelEntity
  10. class InvokeFrom(StrEnum):
  11. """
  12. Invoke From.
  13. """
  14. # SERVICE_API indicates that this invocation is from an API call to Dify app.
  15. #
  16. # Description of service api in Dify docs:
  17. # https://docs.dify.ai/en/guides/application-publishing/developing-with-apis
  18. SERVICE_API = "service-api"
  19. # WEB_APP indicates that this invocation is from
  20. # the web app of the workflow (or chatflow).
  21. #
  22. # Description of web app in Dify docs:
  23. # https://docs.dify.ai/en/guides/application-publishing/launch-your-webapp-quickly/README
  24. WEB_APP = "web-app"
  25. # EXPLORE indicates that this invocation is from
  26. # the workflow (or chatflow) explore page.
  27. EXPLORE = "explore"
  28. # DEBUGGER indicates that this invocation is from
  29. # the workflow (or chatflow) edit page.
  30. DEBUGGER = "debugger"
  31. @classmethod
  32. def value_of(cls, value: str):
  33. """
  34. Get value of given mode.
  35. :param value: mode value
  36. :return: mode
  37. """
  38. for mode in cls:
  39. if mode.value == value:
  40. return mode
  41. raise ValueError(f"invalid invoke from value {value}")
  42. def to_source(self) -> str:
  43. """
  44. Get source of invoke from.
  45. :return: source
  46. """
  47. if self == InvokeFrom.WEB_APP:
  48. return "web_app"
  49. elif self == InvokeFrom.DEBUGGER:
  50. return "dev"
  51. elif self == InvokeFrom.EXPLORE:
  52. return "explore_app"
  53. elif self == InvokeFrom.SERVICE_API:
  54. return "api"
  55. return "dev"
  56. class ModelConfigWithCredentialsEntity(BaseModel):
  57. """
  58. Model Config With Credentials Entity.
  59. """
  60. provider: str
  61. model: str
  62. model_schema: AIModelEntity
  63. mode: str
  64. provider_model_bundle: ProviderModelBundle
  65. credentials: dict[str, Any] = Field(default_factory=dict)
  66. parameters: dict[str, Any] = Field(default_factory=dict)
  67. stop: list[str] = Field(default_factory=list)
  68. # pydantic configs
  69. model_config = ConfigDict(protected_namespaces=())
  70. class AppGenerateEntity(BaseModel):
  71. """
  72. App Generate Entity.
  73. """
  74. model_config = ConfigDict(arbitrary_types_allowed=True)
  75. task_id: str
  76. # app config
  77. app_config: Any
  78. file_upload_config: Optional[FileUploadConfig] = None
  79. inputs: Mapping[str, Any]
  80. files: Sequence[File]
  81. user_id: str
  82. # extras
  83. stream: bool
  84. invoke_from: InvokeFrom
  85. # invoke call depth
  86. call_depth: int = 0
  87. # extra parameters, like: auto_generate_conversation_name
  88. extras: dict[str, Any] = Field(default_factory=dict)
  89. # tracing instance
  90. # Using Any to avoid circular import with TraceQueueManager
  91. trace_manager: Optional[Any] = None
  92. class EasyUIBasedAppGenerateEntity(AppGenerateEntity):
  93. """
  94. Chat Application Generate Entity.
  95. """
  96. # app config
  97. app_config: EasyUIBasedAppConfig
  98. model_conf: ModelConfigWithCredentialsEntity
  99. query: Optional[str] = None
  100. # pydantic configs
  101. model_config = ConfigDict(protected_namespaces=())
  102. class ConversationAppGenerateEntity(AppGenerateEntity):
  103. """
  104. Base entity for conversation-based app generation.
  105. """
  106. conversation_id: Optional[str] = None
  107. parent_message_id: Optional[str] = Field(
  108. default=None,
  109. description=(
  110. "Starting from v0.9.0, parent_message_id is used to support message regeneration for internal chat API."
  111. "For service API, we need to ensure its forward compatibility, "
  112. "so passing in the parent_message_id as request arg is not supported for now. "
  113. "It needs to be set to UUID_NIL so that the subsequent processing will treat it as legacy messages."
  114. ),
  115. )
  116. @field_validator("parent_message_id")
  117. @classmethod
  118. def validate_parent_message_id(cls, v, info: ValidationInfo):
  119. if info.data.get("invoke_from") == InvokeFrom.SERVICE_API and v != UUID_NIL:
  120. raise ValueError("parent_message_id should be UUID_NIL for service API")
  121. return v
  122. class ChatAppGenerateEntity(ConversationAppGenerateEntity, EasyUIBasedAppGenerateEntity):
  123. """
  124. Chat Application Generate Entity.
  125. """
  126. pass
  127. class CompletionAppGenerateEntity(EasyUIBasedAppGenerateEntity):
  128. """
  129. Completion Application Generate Entity.
  130. """
  131. pass
  132. class AgentChatAppGenerateEntity(ConversationAppGenerateEntity, EasyUIBasedAppGenerateEntity):
  133. """
  134. Agent Chat Application Generate Entity.
  135. """
  136. pass
  137. class AdvancedChatAppGenerateEntity(ConversationAppGenerateEntity):
  138. """
  139. Advanced Chat Application Generate Entity.
  140. """
  141. # app config
  142. app_config: WorkflowUIBasedAppConfig
  143. workflow_run_id: Optional[str] = None
  144. query: str
  145. class SingleIterationRunEntity(BaseModel):
  146. """
  147. Single Iteration Run Entity.
  148. """
  149. node_id: str
  150. inputs: Mapping
  151. single_iteration_run: Optional[SingleIterationRunEntity] = None
  152. class SingleLoopRunEntity(BaseModel):
  153. """
  154. Single Loop Run Entity.
  155. """
  156. node_id: str
  157. inputs: Mapping
  158. single_loop_run: Optional[SingleLoopRunEntity] = None
  159. class WorkflowAppGenerateEntity(AppGenerateEntity):
  160. """
  161. Workflow Application Generate Entity.
  162. """
  163. # app config
  164. app_config: WorkflowUIBasedAppConfig
  165. workflow_execution_id: str
  166. class SingleIterationRunEntity(BaseModel):
  167. """
  168. Single Iteration Run Entity.
  169. """
  170. node_id: str
  171. inputs: dict
  172. single_iteration_run: Optional[SingleIterationRunEntity] = None
  173. class SingleLoopRunEntity(BaseModel):
  174. """
  175. Single Loop Run Entity.
  176. """
  177. node_id: str
  178. inputs: dict
  179. single_loop_run: Optional[SingleLoopRunEntity] = None