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.

model_manager.py 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. import logging
  2. from collections.abc import Callable, Generator, Iterable, Sequence
  3. from typing import IO, Any, Literal, Optional, Union, cast, overload
  4. from configs import dify_config
  5. from core.entities.embedding_type import EmbeddingInputType
  6. from core.entities.provider_configuration import ProviderConfiguration, ProviderModelBundle
  7. from core.entities.provider_entities import ModelLoadBalancingConfiguration
  8. from core.errors.error import ProviderTokenNotInitError
  9. from core.model_runtime.callbacks.base_callback import Callback
  10. from core.model_runtime.entities.llm_entities import LLMResult
  11. from core.model_runtime.entities.message_entities import PromptMessage, PromptMessageTool
  12. from core.model_runtime.entities.model_entities import ModelType
  13. from core.model_runtime.entities.rerank_entities import RerankResult
  14. from core.model_runtime.entities.text_embedding_entities import TextEmbeddingResult
  15. from core.model_runtime.errors.invoke import InvokeAuthorizationError, InvokeConnectionError, InvokeRateLimitError
  16. from core.model_runtime.model_providers.__base.large_language_model import LargeLanguageModel
  17. from core.model_runtime.model_providers.__base.moderation_model import ModerationModel
  18. from core.model_runtime.model_providers.__base.rerank_model import RerankModel
  19. from core.model_runtime.model_providers.__base.speech2text_model import Speech2TextModel
  20. from core.model_runtime.model_providers.__base.text_embedding_model import TextEmbeddingModel
  21. from core.model_runtime.model_providers.__base.tts_model import TTSModel
  22. from core.provider_manager import ProviderManager
  23. from extensions.ext_redis import redis_client
  24. from models.provider import ProviderType
  25. from services.enterprise.plugin_manager_service import PluginCredentialType
  26. logger = logging.getLogger(__name__)
  27. class ModelInstance:
  28. """
  29. Model instance class
  30. """
  31. def __init__(self, provider_model_bundle: ProviderModelBundle, model: str):
  32. self.provider_model_bundle = provider_model_bundle
  33. self.model = model
  34. self.provider = provider_model_bundle.configuration.provider.provider
  35. self.credentials = self._fetch_credentials_from_bundle(provider_model_bundle, model)
  36. self.model_type_instance = self.provider_model_bundle.model_type_instance
  37. self.load_balancing_manager = self._get_load_balancing_manager(
  38. configuration=provider_model_bundle.configuration,
  39. model_type=provider_model_bundle.model_type_instance.model_type,
  40. model=model,
  41. credentials=self.credentials,
  42. )
  43. @staticmethod
  44. def _fetch_credentials_from_bundle(provider_model_bundle: ProviderModelBundle, model: str):
  45. """
  46. Fetch credentials from provider model bundle
  47. :param provider_model_bundle: provider model bundle
  48. :param model: model name
  49. :return:
  50. """
  51. configuration = provider_model_bundle.configuration
  52. model_type = provider_model_bundle.model_type_instance.model_type
  53. credentials = configuration.get_current_credentials(model_type=model_type, model=model)
  54. if credentials is None:
  55. raise ProviderTokenNotInitError(f"Model {model} credentials is not initialized.")
  56. return credentials
  57. @staticmethod
  58. def _get_load_balancing_manager(
  59. configuration: ProviderConfiguration, model_type: ModelType, model: str, credentials: dict
  60. ) -> Optional["LBModelManager"]:
  61. """
  62. Get load balancing model credentials
  63. :param configuration: provider configuration
  64. :param model_type: model type
  65. :param model: model name
  66. :param credentials: model credentials
  67. :return:
  68. """
  69. if configuration.model_settings and configuration.using_provider_type == ProviderType.CUSTOM:
  70. current_model_setting = None
  71. # check if model is disabled by admin
  72. for model_setting in configuration.model_settings:
  73. if model_setting.model_type == model_type and model_setting.model == model:
  74. current_model_setting = model_setting
  75. break
  76. # check if load balancing is enabled
  77. if current_model_setting and current_model_setting.load_balancing_configs:
  78. # use load balancing proxy to choose credentials
  79. lb_model_manager = LBModelManager(
  80. tenant_id=configuration.tenant_id,
  81. provider=configuration.provider.provider,
  82. model_type=model_type,
  83. model=model,
  84. load_balancing_configs=current_model_setting.load_balancing_configs,
  85. managed_credentials=credentials if configuration.custom_configuration.provider else None,
  86. )
  87. return lb_model_manager
  88. return None
  89. @overload
  90. def invoke_llm(
  91. self,
  92. prompt_messages: Sequence[PromptMessage],
  93. model_parameters: Optional[dict] = None,
  94. tools: Sequence[PromptMessageTool] | None = None,
  95. stop: Optional[list[str]] = None,
  96. stream: Literal[True] = True,
  97. user: Optional[str] = None,
  98. callbacks: Optional[list[Callback]] = None,
  99. ) -> Generator: ...
  100. @overload
  101. def invoke_llm(
  102. self,
  103. prompt_messages: list[PromptMessage],
  104. model_parameters: Optional[dict] = None,
  105. tools: Sequence[PromptMessageTool] | None = None,
  106. stop: Optional[list[str]] = None,
  107. stream: Literal[False] = False,
  108. user: Optional[str] = None,
  109. callbacks: Optional[list[Callback]] = None,
  110. ) -> LLMResult: ...
  111. @overload
  112. def invoke_llm(
  113. self,
  114. prompt_messages: list[PromptMessage],
  115. model_parameters: Optional[dict] = None,
  116. tools: Sequence[PromptMessageTool] | None = None,
  117. stop: Optional[list[str]] = None,
  118. stream: bool = True,
  119. user: Optional[str] = None,
  120. callbacks: Optional[list[Callback]] = None,
  121. ) -> Union[LLMResult, Generator]: ...
  122. def invoke_llm(
  123. self,
  124. prompt_messages: Sequence[PromptMessage],
  125. model_parameters: Optional[dict] = None,
  126. tools: Sequence[PromptMessageTool] | None = None,
  127. stop: Optional[Sequence[str]] = None,
  128. stream: bool = True,
  129. user: Optional[str] = None,
  130. callbacks: Optional[list[Callback]] = None,
  131. ) -> Union[LLMResult, Generator]:
  132. """
  133. Invoke large language model
  134. :param prompt_messages: prompt messages
  135. :param model_parameters: model parameters
  136. :param tools: tools for tool calling
  137. :param stop: stop words
  138. :param stream: is stream response
  139. :param user: unique user id
  140. :param callbacks: callbacks
  141. :return: full response or stream response chunk generator result
  142. """
  143. if not isinstance(self.model_type_instance, LargeLanguageModel):
  144. raise Exception("Model type instance is not LargeLanguageModel")
  145. return cast(
  146. Union[LLMResult, Generator],
  147. self._round_robin_invoke(
  148. function=self.model_type_instance.invoke,
  149. model=self.model,
  150. credentials=self.credentials,
  151. prompt_messages=prompt_messages,
  152. model_parameters=model_parameters,
  153. tools=tools,
  154. stop=stop,
  155. stream=stream,
  156. user=user,
  157. callbacks=callbacks,
  158. ),
  159. )
  160. def get_llm_num_tokens(
  161. self, prompt_messages: Sequence[PromptMessage], tools: Optional[Sequence[PromptMessageTool]] = None
  162. ) -> int:
  163. """
  164. Get number of tokens for llm
  165. :param prompt_messages: prompt messages
  166. :param tools: tools for tool calling
  167. :return:
  168. """
  169. if not isinstance(self.model_type_instance, LargeLanguageModel):
  170. raise Exception("Model type instance is not LargeLanguageModel")
  171. return cast(
  172. int,
  173. self._round_robin_invoke(
  174. function=self.model_type_instance.get_num_tokens,
  175. model=self.model,
  176. credentials=self.credentials,
  177. prompt_messages=prompt_messages,
  178. tools=tools,
  179. ),
  180. )
  181. def invoke_text_embedding(
  182. self, texts: list[str], user: Optional[str] = None, input_type: EmbeddingInputType = EmbeddingInputType.DOCUMENT
  183. ) -> TextEmbeddingResult:
  184. """
  185. Invoke large language model
  186. :param texts: texts to embed
  187. :param user: unique user id
  188. :param input_type: input type
  189. :return: embeddings result
  190. """
  191. if not isinstance(self.model_type_instance, TextEmbeddingModel):
  192. raise Exception("Model type instance is not TextEmbeddingModel")
  193. return cast(
  194. TextEmbeddingResult,
  195. self._round_robin_invoke(
  196. function=self.model_type_instance.invoke,
  197. model=self.model,
  198. credentials=self.credentials,
  199. texts=texts,
  200. user=user,
  201. input_type=input_type,
  202. ),
  203. )
  204. def get_text_embedding_num_tokens(self, texts: list[str]) -> list[int]:
  205. """
  206. Get number of tokens for text embedding
  207. :param texts: texts to embed
  208. :return:
  209. """
  210. if not isinstance(self.model_type_instance, TextEmbeddingModel):
  211. raise Exception("Model type instance is not TextEmbeddingModel")
  212. return cast(
  213. list[int],
  214. self._round_robin_invoke(
  215. function=self.model_type_instance.get_num_tokens,
  216. model=self.model,
  217. credentials=self.credentials,
  218. texts=texts,
  219. ),
  220. )
  221. def invoke_rerank(
  222. self,
  223. query: str,
  224. docs: list[str],
  225. score_threshold: Optional[float] = None,
  226. top_n: Optional[int] = None,
  227. user: Optional[str] = None,
  228. ) -> RerankResult:
  229. """
  230. Invoke rerank model
  231. :param query: search query
  232. :param docs: docs for reranking
  233. :param score_threshold: score threshold
  234. :param top_n: top n
  235. :param user: unique user id
  236. :return: rerank result
  237. """
  238. if not isinstance(self.model_type_instance, RerankModel):
  239. raise Exception("Model type instance is not RerankModel")
  240. return cast(
  241. RerankResult,
  242. self._round_robin_invoke(
  243. function=self.model_type_instance.invoke,
  244. model=self.model,
  245. credentials=self.credentials,
  246. query=query,
  247. docs=docs,
  248. score_threshold=score_threshold,
  249. top_n=top_n,
  250. user=user,
  251. ),
  252. )
  253. def invoke_moderation(self, text: str, user: Optional[str] = None) -> bool:
  254. """
  255. Invoke moderation model
  256. :param text: text to moderate
  257. :param user: unique user id
  258. :return: false if text is safe, true otherwise
  259. """
  260. if not isinstance(self.model_type_instance, ModerationModel):
  261. raise Exception("Model type instance is not ModerationModel")
  262. return cast(
  263. bool,
  264. self._round_robin_invoke(
  265. function=self.model_type_instance.invoke,
  266. model=self.model,
  267. credentials=self.credentials,
  268. text=text,
  269. user=user,
  270. ),
  271. )
  272. def invoke_speech2text(self, file: IO[bytes], user: Optional[str] = None) -> str:
  273. """
  274. Invoke large language model
  275. :param file: audio file
  276. :param user: unique user id
  277. :return: text for given audio file
  278. """
  279. if not isinstance(self.model_type_instance, Speech2TextModel):
  280. raise Exception("Model type instance is not Speech2TextModel")
  281. return cast(
  282. str,
  283. self._round_robin_invoke(
  284. function=self.model_type_instance.invoke,
  285. model=self.model,
  286. credentials=self.credentials,
  287. file=file,
  288. user=user,
  289. ),
  290. )
  291. def invoke_tts(self, content_text: str, tenant_id: str, voice: str, user: Optional[str] = None) -> Iterable[bytes]:
  292. """
  293. Invoke large language tts model
  294. :param content_text: text content to be translated
  295. :param tenant_id: user tenant id
  296. :param voice: model timbre
  297. :param user: unique user id
  298. :return: text for given audio file
  299. """
  300. if not isinstance(self.model_type_instance, TTSModel):
  301. raise Exception("Model type instance is not TTSModel")
  302. return cast(
  303. Iterable[bytes],
  304. self._round_robin_invoke(
  305. function=self.model_type_instance.invoke,
  306. model=self.model,
  307. credentials=self.credentials,
  308. content_text=content_text,
  309. user=user,
  310. tenant_id=tenant_id,
  311. voice=voice,
  312. ),
  313. )
  314. def _round_robin_invoke(self, function: Callable[..., Any], *args, **kwargs):
  315. """
  316. Round-robin invoke
  317. :param function: function to invoke
  318. :param args: function args
  319. :param kwargs: function kwargs
  320. :return:
  321. """
  322. if not self.load_balancing_manager:
  323. return function(*args, **kwargs)
  324. last_exception: Union[InvokeRateLimitError, InvokeAuthorizationError, InvokeConnectionError, None] = None
  325. while True:
  326. lb_config = self.load_balancing_manager.fetch_next()
  327. if not lb_config:
  328. if not last_exception:
  329. raise ProviderTokenNotInitError("Model credentials is not initialized.")
  330. else:
  331. raise last_exception
  332. # Additional policy compliance check as fallback (in case fetch_next didn't catch it)
  333. try:
  334. from core.helper.credential_utils import check_credential_policy_compliance
  335. if lb_config.credential_id:
  336. check_credential_policy_compliance(
  337. credential_id=lb_config.credential_id,
  338. provider=self.provider,
  339. credential_type=PluginCredentialType.MODEL,
  340. )
  341. except Exception as e:
  342. logger.warning(
  343. "Load balancing config %s failed policy compliance check in round-robin: %s", lb_config.id, str(e)
  344. )
  345. self.load_balancing_manager.cooldown(lb_config, expire=60)
  346. continue
  347. try:
  348. if "credentials" in kwargs:
  349. del kwargs["credentials"]
  350. return function(*args, **kwargs, credentials=lb_config.credentials)
  351. except InvokeRateLimitError as e:
  352. # expire in 60 seconds
  353. self.load_balancing_manager.cooldown(lb_config, expire=60)
  354. last_exception = e
  355. continue
  356. except (InvokeAuthorizationError, InvokeConnectionError) as e:
  357. # expire in 10 seconds
  358. self.load_balancing_manager.cooldown(lb_config, expire=10)
  359. last_exception = e
  360. continue
  361. except Exception as e:
  362. raise e
  363. def get_tts_voices(self, language: Optional[str] = None):
  364. """
  365. Invoke large language tts model voices
  366. :param language: tts language
  367. :return: tts model voices
  368. """
  369. if not isinstance(self.model_type_instance, TTSModel):
  370. raise Exception("Model type instance is not TTSModel")
  371. return self.model_type_instance.get_tts_model_voices(
  372. model=self.model, credentials=self.credentials, language=language
  373. )
  374. class ModelManager:
  375. def __init__(self):
  376. self._provider_manager = ProviderManager()
  377. def get_model_instance(self, tenant_id: str, provider: str, model_type: ModelType, model: str) -> ModelInstance:
  378. """
  379. Get model instance
  380. :param tenant_id: tenant id
  381. :param provider: provider name
  382. :param model_type: model type
  383. :param model: model name
  384. :return:
  385. """
  386. if not provider:
  387. return self.get_default_model_instance(tenant_id, model_type)
  388. provider_model_bundle = self._provider_manager.get_provider_model_bundle(
  389. tenant_id=tenant_id, provider=provider, model_type=model_type
  390. )
  391. return ModelInstance(provider_model_bundle, model)
  392. def get_default_provider_model_name(self, tenant_id: str, model_type: ModelType) -> tuple[str | None, str | None]:
  393. """
  394. Return first provider and the first model in the provider
  395. :param tenant_id: tenant id
  396. :param model_type: model type
  397. :return: provider name, model name
  398. """
  399. return self._provider_manager.get_first_provider_first_model(tenant_id, model_type)
  400. def get_default_model_instance(self, tenant_id: str, model_type: ModelType) -> ModelInstance:
  401. """
  402. Get default model instance
  403. :param tenant_id: tenant id
  404. :param model_type: model type
  405. :return:
  406. """
  407. default_model_entity = self._provider_manager.get_default_model(tenant_id=tenant_id, model_type=model_type)
  408. if not default_model_entity:
  409. raise ProviderTokenNotInitError(f"Default model not found for {model_type}")
  410. return self.get_model_instance(
  411. tenant_id=tenant_id,
  412. provider=default_model_entity.provider.provider,
  413. model_type=model_type,
  414. model=default_model_entity.model,
  415. )
  416. class LBModelManager:
  417. def __init__(
  418. self,
  419. tenant_id: str,
  420. provider: str,
  421. model_type: ModelType,
  422. model: str,
  423. load_balancing_configs: list[ModelLoadBalancingConfiguration],
  424. managed_credentials: Optional[dict] = None,
  425. ):
  426. """
  427. Load balancing model manager
  428. :param tenant_id: tenant_id
  429. :param provider: provider
  430. :param model_type: model_type
  431. :param model: model name
  432. :param load_balancing_configs: all load balancing configurations
  433. :param managed_credentials: credentials if load balancing configuration name is __inherit__
  434. """
  435. self._tenant_id = tenant_id
  436. self._provider = provider
  437. self._model_type = model_type
  438. self._model = model
  439. self._load_balancing_configs = load_balancing_configs
  440. for load_balancing_config in self._load_balancing_configs[:]: # Iterate over a shallow copy of the list
  441. if load_balancing_config.name == "__inherit__":
  442. if not managed_credentials:
  443. # remove __inherit__ if managed credentials is not provided
  444. self._load_balancing_configs.remove(load_balancing_config)
  445. else:
  446. load_balancing_config.credentials = managed_credentials
  447. def fetch_next(self) -> Optional[ModelLoadBalancingConfiguration]:
  448. """
  449. Get next model load balancing config
  450. Strategy: Round Robin
  451. :return:
  452. """
  453. cache_key = "model_lb_index:{}:{}:{}:{}".format(
  454. self._tenant_id, self._provider, self._model_type.value, self._model
  455. )
  456. cooldown_load_balancing_configs = []
  457. max_index = len(self._load_balancing_configs)
  458. while True:
  459. current_index = redis_client.incr(cache_key)
  460. current_index = cast(int, current_index)
  461. if current_index >= 10000000:
  462. current_index = 1
  463. redis_client.set(cache_key, current_index)
  464. redis_client.expire(cache_key, 3600)
  465. if current_index > max_index:
  466. current_index = current_index % max_index
  467. real_index = current_index - 1
  468. if real_index > max_index:
  469. real_index = 0
  470. config: ModelLoadBalancingConfiguration = self._load_balancing_configs[real_index]
  471. if self.in_cooldown(config):
  472. cooldown_load_balancing_configs.append(config)
  473. if len(cooldown_load_balancing_configs) >= len(self._load_balancing_configs):
  474. # all configs are in cooldown
  475. return None
  476. continue
  477. # Check policy compliance for the selected configuration
  478. try:
  479. from core.helper.credential_utils import check_credential_policy_compliance
  480. if config.credential_id:
  481. check_credential_policy_compliance(
  482. credential_id=config.credential_id,
  483. provider=self._provider,
  484. credential_type=PluginCredentialType.MODEL,
  485. )
  486. except Exception as e:
  487. logger.warning("Load balancing config %s failed policy compliance check: %s", config.id, str(e))
  488. cooldown_load_balancing_configs.append(config)
  489. if len(cooldown_load_balancing_configs) >= len(self._load_balancing_configs):
  490. # all configs are in cooldown or failed policy compliance
  491. return None
  492. continue
  493. if dify_config.DEBUG:
  494. logger.info(
  495. """Model LB
  496. id: %s
  497. name:%s
  498. tenant_id: %s
  499. provider: %s
  500. model_type: %s
  501. model: %s""",
  502. config.id,
  503. config.name,
  504. self._tenant_id,
  505. self._provider,
  506. self._model_type.value,
  507. self._model,
  508. )
  509. return config
  510. def cooldown(self, config: ModelLoadBalancingConfiguration, expire: int = 60):
  511. """
  512. Cooldown model load balancing config
  513. :param config: model load balancing config
  514. :param expire: cooldown time
  515. :return:
  516. """
  517. cooldown_cache_key = "model_lb_index:cooldown:{}:{}:{}:{}:{}".format(
  518. self._tenant_id, self._provider, self._model_type.value, self._model, config.id
  519. )
  520. redis_client.setex(cooldown_cache_key, expire, "true")
  521. def in_cooldown(self, config: ModelLoadBalancingConfiguration) -> bool:
  522. """
  523. Check if model load balancing config is in cooldown
  524. :param config: model load balancing config
  525. :return:
  526. """
  527. cooldown_cache_key = "model_lb_index:cooldown:{}:{}:{}:{}:{}".format(
  528. self._tenant_id, self._provider, self._model_type.value, self._model, config.id
  529. )
  530. res: bool = redis_client.exists(cooldown_cache_key)
  531. return res
  532. @staticmethod
  533. def get_config_in_cooldown_and_ttl(
  534. tenant_id: str, provider: str, model_type: ModelType, model: str, config_id: str
  535. ) -> tuple[bool, int]:
  536. """
  537. Get model load balancing config is in cooldown and ttl
  538. :param tenant_id: workspace id
  539. :param provider: provider name
  540. :param model_type: model type
  541. :param model: model name
  542. :param config_id: model load balancing config id
  543. :return:
  544. """
  545. cooldown_cache_key = "model_lb_index:cooldown:{}:{}:{}:{}:{}".format(
  546. tenant_id, provider, model_type.value, model, config_id
  547. )
  548. ttl = redis_client.ttl(cooldown_cache_key)
  549. if ttl == -2:
  550. return False, 0
  551. ttl = cast(int, ttl)
  552. return True, ttl