plugin_migration.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import datetime
  2. import json
  3. import logging
  4. from collections.abc import Sequence
  5. import click
  6. from sqlalchemy.orm import Session
  7. from core.agent.entities import AgentToolEntity
  8. from core.entities import DEFAULT_PLUGIN_ID
  9. from core.tools.entities.tool_entities import ToolProviderType
  10. from models.account import Tenant
  11. from models.engine import db
  12. from models.model import App, AppMode, AppModelConfig
  13. from models.tools import BuiltinToolProvider
  14. from models.workflow import Workflow
  15. logger = logging.getLogger(__name__)
  16. excluded_providers = ["time", "audio", "code", "webscraper"]
  17. class PluginMigration:
  18. @classmethod
  19. def extract_plugins(cls, filepath: str) -> None:
  20. """
  21. Migrate plugin.
  22. """
  23. click.echo(click.style("Migrating models/tools to new plugin Mechanism", fg="white"))
  24. ended_at = datetime.datetime.now()
  25. started_at = datetime.datetime(2023, 4, 3, 8, 59, 24)
  26. current_time = started_at
  27. with Session(db.engine) as session:
  28. total_tenant_count = session.query(Tenant.id).count()
  29. handled_tenant_count = 0
  30. while current_time < ended_at:
  31. # Initial interval of 1 day, will be dynamically adjusted based on tenant count
  32. interval = datetime.timedelta(days=1)
  33. # Process tenants in this batch
  34. with Session(db.engine) as session:
  35. # Calculate tenant count in next batch with current interval
  36. # Try different intervals until we find one with a reasonable tenant count
  37. test_intervals = [
  38. datetime.timedelta(days=1),
  39. datetime.timedelta(hours=12),
  40. datetime.timedelta(hours=6),
  41. datetime.timedelta(hours=3),
  42. datetime.timedelta(hours=1),
  43. ]
  44. for test_interval in test_intervals:
  45. tenant_count = (
  46. session.query(Tenant.id)
  47. .filter(Tenant.created_at.between(current_time, current_time + test_interval))
  48. .count()
  49. )
  50. if tenant_count <= 100:
  51. interval = test_interval
  52. break
  53. else:
  54. # If all intervals have too many tenants, use minimum interval
  55. interval = datetime.timedelta(hours=1)
  56. # Adjust interval to target ~100 tenants per batch
  57. if tenant_count > 0:
  58. # Scale interval based on ratio to target count
  59. interval = min(
  60. datetime.timedelta(days=1), # Max 1 day
  61. max(
  62. datetime.timedelta(hours=1), # Min 1 hour
  63. interval * (100 / tenant_count), # Scale to target 100
  64. ),
  65. )
  66. batch_end = min(current_time + interval, ended_at)
  67. rs = (
  68. session.query(Tenant.id)
  69. .filter(Tenant.created_at.between(current_time, batch_end))
  70. .order_by(Tenant.created_at)
  71. )
  72. tenants = []
  73. for row in rs:
  74. tenant_id = str(row.id)
  75. try:
  76. tenants.append(tenant_id)
  77. except Exception:
  78. logger.exception(f"Failed to process tenant {tenant_id}")
  79. continue
  80. for tenant_id in tenants:
  81. plugins = cls.extract_installed_plugin_ids(tenant_id)
  82. # append to file, it's a jsonl file
  83. with open(filepath, "a") as f:
  84. f.write(json.dumps({"tenant_id": tenant_id, "plugins": plugins}) + "\n")
  85. handled_tenant_count += len(tenants)
  86. click.echo(
  87. click.style(
  88. f"Processed {handled_tenant_count} tenants "
  89. f"({(handled_tenant_count / total_tenant_count) * 100:.1f}%), "
  90. f"{handled_tenant_count}/{total_tenant_count}",
  91. fg="green",
  92. )
  93. )
  94. current_time = batch_end
  95. @classmethod
  96. def extract_installed_plugin_ids(cls, tenant_id: str) -> Sequence[str]:
  97. """
  98. Extract installed plugin ids.
  99. """
  100. tools = cls.extract_tool_tables(tenant_id)
  101. models = cls.extract_model_tables(tenant_id)
  102. workflows = cls.extract_workflow_tables(tenant_id)
  103. apps = cls.extract_app_tables(tenant_id)
  104. return list({*tools, *models, *workflows, *apps})
  105. @classmethod
  106. def extract_model_tables(cls, tenant_id: str) -> Sequence[str]:
  107. """
  108. Extract model tables.
  109. NOTE: rename google to gemini
  110. """
  111. models = []
  112. table_pairs = [
  113. ("providers", "provider_name"),
  114. ("provider_models", "provider_name"),
  115. ("provider_orders", "provider_name"),
  116. ("tenant_default_models", "provider_name"),
  117. ("tenant_preferred_model_providers", "provider_name"),
  118. ("provider_model_settings", "provider_name"),
  119. ("load_balancing_model_configs", "provider_name"),
  120. ]
  121. for table, column in table_pairs:
  122. models.extend(cls.extract_model_table(tenant_id, table, column))
  123. # duplicate models
  124. models = list(set(models))
  125. return models
  126. @classmethod
  127. def extract_model_table(cls, tenant_id: str, table: str, column: str) -> Sequence[str]:
  128. """
  129. Extract model table.
  130. """
  131. with Session(db.engine) as session:
  132. rs = session.execute(
  133. db.text(f"SELECT DISTINCT {column} FROM {table} WHERE tenant_id = :tenant_id"), {"tenant_id": tenant_id}
  134. )
  135. result = []
  136. for row in rs:
  137. provider_name = str(row[0])
  138. if provider_name and "/" not in provider_name:
  139. if provider_name == "google":
  140. provider_name = "gemini"
  141. result.append(DEFAULT_PLUGIN_ID + "/" + provider_name + "/" + provider_name)
  142. elif provider_name:
  143. result.append(provider_name)
  144. return result
  145. @classmethod
  146. def extract_tool_tables(cls, tenant_id: str) -> Sequence[str]:
  147. """
  148. Extract tool tables.
  149. """
  150. with Session(db.engine) as session:
  151. rs = session.query(BuiltinToolProvider).filter(BuiltinToolProvider.tenant_id == tenant_id).all()
  152. result = []
  153. for row in rs:
  154. if "/" not in row.provider:
  155. result.append(DEFAULT_PLUGIN_ID + "/" + row.provider + "/" + row.provider)
  156. else:
  157. result.append(row.provider)
  158. return result
  159. @classmethod
  160. def _handle_builtin_tool_provider(cls, provider_name: str) -> str:
  161. """
  162. Handle builtin tool provider.
  163. """
  164. if provider_name == "jina":
  165. provider_name = "jina_tool"
  166. elif provider_name == "siliconflow":
  167. provider_name = "siliconflow_tool"
  168. elif provider_name == "stepfun":
  169. provider_name = "stepfun_tool"
  170. if "/" not in provider_name:
  171. return DEFAULT_PLUGIN_ID + "/" + provider_name + "/" + provider_name
  172. else:
  173. return provider_name
  174. @classmethod
  175. def extract_workflow_tables(cls, tenant_id: str) -> Sequence[str]:
  176. """
  177. Extract workflow tables, only ToolNode is required.
  178. """
  179. with Session(db.engine) as session:
  180. rs = session.query(Workflow).filter(Workflow.tenant_id == tenant_id).all()
  181. result = []
  182. for row in rs:
  183. graph = row.graph_dict
  184. # get nodes
  185. nodes = graph.get("nodes", [])
  186. for node in nodes:
  187. data = node.get("data", {})
  188. if data.get("type") == "tool":
  189. provider_name = data.get("provider_name")
  190. provider_type = data.get("provider_type")
  191. if provider_name not in excluded_providers and provider_type == ToolProviderType.BUILT_IN.value:
  192. provider_name = cls._handle_builtin_tool_provider(provider_name)
  193. result.append(provider_name)
  194. return result
  195. @classmethod
  196. def extract_app_tables(cls, tenant_id: str) -> Sequence[str]:
  197. """
  198. Extract app tables.
  199. """
  200. with Session(db.engine) as session:
  201. apps = session.query(App).filter(App.tenant_id == tenant_id).all()
  202. if not apps:
  203. return []
  204. agent_app_model_config_ids = [
  205. app.app_model_config_id for app in apps if app.is_agent or app.mode == AppMode.AGENT_CHAT.value
  206. ]
  207. rs = session.query(AppModelConfig).filter(AppModelConfig.id.in_(agent_app_model_config_ids)).all()
  208. result = []
  209. for row in rs:
  210. agent_config = row.agent_mode_dict
  211. if "tools" in agent_config and isinstance(agent_config["tools"], list):
  212. for tool in agent_config["tools"]:
  213. if isinstance(tool, dict):
  214. try:
  215. tool_entity = AgentToolEntity(**tool)
  216. if (
  217. tool_entity.provider_type == ToolProviderType.BUILT_IN.value
  218. and tool_entity.provider_id not in excluded_providers
  219. ):
  220. result.append(cls._handle_builtin_tool_provider(tool_entity.provider_id))
  221. except Exception:
  222. logger.exception(f"Failed to process tool {tool}")
  223. continue
  224. return result